clang  19.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"
21 #include "clang/AST/Mangle.h"
23 #include "clang/AST/TypeLoc.h"
25 #include "clang/Basic/TargetInfo.h"
28 #include "clang/Sema/Lookup.h"
29 #include "clang/Sema/ScopeInfo.h"
30 #include "clang/Sema/SemaCUDA.h"
32 #include "clang/Sema/SemaObjC.h"
33 #include "clang/Sema/SemaOpenMP.h"
34 #include "clang/Sema/Template.h"
36 #include "llvm/Support/TimeProfiler.h"
37 #include <optional>
38 
39 using namespace clang;
40 
41 static bool isDeclWithinFunction(const Decl *D) {
42  const DeclContext *DC = D->getDeclContext();
43  if (DC->isFunctionOrMethod())
44  return true;
45 
46  if (DC->isRecord())
47  return cast<CXXRecordDecl>(DC)->isLocalClass();
48 
49  return false;
50 }
51 
52 template<typename DeclT>
53 static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
54  const MultiLevelTemplateArgumentList &TemplateArgs) {
55  if (!OldDecl->getQualifierLoc())
56  return false;
57 
58  assert((NewDecl->getFriendObjectKind() ||
59  !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
60  "non-friend with qualified name defined in dependent context");
61  Sema::ContextRAII SavedContext(
62  SemaRef,
63  const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
64  ? NewDecl->getLexicalDeclContext()
65  : OldDecl->getLexicalDeclContext()));
66 
67  NestedNameSpecifierLoc NewQualifierLoc
68  = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
69  TemplateArgs);
70 
71  if (!NewQualifierLoc)
72  return true;
73 
74  NewDecl->setQualifierInfo(NewQualifierLoc);
75  return false;
76 }
77 
79  DeclaratorDecl *NewDecl) {
80  return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
81 }
82 
84  TagDecl *NewDecl) {
85  return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
86 }
87 
88 // Include attribute instantiation code.
89 #include "clang/Sema/AttrTemplateInstantiate.inc"
90 
92  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
93  const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
94  if (Aligned->isAlignmentExpr()) {
95  // The alignment expression is a constant expression.
98  ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
99  if (!Result.isInvalid())
100  S.AddAlignedAttr(New, *Aligned, Result.getAs<Expr>(), IsPackExpansion);
101  } else {
102  if (TypeSourceInfo *Result =
103  S.SubstType(Aligned->getAlignmentType(), TemplateArgs,
104  Aligned->getLocation(), DeclarationName())) {
105  if (!S.CheckAlignasTypeArgument(Aligned->getSpelling(), Result,
106  Aligned->getLocation(),
107  Result->getTypeLoc().getSourceRange()))
108  S.AddAlignedAttr(New, *Aligned, Result, IsPackExpansion);
109  }
110  }
111 }
112 
114  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
115  const AlignedAttr *Aligned, Decl *New) {
116  if (!Aligned->isPackExpansion()) {
117  instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
118  return;
119  }
120 
122  if (Aligned->isAlignmentExpr())
123  S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
124  Unexpanded);
125  else
126  S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
127  Unexpanded);
128  assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
129 
130  // Determine whether we can expand this attribute pack yet.
131  bool Expand = true, RetainExpansion = false;
132  std::optional<unsigned> NumExpansions;
133  // FIXME: Use the actual location of the ellipsis.
134  SourceLocation EllipsisLoc = Aligned->getLocation();
135  if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
136  Unexpanded, TemplateArgs, Expand,
137  RetainExpansion, NumExpansions))
138  return;
139 
140  if (!Expand) {
141  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
142  instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
143  } else {
144  for (unsigned I = 0; I != *NumExpansions; ++I) {
146  instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
147  }
148  }
149 }
150 
152  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
153  const AssumeAlignedAttr *Aligned, Decl *New) {
154  // The alignment expression is a constant expression.
157 
158  Expr *E, *OE = nullptr;
159  ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
160  if (Result.isInvalid())
161  return;
162  E = Result.getAs<Expr>();
163 
164  if (Aligned->getOffset()) {
165  Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
166  if (Result.isInvalid())
167  return;
168  OE = Result.getAs<Expr>();
169  }
170 
171  S.AddAssumeAlignedAttr(New, *Aligned, E, OE);
172 }
173 
175  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
176  const AlignValueAttr *Aligned, Decl *New) {
177  // The alignment expression is a constant expression.
180  ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
181  if (!Result.isInvalid())
182  S.AddAlignValueAttr(New, *Aligned, Result.getAs<Expr>());
183 }
184 
186  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
187  const AllocAlignAttr *Align, Decl *New) {
188  Expr *Param = IntegerLiteral::Create(
189  S.getASTContext(),
190  llvm::APInt(64, Align->getParamIndex().getSourceIndex()),
191  S.getASTContext().UnsignedLongLongTy, Align->getLocation());
192  S.AddAllocAlignAttr(New, *Align, Param);
193 }
194 
196  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
197  const AnnotateAttr *Attr, Decl *New) {
200 
201  // If the attribute has delayed arguments it will have to instantiate those
202  // and handle them as new arguments for the attribute.
203  bool HasDelayedArgs = Attr->delayedArgs_size();
204 
205  ArrayRef<Expr *> ArgsToInstantiate =
206  HasDelayedArgs
207  ? ArrayRef<Expr *>{Attr->delayedArgs_begin(), Attr->delayedArgs_end()}
208  : ArrayRef<Expr *>{Attr->args_begin(), Attr->args_end()};
209 
211  if (S.SubstExprs(ArgsToInstantiate,
212  /*IsCall=*/false, TemplateArgs, Args))
213  return;
214 
215  StringRef Str = Attr->getAnnotation();
216  if (HasDelayedArgs) {
217  if (Args.size() < 1) {
218  S.Diag(Attr->getLoc(), diag::err_attribute_too_few_arguments)
219  << Attr << 1;
220  return;
221  }
222 
223  if (!S.checkStringLiteralArgumentAttr(*Attr, Args[0], Str))
224  return;
225 
226  llvm::SmallVector<Expr *, 4> ActualArgs;
227  ActualArgs.insert(ActualArgs.begin(), Args.begin() + 1, Args.end());
228  std::swap(Args, ActualArgs);
229  }
230  S.AddAnnotationAttr(New, *Attr, Str, Args);
231 }
232 
234  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
235  const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) {
236  Expr *Cond = nullptr;
237  {
238  Sema::ContextRAII SwitchContext(S, New);
241  ExprResult Result = S.SubstExpr(OldCond, TemplateArgs);
242  if (Result.isInvalid())
243  return nullptr;
244  Cond = Result.getAs<Expr>();
245  }
246  if (!Cond->isTypeDependent()) {
247  ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
248  if (Converted.isInvalid())
249  return nullptr;
250  Cond = Converted.get();
251  }
252 
254  if (OldCond->isValueDependent() && !Cond->isValueDependent() &&
255  !Expr::isPotentialConstantExprUnevaluated(Cond, New, Diags)) {
256  S.Diag(A->getLocation(), diag::err_attr_cond_never_constant_expr) << A;
257  for (const auto &P : Diags)
258  S.Diag(P.first, P.second);
259  return nullptr;
260  }
261  return Cond;
262 }
263 
265  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
266  const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) {
268  S, TemplateArgs, EIA, EIA->getCond(), Tmpl, New);
269 
270  if (Cond)
271  New->addAttr(new (S.getASTContext()) EnableIfAttr(S.getASTContext(), *EIA,
272  Cond, EIA->getMessage()));
273 }
274 
276  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
277  const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) {
279  S, TemplateArgs, DIA, DIA->getCond(), Tmpl, New);
280 
281  if (Cond)
282  New->addAttr(new (S.getASTContext()) DiagnoseIfAttr(
283  S.getASTContext(), *DIA, Cond, DIA->getMessage(),
284  DIA->getDiagnosticType(), DIA->getArgDependent(), New));
285 }
286 
287 // Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
288 // template A as the base and arguments from TemplateArgs.
290  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
291  const CUDALaunchBoundsAttr &Attr, Decl *New) {
292  // The alignment expression is a constant expression.
295 
296  ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
297  if (Result.isInvalid())
298  return;
299  Expr *MaxThreads = Result.getAs<Expr>();
300 
301  Expr *MinBlocks = nullptr;
302  if (Attr.getMinBlocks()) {
303  Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
304  if (Result.isInvalid())
305  return;
306  MinBlocks = Result.getAs<Expr>();
307  }
308 
309  Expr *MaxBlocks = nullptr;
310  if (Attr.getMaxBlocks()) {
311  Result = S.SubstExpr(Attr.getMaxBlocks(), TemplateArgs);
312  if (Result.isInvalid())
313  return;
314  MaxBlocks = Result.getAs<Expr>();
315  }
316 
317  S.AddLaunchBoundsAttr(New, Attr, MaxThreads, MinBlocks, MaxBlocks);
318 }
319 
320 static void
322  const MultiLevelTemplateArgumentList &TemplateArgs,
323  const ModeAttr &Attr, Decl *New) {
324  S.AddModeAttr(New, Attr, Attr.getMode(),
325  /*InInstantiation=*/true);
326 }
327 
328 /// Instantiation of 'declare simd' attribute and its arguments.
330  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
331  const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
332  // Allow 'this' in clauses with varlists.
333  if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
334  New = FTD->getTemplatedDecl();
335  auto *FD = cast<FunctionDecl>(New);
336  auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
337  SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
338  SmallVector<unsigned, 4> LinModifiers;
339 
340  auto SubstExpr = [&](Expr *E) -> ExprResult {
341  if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
342  if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
343  Sema::ContextRAII SavedContext(S, FD);
344  LocalInstantiationScope Local(S);
345  if (FD->getNumParams() > PVD->getFunctionScopeIndex())
346  Local.InstantiatedLocal(
347  PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
348  return S.SubstExpr(E, TemplateArgs);
349  }
350  Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
351  FD->isCXXInstanceMember());
352  return S.SubstExpr(E, TemplateArgs);
353  };
354 
355  // Substitute a single OpenMP clause, which is a potentially-evaluated
356  // full-expression.
357  auto Subst = [&](Expr *E) -> ExprResult {
360  ExprResult Res = SubstExpr(E);
361  if (Res.isInvalid())
362  return Res;
363  return S.ActOnFinishFullExpr(Res.get(), false);
364  };
365 
366  ExprResult Simdlen;
367  if (auto *E = Attr.getSimdlen())
368  Simdlen = Subst(E);
369 
370  if (Attr.uniforms_size() > 0) {
371  for(auto *E : Attr.uniforms()) {
372  ExprResult Inst = Subst(E);
373  if (Inst.isInvalid())
374  continue;
375  Uniforms.push_back(Inst.get());
376  }
377  }
378 
379  auto AI = Attr.alignments_begin();
380  for (auto *E : Attr.aligneds()) {
381  ExprResult Inst = Subst(E);
382  if (Inst.isInvalid())
383  continue;
384  Aligneds.push_back(Inst.get());
385  Inst = ExprEmpty();
386  if (*AI)
387  Inst = S.SubstExpr(*AI, TemplateArgs);
388  Alignments.push_back(Inst.get());
389  ++AI;
390  }
391 
392  auto SI = Attr.steps_begin();
393  for (auto *E : Attr.linears()) {
394  ExprResult Inst = Subst(E);
395  if (Inst.isInvalid())
396  continue;
397  Linears.push_back(Inst.get());
398  Inst = ExprEmpty();
399  if (*SI)
400  Inst = S.SubstExpr(*SI, TemplateArgs);
401  Steps.push_back(Inst.get());
402  ++SI;
403  }
404  LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
406  S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
407  Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
408  Attr.getRange());
409 }
410 
411 /// Instantiation of 'declare variant' attribute and its arguments.
413  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
414  const OMPDeclareVariantAttr &Attr, Decl *New) {
415  // Allow 'this' in clauses with varlists.
416  if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
417  New = FTD->getTemplatedDecl();
418  auto *FD = cast<FunctionDecl>(New);
419  auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
420 
421  auto &&SubstExpr = [FD, ThisContext, &S, &TemplateArgs](Expr *E) {
422  if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
423  if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
424  Sema::ContextRAII SavedContext(S, FD);
425  LocalInstantiationScope Local(S);
426  if (FD->getNumParams() > PVD->getFunctionScopeIndex())
427  Local.InstantiatedLocal(
428  PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
429  return S.SubstExpr(E, TemplateArgs);
430  }
431  Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
432  FD->isCXXInstanceMember());
433  return S.SubstExpr(E, TemplateArgs);
434  };
435 
436  // Substitute a single OpenMP clause, which is a potentially-evaluated
437  // full-expression.
438  auto &&Subst = [&SubstExpr, &S](Expr *E) {
441  ExprResult Res = SubstExpr(E);
442  if (Res.isInvalid())
443  return Res;
444  return S.ActOnFinishFullExpr(Res.get(), false);
445  };
446 
447  ExprResult VariantFuncRef;
448  if (Expr *E = Attr.getVariantFuncRef()) {
449  // Do not mark function as is used to prevent its emission if this is the
450  // only place where it is used.
453  VariantFuncRef = Subst(E);
454  }
455 
456  // Copy the template version of the OMPTraitInfo and run substitute on all
457  // score and condition expressiosn.
459  TI = *Attr.getTraitInfos();
460 
461  // Try to substitute template parameters in score and condition expressions.
462  auto SubstScoreOrConditionExpr = [&S, Subst](Expr *&E, bool) {
463  if (E) {
466  ExprResult ER = Subst(E);
467  if (ER.isUsable())
468  E = ER.get();
469  else
470  return true;
471  }
472  return false;
473  };
474  if (TI.anyScoreOrCondition(SubstScoreOrConditionExpr))
475  return;
476 
477  Expr *E = VariantFuncRef.get();
478 
479  // Check function/variant ref for `omp declare variant` but not for `omp
480  // begin declare variant` (which use implicit attributes).
481  std::optional<std::pair<FunctionDecl *, Expr *>> DeclVarData =
483  S.ConvertDeclToDeclGroup(New), E, TI, Attr.appendArgs_size(),
484  Attr.getRange());
485 
486  if (!DeclVarData)
487  return;
488 
489  E = DeclVarData->second;
490  FD = DeclVarData->first;
491 
492  if (auto *VariantDRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) {
493  if (auto *VariantFD = dyn_cast<FunctionDecl>(VariantDRE->getDecl())) {
494  if (auto *VariantFTD = VariantFD->getDescribedFunctionTemplate()) {
495  if (!VariantFTD->isThisDeclarationADefinition())
496  return;
499  S.Context, TemplateArgs.getInnermost());
500 
501  auto *SubstFD = S.InstantiateFunctionDeclaration(VariantFTD, TAL,
502  New->getLocation());
503  if (!SubstFD)
504  return;
505  QualType NewType = S.Context.mergeFunctionTypes(
506  SubstFD->getType(), FD->getType(),
507  /* OfBlockPointer */ false,
508  /* Unqualified */ false, /* AllowCXX */ true);
509  if (NewType.isNull())
510  return;
512  New->getLocation(), SubstFD, /* Recursive */ true,
513  /* DefinitionRequired */ false, /* AtEndOfTU */ false);
514  SubstFD->setInstantiationIsPending(!SubstFD->isDefined());
516  SourceLocation(), SubstFD,
517  /* RefersToEnclosingVariableOrCapture */ false,
518  /* NameLoc */ SubstFD->getLocation(),
519  SubstFD->getType(), ExprValueKind::VK_PRValue);
520  }
521  }
522  }
523 
524  SmallVector<Expr *, 8> NothingExprs;
525  SmallVector<Expr *, 8> NeedDevicePtrExprs;
527 
528  for (Expr *E : Attr.adjustArgsNothing()) {
529  ExprResult ER = Subst(E);
530  if (ER.isInvalid())
531  continue;
532  NothingExprs.push_back(ER.get());
533  }
534  for (Expr *E : Attr.adjustArgsNeedDevicePtr()) {
535  ExprResult ER = Subst(E);
536  if (ER.isInvalid())
537  continue;
538  NeedDevicePtrExprs.push_back(ER.get());
539  }
540  for (OMPInteropInfo &II : Attr.appendArgs()) {
541  // When prefer_type is implemented for append_args handle them here too.
542  AppendArgs.emplace_back(II.IsTarget, II.IsTargetSync);
543  }
544 
546  FD, E, TI, NothingExprs, NeedDevicePtrExprs, AppendArgs, SourceLocation(),
548 }
549 
551  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
552  const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) {
553  // Both min and max expression are constant expressions.
556 
557  ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
558  if (Result.isInvalid())
559  return;
560  Expr *MinExpr = Result.getAs<Expr>();
561 
562  Result = S.SubstExpr(Attr.getMax(), TemplateArgs);
563  if (Result.isInvalid())
564  return;
565  Expr *MaxExpr = Result.getAs<Expr>();
566 
567  S.addAMDGPUFlatWorkGroupSizeAttr(New, Attr, MinExpr, MaxExpr);
568 }
569 
571  const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES) {
572  if (!ES.getExpr())
573  return ES;
574  Expr *OldCond = ES.getExpr();
575  Expr *Cond = nullptr;
576  {
579  ExprResult SubstResult = SubstExpr(OldCond, TemplateArgs);
580  if (SubstResult.isInvalid()) {
582  }
583  Cond = SubstResult.get();
584  }
585  ExplicitSpecifier Result(Cond, ES.getKind());
586  if (!Cond->isTypeDependent())
588  return Result;
589 }
590 
592  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
593  const AMDGPUWavesPerEUAttr &Attr, Decl *New) {
594  // Both min and max expression are constant expressions.
597 
598  ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
599  if (Result.isInvalid())
600  return;
601  Expr *MinExpr = Result.getAs<Expr>();
602 
603  Expr *MaxExpr = nullptr;
604  if (auto Max = Attr.getMax()) {
605  Result = S.SubstExpr(Max, TemplateArgs);
606  if (Result.isInvalid())
607  return;
608  MaxExpr = Result.getAs<Expr>();
609  }
610 
611  S.addAMDGPUWavesPerEUAttr(New, Attr, MinExpr, MaxExpr);
612 }
613 
615  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
616  const AMDGPUMaxNumWorkGroupsAttr &Attr, Decl *New) {
619 
620  ExprResult ResultX = S.SubstExpr(Attr.getMaxNumWorkGroupsX(), TemplateArgs);
621  if (!ResultX.isUsable())
622  return;
623  ExprResult ResultY = S.SubstExpr(Attr.getMaxNumWorkGroupsY(), TemplateArgs);
624  if (!ResultY.isUsable())
625  return;
626  ExprResult ResultZ = S.SubstExpr(Attr.getMaxNumWorkGroupsZ(), TemplateArgs);
627  if (!ResultZ.isUsable())
628  return;
629 
630  Expr *XExpr = ResultX.getAs<Expr>();
631  Expr *YExpr = ResultY.getAs<Expr>();
632  Expr *ZExpr = ResultZ.getAs<Expr>();
633 
634  S.addAMDGPUMaxNumWorkGroupsAttr(New, Attr, XExpr, YExpr, ZExpr);
635 }
636 
638  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
639  const SYCLIntelForcePow2DepthAttr *Attr, Decl *New) {
642  ExprResult Result = S.SubstExpr(Attr->getValue(), TemplateArgs);
643  if (!Result.isInvalid())
644  return S.AddSYCLIntelForcePow2DepthAttr(New, *Attr, Result.getAs<Expr>());
645 }
646 
648  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
649  const SYCLIntelBankWidthAttr *Attr, Decl *New) {
652  ExprResult Result = S.SubstExpr(Attr->getValue(), TemplateArgs);
653  if (!Result.isInvalid())
654  S.AddSYCLIntelBankWidthAttr(New, *Attr, Result.getAs<Expr>());
655 }
656 
658  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
659  const SYCLIntelNumBanksAttr *Attr, Decl *New) {
662  ExprResult Result = S.SubstExpr(Attr->getValue(), TemplateArgs);
663  if (!Result.isInvalid())
664  S.AddSYCLIntelNumBanksAttr(New, *Attr, Result.getAs<Expr>());
665 }
666 
668  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
669  const SYCLIntelBankBitsAttr *Attr, Decl *New) {
673  for (auto I : Attr->args()) {
674  ExprResult Result = S.SubstExpr(I, TemplateArgs);
675  if (Result.isInvalid())
676  return;
677  Args.push_back(Result.getAs<Expr>());
678  }
679  S.AddSYCLIntelBankBitsAttr(New, *Attr, Args.data(), Args.size());
680 }
681 
682 static void
684  const MultiLevelTemplateArgumentList &TemplateArgs,
685  const SYCLDeviceHasAttr *Attr, Decl *New) {
689  if (S.SubstExprs(ArrayRef<Expr *>(Attr->aspects_begin(), Attr->aspects_end()),
690  /*IsCall=*/false, TemplateArgs, Args))
691  return;
692  S.AddSYCLDeviceHasAttr(New, *Attr, Args.data(), Args.size());
693 }
694 
696  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
697  const SYCLUsesAspectsAttr *Attr, Decl *New) {
701  for (auto I : Attr->aspects()) {
702  ExprResult Result = S.SubstExpr(I, TemplateArgs);
703  if (Result.isInvalid())
704  return;
705  Args.push_back(Result.getAs<Expr>());
706  }
707  S.AddSYCLUsesAspectsAttr(New, *Attr, Args.data(), Args.size());
708 }
709 
711  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
712  const SYCLIntelPipeIOAttr *Attr, Decl *New) {
713  // The ID expression is a constant expression.
716  ExprResult Result = S.SubstExpr(Attr->getID(), TemplateArgs);
717  if (!Result.isInvalid())
718  S.addSYCLIntelPipeIOAttr(New, *Attr, Result.getAs<Expr>());
719 }
720 
722  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
723  const SYCLIntelLoopFuseAttr *Attr, Decl *New) {
726  ExprResult Result = S.SubstExpr(Attr->getValue(), TemplateArgs);
727  if (!Result.isInvalid())
728  S.AddSYCLIntelLoopFuseAttr(New, *Attr, Result.getAs<Expr>());
729 }
730 
732  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
733  const IntelReqdSubGroupSizeAttr *A, Decl *New) {
736  ExprResult Result = S.SubstExpr(A->getValue(), TemplateArgs);
737  if (!Result.isInvalid())
738  S.AddIntelReqdSubGroupSize(New, *A, Result.getAs<Expr>());
739 }
740 
742  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
743  const SYCLIntelNumSimdWorkItemsAttr *A, Decl *New) {
746  ExprResult Result = S.SubstExpr(A->getValue(), TemplateArgs);
747  if (!Result.isInvalid())
748  S.AddSYCLIntelNumSimdWorkItemsAttr(New, *A, Result.getAs<Expr>());
749 }
750 
752  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
753  const SYCLIntelSchedulerTargetFmaxMhzAttr *A, Decl *New) {
756  ExprResult Result = S.SubstExpr(A->getValue(), TemplateArgs);
757  if (!Result.isInvalid())
758  S.AddSYCLIntelSchedulerTargetFmaxMhzAttr(New, *A, Result.getAs<Expr>());
759 }
760 
762  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
763  const SYCLIntelNoGlobalWorkOffsetAttr *A, Decl *New) {
766  ExprResult Result = S.SubstExpr(A->getValue(), TemplateArgs);
767  if (!Result.isInvalid())
768  S.AddSYCLIntelNoGlobalWorkOffsetAttr(New, *A, Result.getAs<Expr>());
769 }
770 
772  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
773  const SYCLIntelMaxGlobalWorkDimAttr *A, Decl *New) {
776  ExprResult Result = S.SubstExpr(A->getValue(), TemplateArgs);
777  if (!Result.isInvalid())
778  S.AddSYCLIntelMaxGlobalWorkDimAttr(New, *A, Result.getAs<Expr>());
779 }
780 
782  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
783  const SYCLIntelMinWorkGroupsPerComputeUnitAttr *A, Decl *New) {
786  ExprResult Result = S.SubstExpr(A->getValue(), TemplateArgs);
787  if (!Result.isInvalid())
789  Result.getAs<Expr>());
790 }
791 
793  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
794  const SYCLIntelMaxWorkGroupsPerMultiprocessorAttr *A, Decl *New) {
797  ExprResult Result = S.SubstExpr(A->getValue(), TemplateArgs);
798  if (!Result.isInvalid())
800  Result.getAs<Expr>());
801 }
802 
804  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
805  const SYCLIntelMaxConcurrencyAttr *A, Decl *New) {
808  ExprResult Result = S.SubstExpr(A->getNExpr(), TemplateArgs);
809  if (!Result.isInvalid())
810  S.AddSYCLIntelMaxConcurrencyAttr(New, *A, Result.getAs<Expr>());
811 }
812 
814  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
815  const SYCLIntelPrivateCopiesAttr *A, Decl *New) {
818  ExprResult Result = S.SubstExpr(A->getValue(), TemplateArgs);
819  if (!Result.isInvalid())
820  S.AddSYCLIntelPrivateCopiesAttr(New, *A, Result.getAs<Expr>());
821 }
822 
824  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
825  const SYCLIntelMaxReplicatesAttr *A, Decl *New) {
828  ExprResult Result = S.SubstExpr(A->getValue(), TemplateArgs);
829  if (!Result.isInvalid())
830  S.AddSYCLIntelMaxReplicatesAttr(New, *A, Result.getAs<Expr>());
831 }
832 
834  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
835  const SYCLIntelInitiationIntervalAttr *A, Decl *New) {
838  ExprResult Result = S.SubstExpr(A->getNExpr(), TemplateArgs);
839  if (!Result.isInvalid())
840  S.AddSYCLIntelInitiationIntervalAttr(New, *A, Result.getAs<Expr>());
841 }
842 
844  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
845  const SYCLIntelESimdVectorizeAttr *A, Decl *New) {
848  ExprResult Result = S.SubstExpr(A->getValue(), TemplateArgs);
849  if (!Result.isInvalid())
850  S.AddSYCLIntelESimdVectorizeAttr(New, *A, Result.getAs<Expr>());
851 }
852 
854  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
855  const SYCLAddIRAttributesFunctionAttr *A, Decl *New) {
859  if (S.SubstExprs(ArrayRef<Expr *>(A->args_begin(), A->args_end()),
860  /*IsCall=*/false, TemplateArgs, Args))
861  return;
862  S.AddSYCLAddIRAttributesFunctionAttr(New, *A, Args);
863 }
864 
866  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
867  const SYCLAddIRAttributesKernelParameterAttr *A, Decl *New) {
871  if (S.SubstExprs(ArrayRef<Expr *>(A->args().begin(), A->args().end()),
872  /*IsCall=*/false, TemplateArgs, Args))
873  return;
875 }
876 
878  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
879  const SYCLAddIRAttributesGlobalVariableAttr *A, Decl *New) {
883  if (S.SubstExprs(ArrayRef<Expr *>(A->args().begin(), A->args().end()),
884  /*IsCall=*/false, TemplateArgs, Args))
885  return;
887 }
888 
890  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
891  const SYCLAddIRAnnotationsMemberAttr *A, Decl *New) {
892  EnterExpressionEvaluationContext ConstantEvaluated(
895  if (S.SubstExprs(ArrayRef<Expr *>(A->args().begin(), A->args().end()),
896  /*IsCall=*/false, TemplateArgs, Args))
897  return;
898  S.AddSYCLAddIRAnnotationsMemberAttr(New, *A, Args);
899 }
900 
902  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
903  const SYCLWorkGroupSizeHintAttr *A, Decl *New) {
906  ExprResult XResult = S.SubstExpr(A->getXDim(), TemplateArgs);
907  if (XResult.isInvalid())
908  return;
909  ExprResult YResult = S.SubstExpr(A->getYDim(), TemplateArgs);
910  if (YResult.isInvalid())
911  return;
912  ExprResult ZResult = S.SubstExpr(A->getZDim(), TemplateArgs);
913  if (ZResult.isInvalid())
914  return;
915 
916  S.AddSYCLWorkGroupSizeHintAttr(New, *A, XResult.get(), YResult.get(),
917  ZResult.get());
918 }
919 
921  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
922  const SYCLIntelMaxWorkGroupSizeAttr *A, Decl *New) {
925  ExprResult XResult = S.SubstExpr(A->getXDim(), TemplateArgs);
926  if (XResult.isInvalid())
927  return;
928  ExprResult YResult = S.SubstExpr(A->getYDim(), TemplateArgs);
929  if (YResult.isInvalid())
930  return;
931  ExprResult ZResult = S.SubstExpr(A->getZDim(), TemplateArgs);
932  if (ZResult.isInvalid())
933  return;
934 
935  S.AddSYCLIntelMaxWorkGroupSizeAttr(New, *A, XResult.get(), YResult.get(),
936  ZResult.get());
937 }
938 
940  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
941  const SYCLReqdWorkGroupSizeAttr *A, Decl *New) {
944  ExprResult XResult = S.SubstExpr(A->getXDim(), TemplateArgs);
945  if (XResult.isInvalid())
946  return;
947  ExprResult YResult = S.SubstExpr(A->getYDim(), TemplateArgs);
948  if (YResult.isInvalid())
949  return;
950  ExprResult ZResult = S.SubstExpr(A->getZDim(), TemplateArgs);
951  if (ZResult.isInvalid())
952  return;
953 
954  S.AddSYCLReqdWorkGroupSizeAttr(New, *A, XResult.get(), YResult.get(),
955  ZResult.get());
956 }
957 
958 // This doesn't take any template parameters, but we have a custom action that
959 // needs to happen when the kernel itself is instantiated. We need to run the
960 // ItaniumMangler to mark the names required to name this kernel.
962  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
963  const SYCLKernelAttr &Attr, Decl *New) {
964  New->addAttr(Attr.clone(S.getASTContext()));
965 }
966 
967 /// Determine whether the attribute A might be relevant to the declaration D.
968 /// If not, we can skip instantiating it. The attribute may or may not have
969 /// been instantiated yet.
970 static bool isRelevantAttr(Sema &S, const Decl *D, const Attr *A) {
971  // 'preferred_name' is only relevant to the matching specialization of the
972  // template.
973  if (const auto *PNA = dyn_cast<PreferredNameAttr>(A)) {
974  QualType T = PNA->getTypedefType();
975  const auto *RD = cast<CXXRecordDecl>(D);
976  if (!T->isDependentType() && !RD->isDependentContext() &&
978  return false;
979  for (const auto *ExistingPNA : D->specific_attrs<PreferredNameAttr>())
980  if (S.Context.hasSameType(ExistingPNA->getTypedefType(),
981  PNA->getTypedefType()))
982  return false;
983  return true;
984  }
985 
986  if (const auto *BA = dyn_cast<BuiltinAttr>(A)) {
987  const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
988  switch (BA->getID()) {
989  case Builtin::BIforward:
990  // Do not treat 'std::forward' as a builtin if it takes an rvalue reference
991  // type and returns an lvalue reference type. The library implementation
992  // will produce an error in this case; don't get in its way.
993  if (FD && FD->getNumParams() >= 1 &&
996  return false;
997  }
998  [[fallthrough]];
999  case Builtin::BImove:
1000  case Builtin::BImove_if_noexcept:
1001  // HACK: Super-old versions of libc++ (3.1 and earlier) provide
1002  // std::forward and std::move overloads that sometimes return by value
1003  // instead of by reference when building in C++98 mode. Don't treat such
1004  // cases as builtins.
1005  if (FD && !FD->getReturnType()->isReferenceType())
1006  return false;
1007  break;
1008  }
1009  }
1010 
1011  return true;
1012 }
1013 
1015  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
1016  const HLSLParamModifierAttr *Attr, Decl *New) {
1017  ParmVarDecl *P = cast<ParmVarDecl>(New);
1018  P->addAttr(Attr->clone(S.getASTContext()));
1019  P->setType(S.getASTContext().getLValueReferenceType(P->getType()));
1020 }
1021 
1023  const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl,
1024  Decl *New, LateInstantiatedAttrVec *LateAttrs,
1025  LocalInstantiationScope *OuterMostScope) {
1026  if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) {
1027  // FIXME: This function is called multiple times for the same template
1028  // specialization. We should only instantiate attributes that were added
1029  // since the previous instantiation.
1030  for (const auto *TmplAttr : Tmpl->attrs()) {
1031  if (!isRelevantAttr(*this, New, TmplAttr))
1032  continue;
1033 
1034  // FIXME: If any of the special case versions from InstantiateAttrs become
1035  // applicable to template declaration, we'll need to add them here.
1036  CXXThisScopeRAII ThisScope(
1037  *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()),
1038  Qualifiers(), ND->isCXXInstanceMember());
1039 
1041  TmplAttr, Context, *this, TemplateArgs);
1042  if (NewAttr && isRelevantAttr(*this, New, NewAttr))
1043  New->addAttr(NewAttr);
1044  }
1045  }
1046 }
1047 
1050  switch (A->getKind()) {
1051  case clang::attr::CFConsumed:
1053  case clang::attr::OSConsumed:
1055  case clang::attr::NSConsumed:
1057  default:
1058  llvm_unreachable("Wrong argument supplied");
1059  }
1060 }
1061 
1063  const Decl *Tmpl, Decl *New,
1064  LateInstantiatedAttrVec *LateAttrs,
1065  LocalInstantiationScope *OuterMostScope) {
1066  for (const auto *TmplAttr : Tmpl->attrs()) {
1067  if (!isRelevantAttr(*this, New, TmplAttr))
1068  continue;
1069 
1070  // FIXME: This should be generalized to more than just the AlignedAttr.
1071  const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
1072  if (Aligned && Aligned->isAlignmentDependent()) {
1073  instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
1074  continue;
1075  }
1076 
1077  if (const auto *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr)) {
1078  instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
1079  continue;
1080  }
1081 
1082  if (const auto *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr)) {
1083  instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
1084  continue;
1085  }
1086 
1087  if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) {
1088  instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New);
1089  continue;
1090  }
1091 
1092  if (const auto *Annotate = dyn_cast<AnnotateAttr>(TmplAttr)) {
1093  instantiateDependentAnnotationAttr(*this, TemplateArgs, Annotate, New);
1094  continue;
1095  }
1096 
1097  if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) {
1098  instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
1099  cast<FunctionDecl>(New));
1100  continue;
1101  }
1102 
1103  if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) {
1104  instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl,
1105  cast<FunctionDecl>(New));
1106  continue;
1107  }
1108 
1109  if (const auto *CUDALaunchBounds =
1110  dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
1111  instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs,
1112  *CUDALaunchBounds, New);
1113  continue;
1114  }
1115 
1116  if (const auto *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
1117  instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
1118  continue;
1119  }
1120 
1121  if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
1122  instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
1123  continue;
1124  }
1125 
1126  if (const auto *OMPAttr = dyn_cast<OMPDeclareVariantAttr>(TmplAttr)) {
1127  instantiateOMPDeclareVariantAttr(*this, TemplateArgs, *OMPAttr, New);
1128  continue;
1129  }
1130 
1131  if (const auto *AMDGPUFlatWorkGroupSize =
1132  dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(TmplAttr)) {
1134  *this, TemplateArgs, *AMDGPUFlatWorkGroupSize, New);
1135  }
1136 
1137  if (const auto *AMDGPUFlatWorkGroupSize =
1138  dyn_cast<AMDGPUWavesPerEUAttr>(TmplAttr)) {
1139  instantiateDependentAMDGPUWavesPerEUAttr(*this, TemplateArgs,
1140  *AMDGPUFlatWorkGroupSize, New);
1141  }
1142 
1143  if (const auto *SYCLIntelBankWidth =
1144  dyn_cast<SYCLIntelBankWidthAttr>(TmplAttr)) {
1145  instantiateSYCLIntelBankWidthAttr(*this, TemplateArgs, SYCLIntelBankWidth,
1146  New);
1147  }
1148 
1149  if (const auto *SYCLIntelNumBanks =
1150  dyn_cast<SYCLIntelNumBanksAttr>(TmplAttr)) {
1151  instantiateSYCLIntelNumBanksAttr(*this, TemplateArgs, SYCLIntelNumBanks,
1152  New);
1153  }
1154  if (const auto *SYCLIntelPrivateCopies =
1155  dyn_cast<SYCLIntelPrivateCopiesAttr>(TmplAttr)) {
1156  instantiateSYCLIntelPrivateCopiesAttr(*this, TemplateArgs,
1157  SYCLIntelPrivateCopies, New);
1158  }
1159  if (const auto *SYCLIntelMaxReplicates =
1160  dyn_cast<SYCLIntelMaxReplicatesAttr>(TmplAttr)) {
1161  instantiateSYCLIntelMaxReplicatesAttr(*this, TemplateArgs,
1162  SYCLIntelMaxReplicates, New);
1163  }
1164  if (const auto *SYCLIntelBankBits =
1165  dyn_cast<SYCLIntelBankBitsAttr>(TmplAttr)) {
1166  instantiateSYCLIntelBankBitsAttr(*this, TemplateArgs, SYCLIntelBankBits,
1167  New);
1168  }
1169  if (const auto *SYCLIntelForcePow2Depth =
1170  dyn_cast<SYCLIntelForcePow2DepthAttr>(TmplAttr)) {
1171  instantiateSYCLIntelForcePow2DepthAttr(*this, TemplateArgs,
1172  SYCLIntelForcePow2Depth, New);
1173  }
1174  if (const auto *SYCLIntelPipeIO = dyn_cast<SYCLIntelPipeIOAttr>(TmplAttr)) {
1175  instantiateSYCLIntelPipeIOAttr(*this, TemplateArgs, SYCLIntelPipeIO, New);
1176  continue;
1177  }
1178  if (const auto *IntelReqdSubGroupSize =
1179  dyn_cast<IntelReqdSubGroupSizeAttr>(TmplAttr)) {
1180  instantiateIntelReqdSubGroupSize(*this, TemplateArgs,
1181  IntelReqdSubGroupSize, New);
1182  continue;
1183  }
1184  if (const auto *SYCLIntelNumSimdWorkItems =
1185  dyn_cast<SYCLIntelNumSimdWorkItemsAttr>(TmplAttr)) {
1186  instantiateSYCLIntelNumSimdWorkItemsAttr(*this, TemplateArgs,
1187  SYCLIntelNumSimdWorkItems, New);
1188  continue;
1189  }
1190  if (const auto *SYCLIntelSchedulerTargetFmaxMhz =
1191  dyn_cast<SYCLIntelSchedulerTargetFmaxMhzAttr>(TmplAttr)) {
1193  *this, TemplateArgs, SYCLIntelSchedulerTargetFmaxMhz, New);
1194  continue;
1195  }
1196  if (const auto *SYCLIntelMaxGlobalWorkDim =
1197  dyn_cast<SYCLIntelMaxGlobalWorkDimAttr>(TmplAttr)) {
1198  instantiateSYCLIntelMaxGlobalWorkDimAttr(*this, TemplateArgs,
1199  SYCLIntelMaxGlobalWorkDim, New);
1200  continue;
1201  }
1202  if (const auto *SYCLIntelMinWorkGroupsPerComputeUnit =
1203  dyn_cast<SYCLIntelMinWorkGroupsPerComputeUnitAttr>(TmplAttr)) {
1205  *this, TemplateArgs, SYCLIntelMinWorkGroupsPerComputeUnit, New);
1206  continue;
1207  }
1208  if (const auto *SYCLIntelMaxWorkGroupsPerMultiprocessor =
1209  dyn_cast<SYCLIntelMaxWorkGroupsPerMultiprocessorAttr>(TmplAttr)) {
1211  *this, TemplateArgs, SYCLIntelMaxWorkGroupsPerMultiprocessor, New);
1212  continue;
1213  }
1214  if (const auto *SYCLIntelLoopFuse =
1215  dyn_cast<SYCLIntelLoopFuseAttr>(TmplAttr)) {
1216  instantiateSYCLIntelLoopFuseAttr(*this, TemplateArgs, SYCLIntelLoopFuse,
1217  New);
1218  continue;
1219  }
1220  if (const auto *SYCLIntelNoGlobalWorkOffset =
1221  dyn_cast<SYCLIntelNoGlobalWorkOffsetAttr>(TmplAttr)) {
1223  *this, TemplateArgs, SYCLIntelNoGlobalWorkOffset, New);
1224  continue;
1225  }
1226  if (const auto *SYCLReqdWorkGroupSize =
1227  dyn_cast<SYCLReqdWorkGroupSizeAttr>(TmplAttr)) {
1228  instantiateSYCLReqdWorkGroupSizeAttr(*this, TemplateArgs,
1229  SYCLReqdWorkGroupSize, New);
1230  continue;
1231  }
1232  if (const auto *SYCLIntelMaxWorkGroupSize =
1233  dyn_cast<SYCLIntelMaxWorkGroupSizeAttr>(TmplAttr)) {
1234  instantiateSYCLIntelMaxWorkGroupSizeAttr(*this, TemplateArgs,
1235  SYCLIntelMaxWorkGroupSize, New);
1236  continue;
1237  }
1238  if (const auto *SYCLIntelMaxConcurrency =
1239  dyn_cast<SYCLIntelMaxConcurrencyAttr>(TmplAttr)) {
1240  instantiateSYCLIntelMaxConcurrencyAttr(*this, TemplateArgs,
1241  SYCLIntelMaxConcurrency, New);
1242  }
1243  if (const auto *SYCLIntelInitiationInterval =
1244  dyn_cast<SYCLIntelInitiationIntervalAttr>(TmplAttr)) {
1246  *this, TemplateArgs, SYCLIntelInitiationInterval, New);
1247  continue;
1248  }
1249  if (const auto *SYCLIntelESimdVectorize =
1250  dyn_cast<SYCLIntelESimdVectorizeAttr>(TmplAttr)) {
1251  instantiateSYCLIntelESimdVectorizeAttr(*this, TemplateArgs,
1252  SYCLIntelESimdVectorize, New);
1253  continue;
1254  }
1255  if (const auto *SYCLAddIRAttributesFunction =
1256  dyn_cast<SYCLAddIRAttributesFunctionAttr>(TmplAttr)) {
1258  *this, TemplateArgs, SYCLAddIRAttributesFunction, New);
1259  continue;
1260  }
1261  if (const auto *SYCLAddIRAttributesKernelParameter =
1262  dyn_cast<SYCLAddIRAttributesKernelParameterAttr>(TmplAttr)) {
1264  *this, TemplateArgs, SYCLAddIRAttributesKernelParameter, New);
1265  continue;
1266  }
1267  if (const auto *SYCLAddIRAttributesGlobalVariable =
1268  dyn_cast<SYCLAddIRAttributesGlobalVariableAttr>(TmplAttr)) {
1270  *this, TemplateArgs, SYCLAddIRAttributesGlobalVariable, New);
1271  continue;
1272  }
1273  if (const auto *SYCLAddIRAnnotationsMember =
1274  dyn_cast<SYCLAddIRAnnotationsMemberAttr>(TmplAttr)) {
1276  *this, TemplateArgs, SYCLAddIRAnnotationsMember, New);
1277  continue;
1278  }
1279  if (const auto *A = dyn_cast<SYCLWorkGroupSizeHintAttr>(TmplAttr)) {
1280  instantiateSYCLWorkGroupSizeHintAttr(*this, TemplateArgs, A, New);
1281  continue;
1282  }
1283  if (const auto *A = dyn_cast<SYCLDeviceHasAttr>(TmplAttr)) {
1284  instantiateSYCLDeviceHasAttr(*this, TemplateArgs, A, New);
1285  continue;
1286  }
1287  if (const auto *A = dyn_cast<SYCLUsesAspectsAttr>(TmplAttr)) {
1288  instantiateSYCLUsesAspectsAttr(*this, TemplateArgs, A, New);
1289  continue;
1290  }
1291 
1292  if (const auto *AMDGPUMaxNumWorkGroups =
1293  dyn_cast<AMDGPUMaxNumWorkGroupsAttr>(TmplAttr)) {
1295  *this, TemplateArgs, *AMDGPUMaxNumWorkGroups, New);
1296  }
1297 
1298  if (const auto *ParamAttr = dyn_cast<HLSLParamModifierAttr>(TmplAttr)) {
1299  instantiateDependentHLSLParamModifierAttr(*this, TemplateArgs, ParamAttr,
1300  New);
1301  continue;
1302  }
1303  // Existing DLL attribute on the instantiation takes precedence.
1304  if (TmplAttr->getKind() == attr::DLLExport ||
1305  TmplAttr->getKind() == attr::DLLImport) {
1306  if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
1307  continue;
1308  }
1309  }
1310 
1311  if (const auto *ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
1312  AddParameterABIAttr(New, *ABIAttr, ABIAttr->getABI());
1313  continue;
1314  }
1315 
1316  if (isa<NSConsumedAttr>(TmplAttr) || isa<OSConsumedAttr>(TmplAttr) ||
1317  isa<CFConsumedAttr>(TmplAttr)) {
1318  AddXConsumedAttr(New, *TmplAttr, attrToRetainOwnershipKind(TmplAttr),
1319  /*template instantiation=*/true);
1320  continue;
1321  }
1322 
1323  if (auto *A = dyn_cast<PointerAttr>(TmplAttr)) {
1324  if (!New->hasAttr<PointerAttr>())
1325  New->addAttr(A->clone(Context));
1326  continue;
1327  }
1328 
1329  if (auto *A = dyn_cast<OwnerAttr>(TmplAttr)) {
1330  if (!New->hasAttr<OwnerAttr>())
1331  New->addAttr(A->clone(Context));
1332  continue;
1333  }
1334 
1335  if (auto *A = dyn_cast<SYCLKernelAttr>(TmplAttr)) {
1336  instantiateDependentSYCLKernelAttr(*this, TemplateArgs, *A, New);
1337  continue;
1338  }
1339 
1340  assert(!TmplAttr->isPackExpansion());
1341  if (TmplAttr->isLateParsed() && LateAttrs) {
1342  // Late parsed attributes must be instantiated and attached after the
1343  // enclosing class has been instantiated. See Sema::InstantiateClass.
1344  LocalInstantiationScope *Saved = nullptr;
1346  Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
1347  LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
1348  } else {
1349  // Allow 'this' within late-parsed attributes.
1350  auto *ND = cast<NamedDecl>(New);
1351  auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
1352  CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
1353  ND->isCXXInstanceMember());
1354 
1355  Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
1356  *this, TemplateArgs);
1357  if (NewAttr && isRelevantAttr(*this, New, TmplAttr))
1358  New->addAttr(NewAttr);
1359  }
1360  }
1361 }
1362 
1363 /// Update instantiation attributes after template was late parsed.
1364 ///
1365 /// Some attributes are evaluated based on the body of template. If it is
1366 /// late parsed, such attributes cannot be evaluated when declaration is
1367 /// instantiated. This function is used to update instantiation attributes when
1368 /// template definition is ready.
1369 void Sema::updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst) {
1370  for (const auto *Attr : Pattern->attrs()) {
1371  if (auto *A = dyn_cast<StrictFPAttr>(Attr)) {
1372  if (!Inst->hasAttr<StrictFPAttr>())
1373  Inst->addAttr(A->clone(getASTContext()));
1374  continue;
1375  }
1376  }
1377 }
1378 
1379 /// In the MS ABI, we need to instantiate default arguments of dllexported
1380 /// default constructors along with the constructor definition. This allows IR
1381 /// gen to emit a constructor closure which calls the default constructor with
1382 /// its default arguments.
1384  assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
1385  Ctor->isDefaultConstructor());
1386  unsigned NumParams = Ctor->getNumParams();
1387  if (NumParams == 0)
1388  return;
1389  DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>();
1390  if (!Attr)
1391  return;
1392  for (unsigned I = 0; I != NumParams; ++I) {
1393  (void)CheckCXXDefaultArgExpr(Attr->getLocation(), Ctor,
1394  Ctor->getParamDecl(I));
1396  }
1397 }
1398 
1399 /// Get the previous declaration of a declaration for the purposes of template
1400 /// instantiation. If this finds a previous declaration, then the previous
1401 /// declaration of the instantiation of D should be an instantiation of the
1402 /// result of this function.
1403 template<typename DeclT>
1404 static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
1405  DeclT *Result = D->getPreviousDecl();
1406 
1407  // If the declaration is within a class, and the previous declaration was
1408  // merged from a different definition of that class, then we don't have a
1409  // previous declaration for the purpose of template instantiation.
1410  if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
1411  D->getLexicalDeclContext() != Result->getLexicalDeclContext())
1412  return nullptr;
1413 
1414  return Result;
1415 }
1416 
1417 Decl *
1418 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
1419  llvm_unreachable("Translation units cannot be instantiated");
1420 }
1421 
1422 Decl *TemplateDeclInstantiator::VisitHLSLBufferDecl(HLSLBufferDecl *Decl) {
1423  llvm_unreachable("HLSL buffer declarations cannot be instantiated");
1424 }
1425 
1426 Decl *
1427 TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
1428  llvm_unreachable("pragma comment cannot be instantiated");
1429 }
1430 
1431 Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
1433  llvm_unreachable("pragma comment cannot be instantiated");
1434 }
1435 
1436 Decl *
1437 TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
1438  llvm_unreachable("extern \"C\" context cannot be instantiated");
1439 }
1440 
1441 Decl *TemplateDeclInstantiator::VisitMSGuidDecl(MSGuidDecl *D) {
1442  llvm_unreachable("GUID declaration cannot be instantiated");
1443 }
1444 
1445 Decl *TemplateDeclInstantiator::VisitUnnamedGlobalConstantDecl(
1447  llvm_unreachable("UnnamedGlobalConstantDecl cannot be instantiated");
1448 }
1449 
1450 Decl *TemplateDeclInstantiator::VisitTemplateParamObjectDecl(
1452  llvm_unreachable("template parameter objects cannot be instantiated");
1453 }
1454 
1455 Decl *
1456 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
1457  LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1458  D->getIdentifier());
1459  Owner->addDecl(Inst);
1460  return Inst;
1461 }
1462 
1463 Decl *
1464 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
1465  llvm_unreachable("Namespaces cannot be instantiated");
1466 }
1467 
1468 Decl *
1469 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1470  NamespaceAliasDecl *Inst
1471  = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
1472  D->getNamespaceLoc(),
1473  D->getAliasLoc(),
1474  D->getIdentifier(),
1475  D->getQualifierLoc(),
1476  D->getTargetNameLoc(),
1477  D->getNamespace());
1478  Owner->addDecl(Inst);
1479  return Inst;
1480 }
1481 
1483  bool IsTypeAlias) {
1484  bool Invalid = false;
1485  TypeSourceInfo *DI = D->getTypeSourceInfo();
1486  if (DI->getType()->isInstantiationDependentType() ||
1487  DI->getType()->isVariablyModifiedType()) {
1488  DI = SemaRef.SubstType(DI, TemplateArgs,
1489  D->getLocation(), D->getDeclName());
1490  if (!DI) {
1491  Invalid = true;
1492  DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
1493  }
1494  } else {
1496  }
1497 
1498  // HACK: 2012-10-23 g++ has a bug where it gets the value kind of ?: wrong.
1499  // libstdc++ relies upon this bug in its implementation of common_type. If we
1500  // happen to be processing that implementation, fake up the g++ ?:
1501  // semantics. See LWG issue 2141 for more information on the bug. The bugs
1502  // are fixed in g++ and libstdc++ 4.9.0 (2014-04-22).
1503  const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
1504  CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
1505  if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
1506  DT->isReferenceType() &&
1507  RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
1508  RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
1509  D->getIdentifier() && D->getIdentifier()->isStr("type") &&
1511  // Fold it to the (non-reference) type which g++ would have produced.
1512  DI = SemaRef.Context.getTrivialTypeSourceInfo(
1513  DI->getType().getNonReferenceType());
1514 
1515  // Create the new typedef
1516  TypedefNameDecl *Typedef;
1517  if (IsTypeAlias)
1518  Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1519  D->getLocation(), D->getIdentifier(), DI);
1520  else
1521  Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1522  D->getLocation(), D->getIdentifier(), DI);
1523  if (Invalid)
1524  Typedef->setInvalidDecl();
1525 
1526  // If the old typedef was the name for linkage purposes of an anonymous
1527  // tag decl, re-establish that relationship for the new typedef.
1528  if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
1529  TagDecl *oldTag = oldTagType->getDecl();
1530  if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
1531  TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
1532  assert(!newTag->hasNameForLinkage());
1533  newTag->setTypedefNameForAnonDecl(Typedef);
1534  }
1535  }
1536 
1538  NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
1539  TemplateArgs);
1540  if (!InstPrev)
1541  return nullptr;
1542 
1543  TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
1544 
1545  // If the typedef types are not identical, reject them.
1546  SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
1547 
1548  Typedef->setPreviousDecl(InstPrevTypedef);
1549  }
1550 
1551  SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
1552 
1554  SemaRef.inferGslPointerAttribute(Typedef);
1555 
1556  Typedef->setAccess(D->getAccess());
1557  Typedef->setReferenced(D->isReferenced());
1558 
1559  return Typedef;
1560 }
1561 
1562 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
1563  Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
1564  if (Typedef)
1565  Owner->addDecl(Typedef);
1566  return Typedef;
1567 }
1568 
1569 Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
1570  Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
1571  if (Typedef)
1572  Owner->addDecl(Typedef);
1573  return Typedef;
1574 }
1575 
1576 Decl *
1577 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
1578  // Create a local instantiation scope for this type alias template, which
1579  // will contain the instantiations of the template parameters.
1580  LocalInstantiationScope Scope(SemaRef);
1581 
1582  TemplateParameterList *TempParams = D->getTemplateParameters();
1583  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1584  if (!InstParams)
1585  return nullptr;
1586 
1587  TypeAliasDecl *Pattern = D->getTemplatedDecl();
1588  Sema::InstantiatingTemplate InstTemplate(
1589  SemaRef, D->getBeginLoc(), D,
1590  D->getTemplateDepth() >= TemplateArgs.getNumLevels()
1592  : (TemplateArgs.begin() + TemplateArgs.getNumLevels() - 1 -
1593  D->getTemplateDepth())
1594  ->Args);
1595  if (InstTemplate.isInvalid())
1596  return nullptr;
1597 
1598  TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
1599  if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
1600  DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1601  if (!Found.empty()) {
1602  PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
1603  }
1604  }
1605 
1606  TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
1607  InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
1608  if (!AliasInst)
1609  return nullptr;
1610 
1611  TypeAliasTemplateDecl *Inst
1612  = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1613  D->getDeclName(), InstParams, AliasInst);
1614  AliasInst->setDescribedAliasTemplate(Inst);
1615  if (PrevAliasTemplate)
1616  Inst->setPreviousDecl(PrevAliasTemplate);
1617 
1618  Inst->setAccess(D->getAccess());
1619 
1620  if (!PrevAliasTemplate)
1622 
1623  Owner->addDecl(Inst);
1624 
1625  return Inst;
1626 }
1627 
1628 Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) {
1629  auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1630  D->getIdentifier());
1631  NewBD->setReferenced(D->isReferenced());
1632  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewBD);
1633  return NewBD;
1634 }
1635 
1636 Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
1637  // Transform the bindings first.
1638  SmallVector<BindingDecl*, 16> NewBindings;
1639  for (auto *OldBD : D->bindings())
1640  NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD)));
1641  ArrayRef<BindingDecl*> NewBindingArray = NewBindings;
1642 
1643  auto *NewDD = cast_or_null<DecompositionDecl>(
1644  VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray));
1645 
1646  if (!NewDD || NewDD->isInvalidDecl())
1647  for (auto *NewBD : NewBindings)
1648  NewBD->setInvalidDecl();
1649 
1650  return NewDD;
1651 }
1652 
1654  return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
1655 }
1656 
1658  bool InstantiatingVarTemplate,
1660 
1661  // Do substitution on the type of the declaration
1662  TypeSourceInfo *DI = SemaRef.SubstType(
1663  D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(),
1664  D->getDeclName(), /*AllowDeducedTST*/true);
1665  if (!DI)
1666  return nullptr;
1667 
1668  if (DI->getType()->isFunctionType()) {
1669  SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
1670  << D->isStaticDataMember() << DI->getType();
1671  return nullptr;
1672  }
1673 
1674  DeclContext *DC = Owner;
1675  if (D->isLocalExternDecl())
1676  SemaRef.adjustContextForLocalExternDecl(DC);
1677 
1678  // Build the instantiated declaration.
1679  VarDecl *Var;
1680  if (Bindings)
1681  Var = DecompositionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1682  D->getLocation(), DI->getType(), DI,
1683  D->getStorageClass(), *Bindings);
1684  else
1685  Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1686  D->getLocation(), D->getIdentifier(), DI->getType(),
1687  DI, D->getStorageClass());
1688 
1689  // In ARC, infer 'retaining' for variables of retainable type.
1690  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1691  SemaRef.ObjC().inferObjCARCLifetime(Var))
1692  Var->setInvalidDecl();
1693 
1694  if (SemaRef.getLangOpts().OpenCL)
1695  SemaRef.deduceOpenCLAddressSpace(Var);
1696 
1697  // Substitute the nested name specifier, if any.
1698  if (SubstQualifier(D, Var))
1699  return nullptr;
1700 
1701  SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
1702  StartingScope, InstantiatingVarTemplate);
1703  if (D->isNRVOVariable() && !Var->isInvalidDecl()) {
1704  QualType RT;
1705  if (auto *F = dyn_cast<FunctionDecl>(DC))
1706  RT = F->getReturnType();
1707  else if (isa<BlockDecl>(DC))
1708  RT = cast<FunctionType>(SemaRef.getCurBlock()->FunctionType)
1709  ->getReturnType();
1710  else
1711  llvm_unreachable("Unknown context type");
1712 
1713  // This is the last chance we have of checking copy elision eligibility
1714  // for functions in dependent contexts. The sema actions for building
1715  // the return statement during template instantiation will have no effect
1716  // regarding copy elision, since NRVO propagation runs on the scope exit
1717  // actions, and these are not run on instantiation.
1718  // This might run through some VarDecls which were returned from non-taken
1719  // 'if constexpr' branches, and these will end up being constructed on the
1720  // return slot even if they will never be returned, as a sort of accidental
1721  // 'optimization'. Notably, functions with 'auto' return types won't have it
1722  // deduced by this point. Coupled with the limitation described
1723  // previously, this makes it very hard to support copy elision for these.
1724  Sema::NamedReturnInfo Info = SemaRef.getNamedReturnInfo(Var);
1725  bool NRVO = SemaRef.getCopyElisionCandidate(Info, RT) != nullptr;
1726  Var->setNRVOVariable(NRVO);
1727  }
1728 
1729  Var->setImplicit(D->isImplicit());
1730 
1731  if (Var->isStaticLocal())
1732  SemaRef.CheckStaticLocalForDllExport(Var);
1733 
1734  // Only add this if we aren't instantiating a variable template. We'll end up
1735  // adding the VarTemplateSpecializationDecl later.
1736  if (!InstantiatingVarTemplate) {
1737  if (SemaRef.getLangOpts().SYCLIsDevice &&
1738  SemaRef.SYCL().isTypeDecoratedWithDeclAttribute<SYCLDeviceGlobalAttr>(
1739  Var->getType())) {
1740  if (!Var->hasGlobalStorage())
1741  SemaRef.Diag(D->getLocation(),
1742  diag::err_sycl_device_global_incorrect_scope);
1743 
1744  if (Var->getAccess() == AS_private || Var->getAccess() == AS_protected)
1745  SemaRef.Diag(D->getLocation(),
1746  diag::err_sycl_device_global_not_publicly_accessible)
1747  << Var;
1748 
1749  if (Var->isStaticLocal()) {
1750  const DeclContext *DC = Var->getDeclContext();
1751  while (!DC->isTranslationUnit()) {
1752  if (isa<FunctionDecl>(DC)) {
1753  SemaRef.Diag(D->getLocation(),
1754  diag::err_sycl_device_global_incorrect_scope);
1755  break;
1756  }
1757  DC = DC->getParent();
1758  }
1759  }
1760  }
1761  if (const auto *SYCLDevice = Var->getAttr<SYCLDeviceAttr>()) {
1762  if (!SemaRef.SYCL().isTypeDecoratedWithDeclAttribute<SYCLDeviceGlobalAttr>(
1763  Var->getType()))
1764  SemaRef.Diag(SYCLDevice->getLoc(),
1765  diag::err_sycl_attribute_not_device_global)
1766  << SYCLDevice;
1767  }
1768  SemaRef.SYCL().addSyclVarDecl(Var);
1769  }
1770 
1771  if (Var->getTLSKind())
1772  SemaRef.CheckThreadLocalForLargeAlignment(Var);
1773 
1774  return Var;
1775 }
1776 
1777 Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
1778  AccessSpecDecl* AD
1779  = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
1780  D->getAccessSpecifierLoc(), D->getColonLoc());
1781  Owner->addHiddenDecl(AD);
1782  return AD;
1783 }
1784 
1785 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
1786  bool Invalid = false;
1787  TypeSourceInfo *DI = D->getTypeSourceInfo();
1788  if (DI->getType()->isInstantiationDependentType() ||
1789  DI->getType()->isVariablyModifiedType()) {
1790  DI = SemaRef.SubstType(DI, TemplateArgs,
1791  D->getLocation(), D->getDeclName());
1792  if (!DI) {
1793  DI = D->getTypeSourceInfo();
1794  Invalid = true;
1795  } else if (DI->getType()->isFunctionType()) {
1796  // C++ [temp.arg.type]p3:
1797  // If a declaration acquires a function type through a type
1798  // dependent on a template-parameter and this causes a
1799  // declaration that does not use the syntactic form of a
1800  // function declarator to have function type, the program is
1801  // ill-formed.
1802  SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1803  << DI->getType();
1804  Invalid = true;
1805  }
1806  } else {
1808  }
1809 
1810  Expr *BitWidth = D->getBitWidth();
1811  if (Invalid)
1812  BitWidth = nullptr;
1813  else if (BitWidth) {
1814  // The bit-width expression is a constant expression.
1817 
1818  ExprResult InstantiatedBitWidth
1819  = SemaRef.SubstExpr(BitWidth, TemplateArgs);
1820  if (InstantiatedBitWidth.isInvalid()) {
1821  Invalid = true;
1822  BitWidth = nullptr;
1823  } else
1824  BitWidth = InstantiatedBitWidth.getAs<Expr>();
1825  }
1826 
1827  FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
1828  DI->getType(), DI,
1829  cast<RecordDecl>(Owner),
1830  D->getLocation(),
1831  D->isMutable(),
1832  BitWidth,
1833  D->getInClassInitStyle(),
1834  D->getInnerLocStart(),
1835  D->getAccess(),
1836  nullptr);
1837  if (!Field) {
1838  cast<Decl>(Owner)->setInvalidDecl();
1839  return nullptr;
1840  }
1841 
1842  SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
1843 
1844  if (Field->hasAttrs())
1845  SemaRef.CheckAlignasUnderalignment(Field);
1846 
1847  if (Invalid)
1848  Field->setInvalidDecl();
1849 
1850  if (!Field->getDeclName()) {
1851  // Keep track of where this decl came from.
1852  SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
1853  }
1854  if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
1855  if (Parent->isAnonymousStructOrUnion() &&
1856  Parent->getRedeclContext()->isFunctionOrMethod())
1857  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
1858  }
1859 
1860  Field->setImplicit(D->isImplicit());
1861  Field->setAccess(D->getAccess());
1862  // Static members are not processed here, so error out if we have a device
1863  // global without checking access modifier.
1864  if (SemaRef.getLangOpts().SYCLIsDevice) {
1865  if (SemaRef.SYCL().isTypeDecoratedWithDeclAttribute<SYCLDeviceGlobalAttr>(
1866  Field->getType())) {
1867  SemaRef.Diag(D->getLocation(),
1868  diag::err_sycl_device_global_incorrect_scope);
1869  Field->setInvalidDecl();
1870  return nullptr;
1871  }
1872  }
1873  Owner->addDecl(Field);
1874 
1875  return Field;
1876 }
1877 
1878 Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
1879  bool Invalid = false;
1880  TypeSourceInfo *DI = D->getTypeSourceInfo();
1881 
1882  if (DI->getType()->isVariablyModifiedType()) {
1883  SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
1884  << D;
1885  Invalid = true;
1886  } else if (DI->getType()->isInstantiationDependentType()) {
1887  DI = SemaRef.SubstType(DI, TemplateArgs,
1888  D->getLocation(), D->getDeclName());
1889  if (!DI) {
1890  DI = D->getTypeSourceInfo();
1891  Invalid = true;
1892  } else if (DI->getType()->isFunctionType()) {
1893  // C++ [temp.arg.type]p3:
1894  // If a declaration acquires a function type through a type
1895  // dependent on a template-parameter and this causes a
1896  // declaration that does not use the syntactic form of a
1897  // function declarator to have function type, the program is
1898  // ill-formed.
1899  SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1900  << DI->getType();
1901  Invalid = true;
1902  }
1903  } else {
1905  }
1906 
1908  SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
1909  DI, D->getBeginLoc(), D->getGetterId(), D->getSetterId());
1910 
1911  SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
1912  StartingScope);
1913 
1914  if (Invalid)
1915  Property->setInvalidDecl();
1916 
1917  Property->setAccess(D->getAccess());
1918  Owner->addDecl(Property);
1919 
1920  return Property;
1921 }
1922 
1923 Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
1924  NamedDecl **NamedChain =
1925  new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
1926 
1927  int i = 0;
1928  for (auto *PI : D->chain()) {
1929  NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
1930  TemplateArgs);
1931  if (!Next)
1932  return nullptr;
1933 
1934  NamedChain[i++] = Next;
1935  }
1936 
1937  QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
1939  SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
1940  {NamedChain, D->getChainingSize()});
1941 
1942  for (const auto *Attr : D->attrs())
1943  IndirectField->addAttr(Attr->clone(SemaRef.Context));
1944 
1945  IndirectField->setImplicit(D->isImplicit());
1946  IndirectField->setAccess(D->getAccess());
1947  Owner->addDecl(IndirectField);
1948  return IndirectField;
1949 }
1950 
1951 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
1952  // Handle friend type expressions by simply substituting template
1953  // parameters into the pattern type and checking the result.
1954  if (TypeSourceInfo *Ty = D->getFriendType()) {
1955  TypeSourceInfo *InstTy;
1956  // If this is an unsupported friend, don't bother substituting template
1957  // arguments into it. The actual type referred to won't be used by any
1958  // parts of Clang, and may not be valid for instantiating. Just use the
1959  // same info for the instantiated friend.
1960  if (D->isUnsupportedFriend()) {
1961  InstTy = Ty;
1962  } else {
1963  InstTy = SemaRef.SubstType(Ty, TemplateArgs,
1964  D->getLocation(), DeclarationName());
1965  }
1966  if (!InstTy)
1967  return nullptr;
1968 
1970  SemaRef.Context, Owner, D->getLocation(), InstTy, D->getFriendLoc());
1971  FD->setAccess(AS_public);
1973  Owner->addDecl(FD);
1974  return FD;
1975  }
1976 
1977  NamedDecl *ND = D->getFriendDecl();
1978  assert(ND && "friend decl must be a decl or a type!");
1979 
1980  // All of the Visit implementations for the various potential friend
1981  // declarations have to be carefully written to work for friend
1982  // objects, with the most important detail being that the target
1983  // decl should almost certainly not be placed in Owner.
1984  Decl *NewND = Visit(ND);
1985  if (!NewND) return nullptr;
1986 
1987  FriendDecl *FD =
1988  FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1989  cast<NamedDecl>(NewND), D->getFriendLoc());
1990  FD->setAccess(AS_public);
1992  Owner->addDecl(FD);
1993  return FD;
1994 }
1995 
1996 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
1997  Expr *AssertExpr = D->getAssertExpr();
1998 
1999  // The expression in a static assertion is a constant expression.
2002 
2003  ExprResult InstantiatedAssertExpr
2004  = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
2005  if (InstantiatedAssertExpr.isInvalid())
2006  return nullptr;
2007 
2008  ExprResult InstantiatedMessageExpr =
2009  SemaRef.SubstExpr(D->getMessage(), TemplateArgs);
2010  if (InstantiatedMessageExpr.isInvalid())
2011  return nullptr;
2012 
2013  return SemaRef.BuildStaticAssertDeclaration(
2014  D->getLocation(), InstantiatedAssertExpr.get(),
2015  InstantiatedMessageExpr.get(), D->getRParenLoc(), D->isFailed());
2016 }
2017 
2018 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
2019  EnumDecl *PrevDecl = nullptr;
2020  if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
2021  NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
2022  PatternPrev,
2023  TemplateArgs);
2024  if (!Prev) return nullptr;
2025  PrevDecl = cast<EnumDecl>(Prev);
2026  }
2027 
2028  EnumDecl *Enum =
2029  EnumDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
2030  D->getLocation(), D->getIdentifier(), PrevDecl,
2031  D->isScoped(), D->isScopedUsingClassTag(), D->isFixed());
2032  if (D->isFixed()) {
2033  if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
2034  // If we have type source information for the underlying type, it means it
2035  // has been explicitly set by the user. Perform substitution on it before
2036  // moving on.
2037  SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
2038  TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
2039  DeclarationName());
2040  if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
2041  Enum->setIntegerType(SemaRef.Context.IntTy);
2042  else
2043  Enum->setIntegerTypeSourceInfo(NewTI);
2044  } else {
2045  assert(!D->getIntegerType()->isDependentType()
2046  && "Dependent type without type source info");
2047  Enum->setIntegerType(D->getIntegerType());
2048  }
2049  }
2050 
2051  SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
2052 
2053  Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
2054  Enum->setAccess(D->getAccess());
2055  // Forward the mangling number from the template to the instantiated decl.
2056  SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
2057  // See if the old tag was defined along with a declarator.
2058  // If it did, mark the new tag as being associated with that declarator.
2060  SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD);
2061  // See if the old tag was defined along with a typedef.
2062  // If it did, mark the new tag as being associated with that typedef.
2064  SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND);
2065  if (SubstQualifier(D, Enum)) return nullptr;
2066  Owner->addDecl(Enum);
2067 
2068  EnumDecl *Def = D->getDefinition();
2069  if (Def && Def != D) {
2070  // If this is an out-of-line definition of an enum member template, check
2071  // that the underlying types match in the instantiation of both
2072  // declarations.
2073  if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
2074  SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
2075  QualType DefnUnderlying =
2076  SemaRef.SubstType(TI->getType(), TemplateArgs,
2077  UnderlyingLoc, DeclarationName());
2078  SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
2079  DefnUnderlying, /*IsFixed=*/true, Enum);
2080  }
2081  }
2082 
2083  // C++11 [temp.inst]p1: The implicit instantiation of a class template
2084  // specialization causes the implicit instantiation of the declarations, but
2085  // not the definitions of scoped member enumerations.
2086  //
2087  // DR1484 clarifies that enumeration definitions inside of a template
2088  // declaration aren't considered entities that can be separately instantiated
2089  // from the rest of the entity they are declared inside of.
2090  if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
2091  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
2092  InstantiateEnumDefinition(Enum, Def);
2093  }
2094 
2095  return Enum;
2096 }
2097 
2099  EnumDecl *Enum, EnumDecl *Pattern) {
2100  Enum->startDefinition();
2101 
2102  // Update the location to refer to the definition.
2103  Enum->setLocation(Pattern->getLocation());
2104 
2105  SmallVector<Decl*, 4> Enumerators;
2106 
2107  EnumConstantDecl *LastEnumConst = nullptr;
2108  for (auto *EC : Pattern->enumerators()) {
2109  // The specified value for the enumerator.
2110  ExprResult Value((Expr *)nullptr);
2111  if (Expr *UninstValue = EC->getInitExpr()) {
2112  // The enumerator's value expression is a constant expression.
2115 
2116  Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
2117  }
2118 
2119  // Drop the initial value and continue.
2120  bool isInvalid = false;
2121  if (Value.isInvalid()) {
2122  Value = nullptr;
2123  isInvalid = true;
2124  }
2125 
2126  EnumConstantDecl *EnumConst
2127  = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
2128  EC->getLocation(), EC->getIdentifier(),
2129  Value.get());
2130 
2131  if (isInvalid) {
2132  if (EnumConst)
2133  EnumConst->setInvalidDecl();
2134  Enum->setInvalidDecl();
2135  }
2136 
2137  if (EnumConst) {
2138  SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
2139 
2140  EnumConst->setAccess(Enum->getAccess());
2141  Enum->addDecl(EnumConst);
2142  Enumerators.push_back(EnumConst);
2143  LastEnumConst = EnumConst;
2144 
2145  if (Pattern->getDeclContext()->isFunctionOrMethod() &&
2146  !Enum->isScoped()) {
2147  // If the enumeration is within a function or method, record the enum
2148  // constant as a local.
2149  SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
2150  }
2151  }
2152  }
2153 
2154  SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
2155  Enumerators, nullptr, ParsedAttributesView());
2156 }
2157 
2158 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
2159  llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
2160 }
2161 
2162 Decl *
2163 TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
2164  llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
2165 }
2166 
2167 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
2168  bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2169 
2170  // Create a local instantiation scope for this class template, which
2171  // will contain the instantiations of the template parameters.
2172  LocalInstantiationScope Scope(SemaRef);
2173  TemplateParameterList *TempParams = D->getTemplateParameters();
2174  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2175  if (!InstParams)
2176  return nullptr;
2177 
2178  CXXRecordDecl *Pattern = D->getTemplatedDecl();
2179 
2180  // Instantiate the qualifier. We have to do this first in case
2181  // we're a friend declaration, because if we are then we need to put
2182  // the new declaration in the appropriate context.
2183  NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
2184  if (QualifierLoc) {
2185  QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2186  TemplateArgs);
2187  if (!QualifierLoc)
2188  return nullptr;
2189  }
2190 
2191  CXXRecordDecl *PrevDecl = nullptr;
2192  ClassTemplateDecl *PrevClassTemplate = nullptr;
2193 
2194  if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
2195  DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
2196  if (!Found.empty()) {
2197  PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
2198  if (PrevClassTemplate)
2199  PrevDecl = PrevClassTemplate->getTemplatedDecl();
2200  }
2201  }
2202 
2203  // If this isn't a friend, then it's a member template, in which
2204  // case we just want to build the instantiation in the
2205  // specialization. If it is a friend, we want to build it in
2206  // the appropriate context.
2207  DeclContext *DC = Owner;
2208  if (isFriend) {
2209  if (QualifierLoc) {
2210  CXXScopeSpec SS;
2211  SS.Adopt(QualifierLoc);
2212  DC = SemaRef.computeDeclContext(SS);
2213  if (!DC) return nullptr;
2214  } else {
2215  DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
2216  Pattern->getDeclContext(),
2217  TemplateArgs);
2218  }
2219 
2220  // Look for a previous declaration of the template in the owning
2221  // context.
2222  LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
2224  SemaRef.forRedeclarationInCurContext());
2225  SemaRef.LookupQualifiedName(R, DC);
2226 
2227  if (R.isSingleResult()) {
2228  PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
2229  if (PrevClassTemplate)
2230  PrevDecl = PrevClassTemplate->getTemplatedDecl();
2231  }
2232 
2233  if (!PrevClassTemplate && QualifierLoc) {
2234  SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
2235  << llvm::to_underlying(D->getTemplatedDecl()->getTagKind())
2236  << Pattern->getDeclName() << DC << QualifierLoc.getSourceRange();
2237  return nullptr;
2238  }
2239  }
2240 
2241  CXXRecordDecl *RecordInst = CXXRecordDecl::Create(
2242  SemaRef.Context, Pattern->getTagKind(), DC, Pattern->getBeginLoc(),
2243  Pattern->getLocation(), Pattern->getIdentifier(), PrevDecl,
2244  /*DelayTypeCreation=*/true);
2245  if (QualifierLoc)
2246  RecordInst->setQualifierInfo(QualifierLoc);
2247 
2248  SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs,
2249  StartingScope);
2250 
2251  ClassTemplateDecl *Inst
2252  = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
2253  D->getIdentifier(), InstParams, RecordInst);
2254  RecordInst->setDescribedClassTemplate(Inst);
2255 
2256  if (isFriend) {
2257  assert(!Owner->isDependentContext());
2258  Inst->setLexicalDeclContext(Owner);
2259  RecordInst->setLexicalDeclContext(Owner);
2260  Inst->setObjectOfFriendDecl();
2261 
2262  if (PrevClassTemplate) {
2263  Inst->setCommonPtr(PrevClassTemplate->getCommonPtr());
2264  RecordInst->setTypeForDecl(
2265  PrevClassTemplate->getTemplatedDecl()->getTypeForDecl());
2266  const ClassTemplateDecl *MostRecentPrevCT =
2267  PrevClassTemplate->getMostRecentDecl();
2268  TemplateParameterList *PrevParams =
2269  MostRecentPrevCT->getTemplateParameters();
2270 
2271  // Make sure the parameter lists match.
2272  if (!SemaRef.TemplateParameterListsAreEqual(
2273  RecordInst, InstParams, MostRecentPrevCT->getTemplatedDecl(),
2274  PrevParams, true, Sema::TPL_TemplateMatch))
2275  return nullptr;
2276 
2277  // Do some additional validation, then merge default arguments
2278  // from the existing declarations.
2279  if (SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
2281  return nullptr;
2282 
2283  Inst->setAccess(PrevClassTemplate->getAccess());
2284  } else {
2285  Inst->setAccess(D->getAccess());
2286  }
2287 
2288  Inst->setObjectOfFriendDecl();
2289  // TODO: do we want to track the instantiation progeny of this
2290  // friend target decl?
2291  } else {
2292  Inst->setAccess(D->getAccess());
2293  if (!PrevClassTemplate)
2295  }
2296 
2297  Inst->setPreviousDecl(PrevClassTemplate);
2298 
2299  // Trigger creation of the type for the instantiation.
2301  RecordInst, Inst->getInjectedClassNameSpecialization());
2302 
2303  // Finish handling of friends.
2304  if (isFriend) {
2305  DC->makeDeclVisibleInContext(Inst);
2306  return Inst;
2307  }
2308 
2309  if (D->isOutOfLine()) {
2311  RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
2312  }
2313 
2314  Owner->addDecl(Inst);
2315 
2316  if (!PrevClassTemplate) {
2317  // Queue up any out-of-line partial specializations of this member
2318  // class template; the client will force their instantiation once
2319  // the enclosing class has been instantiated.
2321  D->getPartialSpecializations(PartialSpecs);
2322  for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
2323  if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
2324  OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
2325  }
2326 
2327  return Inst;
2328 }
2329 
2330 Decl *
2331 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
2333  ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
2334 
2335  // Lookup the already-instantiated declaration in the instantiation
2336  // of the class template and return that.
2338  = Owner->lookup(ClassTemplate->getDeclName());
2339  if (Found.empty())
2340  return nullptr;
2341 
2342  ClassTemplateDecl *InstClassTemplate
2343  = dyn_cast<ClassTemplateDecl>(Found.front());
2344  if (!InstClassTemplate)
2345  return nullptr;
2346 
2348  = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
2349  return Result;
2350 
2351  return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
2352 }
2353 
2354 Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
2355  assert(D->getTemplatedDecl()->isStaticDataMember() &&
2356  "Only static data member templates are allowed.");
2357 
2358  // Create a local instantiation scope for this variable template, which
2359  // will contain the instantiations of the template parameters.
2360  LocalInstantiationScope Scope(SemaRef);
2361  TemplateParameterList *TempParams = D->getTemplateParameters();
2362  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2363  if (!InstParams)
2364  return nullptr;
2365 
2366  VarDecl *Pattern = D->getTemplatedDecl();
2367  VarTemplateDecl *PrevVarTemplate = nullptr;
2368 
2369  if (getPreviousDeclForInstantiation(Pattern)) {
2370  DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
2371  if (!Found.empty())
2372  PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
2373  }
2374 
2375  VarDecl *VarInst =
2376  cast_or_null<VarDecl>(VisitVarDecl(Pattern,
2377  /*InstantiatingVarTemplate=*/true));
2378  if (!VarInst) return nullptr;
2379 
2380  DeclContext *DC = Owner;
2381 
2383  SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
2384  VarInst);
2385  VarInst->setDescribedVarTemplate(Inst);
2386  Inst->setPreviousDecl(PrevVarTemplate);
2387 
2388  Inst->setAccess(D->getAccess());
2389  if (!PrevVarTemplate)
2391 
2392  if (D->isOutOfLine()) {
2395  }
2396 
2397  Owner->addDecl(Inst);
2398 
2399  if (!PrevVarTemplate) {
2400  // Queue up any out-of-line partial specializations of this member
2401  // variable template; the client will force their instantiation once
2402  // the enclosing class has been instantiated.
2404  D->getPartialSpecializations(PartialSpecs);
2405  for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
2406  if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
2407  OutOfLineVarPartialSpecs.push_back(
2408  std::make_pair(Inst, PartialSpecs[I]));
2409  }
2410 
2411  return Inst;
2412 }
2413 
2414 Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
2416  assert(D->isStaticDataMember() &&
2417  "Only static data member templates are allowed.");
2418 
2419  VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
2420 
2421  // Lookup the already-instantiated declaration and return that.
2422  DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
2423  assert(!Found.empty() && "Instantiation found nothing?");
2424 
2425  VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
2426  assert(InstVarTemplate && "Instantiation did not find a variable template?");
2427 
2429  InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
2430  return Result;
2431 
2432  return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
2433 }
2434 
2435 Decl *
2436 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
2437  // Create a local instantiation scope for this function template, which
2438  // will contain the instantiations of the template parameters and then get
2439  // merged with the local instantiation scope for the function template
2440  // itself.
2441  LocalInstantiationScope Scope(SemaRef);
2443 
2444  TemplateParameterList *TempParams = D->getTemplateParameters();
2445  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2446  if (!InstParams)
2447  return nullptr;
2448 
2449  FunctionDecl *Instantiated = nullptr;
2450  if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
2451  Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
2452  InstParams));
2453  else
2454  Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
2455  D->getTemplatedDecl(),
2456  InstParams));
2457 
2458  if (!Instantiated)
2459  return nullptr;
2460 
2461  // Link the instantiated function template declaration to the function
2462  // template from which it was instantiated.
2463  FunctionTemplateDecl *InstTemplate
2464  = Instantiated->getDescribedFunctionTemplate();
2465  InstTemplate->setAccess(D->getAccess());
2466  assert(InstTemplate &&
2467  "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
2468 
2469  bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
2470 
2471  // Link the instantiation back to the pattern *unless* this is a
2472  // non-definition friend declaration.
2473  if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
2474  !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
2475  InstTemplate->setInstantiatedFromMemberTemplate(D);
2476 
2477  // Make declarations visible in the appropriate context.
2478  if (!isFriend) {
2479  Owner->addDecl(InstTemplate);
2480  } else if (InstTemplate->getDeclContext()->isRecord() &&
2482  SemaRef.CheckFriendAccess(InstTemplate);
2483  }
2484 
2485  return InstTemplate;
2486 }
2487 
2488 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
2489  CXXRecordDecl *PrevDecl = nullptr;
2490  if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
2491  NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
2492  PatternPrev,
2493  TemplateArgs);
2494  if (!Prev) return nullptr;
2495  PrevDecl = cast<CXXRecordDecl>(Prev);
2496  }
2497 
2498  CXXRecordDecl *Record = nullptr;
2499  bool IsInjectedClassName = D->isInjectedClassName();
2500  if (D->isLambda())
2502  SemaRef.Context, Owner, D->getLambdaTypeInfo(), D->getLocation(),
2505  else
2506  Record = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
2507  D->getBeginLoc(), D->getLocation(),
2508  D->getIdentifier(), PrevDecl,
2509  /*DelayTypeCreation=*/IsInjectedClassName);
2510  // Link the type of the injected-class-name to that of the outer class.
2511  if (IsInjectedClassName)
2512  (void)SemaRef.Context.getTypeDeclType(Record, cast<CXXRecordDecl>(Owner));
2513 
2514  // Substitute the nested name specifier, if any.
2515  if (SubstQualifier(D, Record))
2516  return nullptr;
2517 
2518  SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs,
2519  StartingScope);
2520 
2521  Record->setImplicit(D->isImplicit());
2522  // FIXME: Check against AS_none is an ugly hack to work around the issue that
2523  // the tag decls introduced by friend class declarations don't have an access
2524  // specifier. Remove once this area of the code gets sorted out.
2525  if (D->getAccess() != AS_none)
2526  Record->setAccess(D->getAccess());
2527  if (!IsInjectedClassName)
2528  Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
2529 
2530  // If the original function was part of a friend declaration,
2531  // inherit its namespace state.
2532  if (D->getFriendObjectKind())
2533  Record->setObjectOfFriendDecl();
2534 
2535  // Make sure that anonymous structs and unions are recorded.
2536  if (D->isAnonymousStructOrUnion())
2537  Record->setAnonymousStructOrUnion(true);
2538 
2539  if (D->isLocalClass())
2541 
2542  // Forward the mangling number from the template to the instantiated decl.
2544  SemaRef.Context.getManglingNumber(D));
2545 
2546  // See if the old tag was defined along with a declarator.
2547  // If it did, mark the new tag as being associated with that declarator.
2550 
2551  // See if the old tag was defined along with a typedef.
2552  // If it did, mark the new tag as being associated with that typedef.
2555 
2556  Owner->addDecl(Record);
2557 
2558  // DR1484 clarifies that the members of a local class are instantiated as part
2559  // of the instantiation of their enclosing entity.
2560  if (D->isCompleteDefinition() && D->isLocalClass()) {
2561  Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef);
2562 
2563  SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
2565  /*Complain=*/true);
2566 
2567  // For nested local classes, we will instantiate the members when we
2568  // reach the end of the outermost (non-nested) local class.
2569  if (!D->isCXXClassMember())
2570  SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
2572 
2573  // This class may have local implicit instantiations that need to be
2574  // performed within this scope.
2575  LocalInstantiations.perform();
2576  }
2577 
2579 
2580  if (IsInjectedClassName)
2581  assert(Record->isInjectedClassName() && "Broken injected-class-name");
2582 
2583  return Record;
2584 }
2585 
2586 /// Adjust the given function type for an instantiation of the
2587 /// given declaration, to cope with modifications to the function's type that
2588 /// aren't reflected in the type-source information.
2589 ///
2590 /// \param D The declaration we're instantiating.
2591 /// \param TInfo The already-instantiated type.
2593  FunctionDecl *D,
2594  TypeSourceInfo *TInfo) {
2595  const FunctionProtoType *OrigFunc
2596  = D->getType()->castAs<FunctionProtoType>();
2597  const FunctionProtoType *NewFunc
2598  = TInfo->getType()->castAs<FunctionProtoType>();
2599  if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
2600  return TInfo->getType();
2601 
2602  FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
2603  NewEPI.ExtInfo = OrigFunc->getExtInfo();
2604  return Context.getFunctionType(NewFunc->getReturnType(),
2605  NewFunc->getParamTypes(), NewEPI);
2606 }
2607 
2608 /// Normal class members are of more specific types and therefore
2609 /// don't make it here. This function serves three purposes:
2610 /// 1) instantiating function templates
2611 /// 2) substituting friend and local function declarations
2612 /// 3) substituting deduction guide declarations for nested class templates
2614  FunctionDecl *D, TemplateParameterList *TemplateParams,
2615  RewriteKind FunctionRewriteKind) {
2616  // Check whether there is already a function template specialization for
2617  // this declaration.
2618  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2619  if (FunctionTemplate && !TemplateParams) {
2620  ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2621 
2622  void *InsertPos = nullptr;
2623  FunctionDecl *SpecFunc
2624  = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2625 
2626  // If we already have a function template specialization, return it.
2627  if (SpecFunc)
2628  return SpecFunc;
2629  }
2630 
2631  bool isFriend;
2632  if (FunctionTemplate)
2633  isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2634  else
2635  isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2636 
2637  bool MergeWithParentScope = (TemplateParams != nullptr) ||
2638  Owner->isFunctionOrMethod() ||
2639  !(isa<Decl>(Owner) &&
2640  cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2641  LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2642 
2643  ExplicitSpecifier InstantiatedExplicitSpecifier;
2644  if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2645  InstantiatedExplicitSpecifier = SemaRef.instantiateExplicitSpecifier(
2646  TemplateArgs, DGuide->getExplicitSpecifier());
2647  if (InstantiatedExplicitSpecifier.isInvalid())
2648  return nullptr;
2649  }
2650 
2652  TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2653  if (!TInfo)
2654  return nullptr;
2656 
2657  if (TemplateParams && TemplateParams->size()) {
2658  auto *LastParam =
2659  dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
2660  if (LastParam && LastParam->isImplicit() &&
2661  LastParam->hasTypeConstraint()) {
2662  // In abbreviated templates, the type-constraints of invented template
2663  // type parameters are instantiated with the function type, invalidating
2664  // the TemplateParameterList which relied on the template type parameter
2665  // not having a type constraint. Recreate the TemplateParameterList with
2666  // the updated parameter list.
2667  TemplateParams = TemplateParameterList::Create(
2668  SemaRef.Context, TemplateParams->getTemplateLoc(),
2669  TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
2670  TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
2671  }
2672  }
2673 
2674  NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2675  if (QualifierLoc) {
2676  QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2677  TemplateArgs);
2678  if (!QualifierLoc)
2679  return nullptr;
2680  }
2681 
2682  Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2683 
2684  // If we're instantiating a local function declaration, put the result
2685  // in the enclosing namespace; otherwise we need to find the instantiated
2686  // context.
2687  DeclContext *DC;
2688  if (D->isLocalExternDecl()) {
2689  DC = Owner;
2690  SemaRef.adjustContextForLocalExternDecl(DC);
2691  } else if (isFriend && QualifierLoc) {
2692  CXXScopeSpec SS;
2693  SS.Adopt(QualifierLoc);
2694  DC = SemaRef.computeDeclContext(SS);
2695  if (!DC) return nullptr;
2696  } else {
2697  DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
2698  TemplateArgs);
2699  }
2700 
2701  DeclarationNameInfo NameInfo
2702  = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2703 
2704  if (FunctionRewriteKind != RewriteKind::None)
2705  adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2706 
2708  if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2710  SemaRef.Context, DC, D->getInnerLocStart(),
2711  InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
2712  D->getSourceRange().getEnd(), DGuide->getCorrespondingConstructor(),
2713  DGuide->getDeductionCandidateKind());
2714  Function->setAccess(D->getAccess());
2715  } else {
2717  SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo,
2720  TrailingRequiresClause);
2721  Function->setFriendConstraintRefersToEnclosingTemplate(
2723  Function->setRangeEnd(D->getSourceRange().getEnd());
2724  }
2725 
2726  if (D->isInlined())
2727  Function->setImplicitlyInline();
2728 
2729  if (QualifierLoc)
2730  Function->setQualifierInfo(QualifierLoc);
2731 
2732  if (D->isLocalExternDecl())
2733  Function->setLocalExternDecl();
2734 
2735  DeclContext *LexicalDC = Owner;
2736  if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
2737  assert(D->getDeclContext()->isFileContext());
2738  LexicalDC = D->getDeclContext();
2739  }
2740  else if (D->isLocalExternDecl()) {
2741  LexicalDC = SemaRef.CurContext;
2742  }
2743 
2744  Function->setLexicalDeclContext(LexicalDC);
2745 
2746  // Attach the parameters
2747  for (unsigned P = 0; P < Params.size(); ++P)
2748  if (Params[P])
2749  Params[P]->setOwningFunction(Function);
2750  Function->setParams(Params);
2751 
2752  if (TrailingRequiresClause)
2753  Function->setTrailingRequiresClause(TrailingRequiresClause);
2754 
2755  if (TemplateParams) {
2756  // Our resulting instantiation is actually a function template, since we
2757  // are substituting only the outer template parameters. For example, given
2758  //
2759  // template<typename T>
2760  // struct X {
2761  // template<typename U> friend void f(T, U);
2762  // };
2763  //
2764  // X<int> x;
2765  //
2766  // We are instantiating the friend function template "f" within X<int>,
2767  // which means substituting int for T, but leaving "f" as a friend function
2768  // template.
2769  // Build the function template itself.
2770  FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
2771  Function->getLocation(),
2772  Function->getDeclName(),
2773  TemplateParams, Function);
2774  Function->setDescribedFunctionTemplate(FunctionTemplate);
2775 
2776  FunctionTemplate->setLexicalDeclContext(LexicalDC);
2777 
2778  if (isFriend && D->isThisDeclarationADefinition()) {
2779  FunctionTemplate->setInstantiatedFromMemberTemplate(
2781  }
2782  } else if (FunctionTemplate &&
2783  SemaRef.CodeSynthesisContexts.back().Kind !=
2785  // Record this function template specialization.
2786  ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2787  Function->setFunctionTemplateSpecialization(FunctionTemplate,
2789  Innermost),
2790  /*InsertPos=*/nullptr);
2791  } else if (FunctionRewriteKind == RewriteKind::None) {
2792  if (isFriend && D->isThisDeclarationADefinition()) {
2793  // Do not connect the friend to the template unless it's actually a
2794  // definition. We don't want non-template functions to be marked as being
2795  // template instantiations.
2796  Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
2797  } else if (!isFriend) {
2798  // If this is not a function template, and this is not a friend (that is,
2799  // this is a locally declared function), save the instantiation
2800  // relationship for the purposes of constraint instantiation.
2801  Function->setInstantiatedFromDecl(D);
2802  }
2803  }
2804 
2805  if (isFriend) {
2806  Function->setObjectOfFriendDecl();
2807  if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate())
2808  FT->setObjectOfFriendDecl();
2809  }
2810 
2812  Function->setInvalidDecl();
2813 
2814  bool IsExplicitSpecialization = false;
2815 
2817  SemaRef, Function->getDeclName(), SourceLocation(),
2821  : SemaRef.forRedeclarationInCurContext());
2822 
2825  assert(isFriend && "dependent specialization info on "
2826  "non-member non-friend function?");
2827 
2828  // Instantiate the explicit template arguments.
2829  TemplateArgumentListInfo ExplicitArgs;
2830  if (const auto *ArgsWritten = DFTSI->TemplateArgumentsAsWritten) {
2831  ExplicitArgs.setLAngleLoc(ArgsWritten->getLAngleLoc());
2832  ExplicitArgs.setRAngleLoc(ArgsWritten->getRAngleLoc());
2833  if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2834  ExplicitArgs))
2835  return nullptr;
2836  }
2837 
2838  // Map the candidates for the primary template to their instantiations.
2839  for (FunctionTemplateDecl *FTD : DFTSI->getCandidates()) {
2840  if (NamedDecl *ND =
2841  SemaRef.FindInstantiatedDecl(D->getLocation(), FTD, TemplateArgs))
2842  Previous.addDecl(ND);
2843  else
2844  return nullptr;
2845  }
2846 
2848  Function,
2849  DFTSI->TemplateArgumentsAsWritten ? &ExplicitArgs : nullptr,
2850  Previous))
2851  Function->setInvalidDecl();
2852 
2853  IsExplicitSpecialization = true;
2854  } else if (const ASTTemplateArgumentListInfo *ArgsWritten =
2856  // The name of this function was written as a template-id.
2857  SemaRef.LookupQualifiedName(Previous, DC);
2858 
2859  // Instantiate the explicit template arguments.
2860  TemplateArgumentListInfo ExplicitArgs(ArgsWritten->getLAngleLoc(),
2861  ArgsWritten->getRAngleLoc());
2862  if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2863  ExplicitArgs))
2864  return nullptr;
2865 
2867  &ExplicitArgs,
2868  Previous))
2869  Function->setInvalidDecl();
2870 
2871  IsExplicitSpecialization = true;
2872  } else if (TemplateParams || !FunctionTemplate) {
2873  // Look only into the namespace where the friend would be declared to
2874  // find a previous declaration. This is the innermost enclosing namespace,
2875  // as described in ActOnFriendFunctionDecl.
2877 
2878  // In C++, the previous declaration we find might be a tag type
2879  // (class or enum). In this case, the new declaration will hide the
2880  // tag type. Note that this does not apply if we're declaring a
2881  // typedef (C++ [dcl.typedef]p4).
2882  if (Previous.isSingleTagDecl())
2883  Previous.clear();
2884 
2885  // Filter out previous declarations that don't match the scope. The only
2886  // effect this has is to remove declarations found in inline namespaces
2887  // for friend declarations with unqualified names.
2888  if (isFriend && !QualifierLoc) {
2889  SemaRef.FilterLookupForScope(Previous, DC, /*Scope=*/ nullptr,
2890  /*ConsiderLinkage=*/ true,
2891  QualifierLoc.hasQualifier());
2892  }
2893  }
2894 
2895  // Per [temp.inst], default arguments in function declarations at local scope
2896  // are instantiated along with the enclosing declaration. For example:
2897  //
2898  // template<typename T>
2899  // void ft() {
2900  // void f(int = []{ return T::value; }());
2901  // }
2902  // template void ft<int>(); // error: type 'int' cannot be used prior
2903  // to '::' because it has no members
2904  //
2905  // The error is issued during instantiation of ft<int>() because substitution
2906  // into the default argument fails; the default argument is instantiated even
2907  // though it is never used.
2908  if (Function->isLocalExternDecl()) {
2909  for (ParmVarDecl *PVD : Function->parameters()) {
2910  if (!PVD->hasDefaultArg())
2911  continue;
2912  if (SemaRef.SubstDefaultArgument(D->getInnerLocStart(), PVD, TemplateArgs)) {
2913  // If substitution fails, the default argument is set to a
2914  // RecoveryExpr that wraps the uninstantiated default argument so
2915  // that downstream diagnostics are omitted.
2916  Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
2917  ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
2918  UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
2919  { UninstExpr }, UninstExpr->getType());
2920  if (ErrorResult.isUsable())
2921  PVD->setDefaultArg(ErrorResult.get());
2922  }
2923  }
2924  }
2925 
2926  SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
2927  IsExplicitSpecialization,
2928  Function->isThisDeclarationADefinition());
2929 
2930  // Check the template parameter list against the previous declaration. The
2931  // goal here is to pick up default arguments added since the friend was
2932  // declared; we know the template parameter lists match, since otherwise
2933  // we would not have picked this template as the previous declaration.
2934  if (isFriend && TemplateParams && FunctionTemplate->getPreviousDecl()) {
2936  TemplateParams,
2937  FunctionTemplate->getPreviousDecl()->getTemplateParameters(),
2938  Function->isThisDeclarationADefinition()
2941  }
2942 
2943  // If we're introducing a friend definition after the first use, trigger
2944  // instantiation.
2945  // FIXME: If this is a friend function template definition, we should check
2946  // to see if any specializations have been used.
2947  if (isFriend && D->isThisDeclarationADefinition() && Function->isUsed(false)) {
2948  if (MemberSpecializationInfo *MSInfo =
2949  Function->getMemberSpecializationInfo()) {
2950  if (MSInfo->getPointOfInstantiation().isInvalid()) {
2951  SourceLocation Loc = D->getLocation(); // FIXME
2952  MSInfo->setPointOfInstantiation(Loc);
2953  SemaRef.PendingLocalImplicitInstantiations.push_back(
2954  std::make_pair(Function, Loc));
2955  }
2956  }
2957  }
2958 
2959  if (D->isExplicitlyDefaulted()) {
2961  return nullptr;
2962  }
2963  if (D->isDeleted())
2965 
2966  NamedDecl *PrincipalDecl =
2967  (TemplateParams ? cast<NamedDecl>(FunctionTemplate) : Function);
2968 
2969  // If this declaration lives in a different context from its lexical context,
2970  // add it to the corresponding lookup table.
2971  if (isFriend ||
2972  (Function->isLocalExternDecl() && !Function->getPreviousDecl()))
2973  DC->makeDeclVisibleInContext(PrincipalDecl);
2974 
2975  if (Function->isOverloadedOperator() && !DC->isRecord() &&
2977  PrincipalDecl->setNonMemberOperator();
2978 
2979  return Function;
2980 }
2981 
2983  CXXMethodDecl *D, TemplateParameterList *TemplateParams,
2984  RewriteKind FunctionRewriteKind) {
2985  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2986  if (FunctionTemplate && !TemplateParams) {
2987  // We are creating a function template specialization from a function
2988  // template. Check whether there is already a function template
2989  // specialization for this particular set of template arguments.
2990  ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2991 
2992  void *InsertPos = nullptr;
2993  FunctionDecl *SpecFunc
2994  = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2995 
2996  // If we already have a function template specialization, return it.
2997  if (SpecFunc)
2998  return SpecFunc;
2999  }
3000 
3001  bool isFriend;
3002  if (FunctionTemplate)
3003  isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
3004  else
3005  isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
3006 
3007  bool MergeWithParentScope = (TemplateParams != nullptr) ||
3008  !(isa<Decl>(Owner) &&
3009  cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
3010  LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
3011 
3013  SemaRef, const_cast<CXXMethodDecl *>(D), TemplateArgs, Scope);
3014 
3015  // Instantiate enclosing template arguments for friends.
3017  unsigned NumTempParamLists = 0;
3018  if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
3019  TempParamLists.resize(NumTempParamLists);
3020  for (unsigned I = 0; I != NumTempParamLists; ++I) {
3021  TemplateParameterList *TempParams = D->getTemplateParameterList(I);
3022  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
3023  if (!InstParams)
3024  return nullptr;
3025  TempParamLists[I] = InstParams;
3026  }
3027  }
3028 
3029  auto InstantiatedExplicitSpecifier = ExplicitSpecifier::getFromDecl(D);
3030  // deduction guides need this
3031  const bool CouldInstantiate =
3032  InstantiatedExplicitSpecifier.getExpr() == nullptr ||
3033  !InstantiatedExplicitSpecifier.getExpr()->isValueDependent();
3034 
3035  // Delay the instantiation of the explicit-specifier until after the
3036  // constraints are checked during template argument deduction.
3037  if (CouldInstantiate ||
3038  SemaRef.CodeSynthesisContexts.back().Kind !=
3040  InstantiatedExplicitSpecifier = SemaRef.instantiateExplicitSpecifier(
3041  TemplateArgs, InstantiatedExplicitSpecifier);
3042 
3043  if (InstantiatedExplicitSpecifier.isInvalid())
3044  return nullptr;
3045  } else {
3046  InstantiatedExplicitSpecifier.setKind(ExplicitSpecKind::Unresolved);
3047  }
3048 
3049  // Implicit destructors/constructors created for local classes in
3050  // DeclareImplicit* (see SemaDeclCXX.cpp) might not have an associated TSI.
3051  // Unfortunately there isn't enough context in those functions to
3052  // conditionally populate the TSI without breaking non-template related use
3053  // cases. Populate TSIs prior to calling SubstFunctionType to make sure we get
3054  // a proper transformation.
3055  if (cast<CXXRecordDecl>(D->getParent())->isLambda() &&
3056  !D->getTypeSourceInfo() &&
3057  isa<CXXConstructorDecl, CXXDestructorDecl>(D)) {
3058  TypeSourceInfo *TSI =
3060  D->setTypeSourceInfo(TSI);
3061  }
3062 
3064  TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
3065  if (!TInfo)
3066  return nullptr;
3068 
3069  if (TemplateParams && TemplateParams->size()) {
3070  auto *LastParam =
3071  dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
3072  if (LastParam && LastParam->isImplicit() &&
3073  LastParam->hasTypeConstraint()) {
3074  // In abbreviated templates, the type-constraints of invented template
3075  // type parameters are instantiated with the function type, invalidating
3076  // the TemplateParameterList which relied on the template type parameter
3077  // not having a type constraint. Recreate the TemplateParameterList with
3078  // the updated parameter list.
3079  TemplateParams = TemplateParameterList::Create(
3080  SemaRef.Context, TemplateParams->getTemplateLoc(),
3081  TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
3082  TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
3083  }
3084  }
3085 
3086  NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
3087  if (QualifierLoc) {
3088  QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
3089  TemplateArgs);
3090  if (!QualifierLoc)
3091  return nullptr;
3092  }
3093 
3094  DeclContext *DC = Owner;
3095  if (isFriend) {
3096  if (QualifierLoc) {
3097  CXXScopeSpec SS;
3098  SS.Adopt(QualifierLoc);
3099  DC = SemaRef.computeDeclContext(SS);
3100 
3101  if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
3102  return nullptr;
3103  } else {
3104  DC = SemaRef.FindInstantiatedContext(D->getLocation(),
3105  D->getDeclContext(),
3106  TemplateArgs);
3107  }
3108  if (!DC) return nullptr;
3109  }
3110 
3111  CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
3112  Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
3113 
3114  DeclarationNameInfo NameInfo
3115  = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
3116 
3117  if (FunctionRewriteKind != RewriteKind::None)
3118  adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
3119 
3120  // Build the instantiated method declaration.
3121  CXXMethodDecl *Method = nullptr;
3122 
3123  SourceLocation StartLoc = D->getInnerLocStart();
3124  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
3125  Method = CXXConstructorDecl::Create(
3126  SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
3127  InstantiatedExplicitSpecifier, Constructor->UsesFPIntrin(),
3128  Constructor->isInlineSpecified(), false,
3129  Constructor->getConstexprKind(), InheritedConstructor(),
3130  TrailingRequiresClause);
3131  Method->setRangeEnd(Constructor->getEndLoc());
3132  } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
3133  Method = CXXDestructorDecl::Create(
3134  SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
3135  Destructor->UsesFPIntrin(), Destructor->isInlineSpecified(), false,
3136  Destructor->getConstexprKind(), TrailingRequiresClause);
3137  Method->setIneligibleOrNotSelected(true);
3138  Method->setRangeEnd(Destructor->getEndLoc());
3140  SemaRef.Context.getCanonicalType(
3141  SemaRef.Context.getTypeDeclType(Record))));
3142  } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
3143  Method = CXXConversionDecl::Create(
3144  SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
3145  Conversion->UsesFPIntrin(), Conversion->isInlineSpecified(),
3146  InstantiatedExplicitSpecifier, Conversion->getConstexprKind(),
3147  Conversion->getEndLoc(), TrailingRequiresClause);
3148  } else {
3149  StorageClass SC = D->isStatic() ? SC_Static : SC_None;
3150  Method = CXXMethodDecl::Create(
3151  SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo, SC,
3153  D->getEndLoc(), TrailingRequiresClause);
3154  }
3155 
3156  if (D->isInlined())
3157  Method->setImplicitlyInline();
3158 
3159  if (QualifierLoc)
3160  Method->setQualifierInfo(QualifierLoc);
3161 
3162  if (TemplateParams) {
3163  // Our resulting instantiation is actually a function template, since we
3164  // are substituting only the outer template parameters. For example, given
3165  //
3166  // template<typename T>
3167  // struct X {
3168  // template<typename U> void f(T, U);
3169  // };
3170  //
3171  // X<int> x;
3172  //
3173  // We are instantiating the member template "f" within X<int>, which means
3174  // substituting int for T, but leaving "f" as a member function template.
3175  // Build the function template itself.
3176  FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
3177  Method->getLocation(),
3178  Method->getDeclName(),
3179  TemplateParams, Method);
3180  if (isFriend) {
3181  FunctionTemplate->setLexicalDeclContext(Owner);
3182  FunctionTemplate->setObjectOfFriendDecl();
3183  } else if (D->isOutOfLine())
3184  FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
3185  Method->setDescribedFunctionTemplate(FunctionTemplate);
3186  } else if (FunctionTemplate) {
3187  // Record this function template specialization.
3188  ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
3189  Method->setFunctionTemplateSpecialization(FunctionTemplate,
3191  Innermost),
3192  /*InsertPos=*/nullptr);
3193  } else if (!isFriend && FunctionRewriteKind == RewriteKind::None) {
3194  // Record that this is an instantiation of a member function.
3196  }
3197 
3198  // If we are instantiating a member function defined
3199  // out-of-line, the instantiation will have the same lexical
3200  // context (which will be a namespace scope) as the template.
3201  if (isFriend) {
3202  if (NumTempParamLists)
3204  SemaRef.Context,
3205  llvm::ArrayRef(TempParamLists.data(), NumTempParamLists));
3206 
3207  Method->setLexicalDeclContext(Owner);
3208  Method->setObjectOfFriendDecl();
3209  } else if (D->isOutOfLine())
3211 
3212  // Attach the parameters
3213  for (unsigned P = 0; P < Params.size(); ++P)
3214  Params[P]->setOwningFunction(Method);
3215  Method->setParams(Params);
3216 
3217  if (InitMethodInstantiation(Method, D))
3218  Method->setInvalidDecl();
3219 
3220  LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
3222 
3223  bool IsExplicitSpecialization = false;
3224 
3225  // If the name of this function was written as a template-id, instantiate
3226  // the explicit template arguments.
3229  // Instantiate the explicit template arguments.
3230  TemplateArgumentListInfo ExplicitArgs;
3231  if (const auto *ArgsWritten = DFTSI->TemplateArgumentsAsWritten) {
3232  ExplicitArgs.setLAngleLoc(ArgsWritten->getLAngleLoc());
3233  ExplicitArgs.setRAngleLoc(ArgsWritten->getRAngleLoc());
3234  if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
3235  ExplicitArgs))
3236  return nullptr;
3237  }
3238 
3239  // Map the candidates for the primary template to their instantiations.
3240  for (FunctionTemplateDecl *FTD : DFTSI->getCandidates()) {
3241  if (NamedDecl *ND =
3242  SemaRef.FindInstantiatedDecl(D->getLocation(), FTD, TemplateArgs))
3243  Previous.addDecl(ND);
3244  else
3245  return nullptr;
3246  }
3247 
3249  Method, DFTSI->TemplateArgumentsAsWritten ? &ExplicitArgs : nullptr,
3250  Previous))
3251  Method->setInvalidDecl();
3252 
3253  IsExplicitSpecialization = true;
3254  } else if (const ASTTemplateArgumentListInfo *ArgsWritten =
3256  SemaRef.LookupQualifiedName(Previous, DC);
3257 
3258  TemplateArgumentListInfo ExplicitArgs(ArgsWritten->getLAngleLoc(),
3259  ArgsWritten->getRAngleLoc());
3260 
3261  if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
3262  ExplicitArgs))
3263  return nullptr;
3264 
3265  if (SemaRef.CheckFunctionTemplateSpecialization(Method,
3266  &ExplicitArgs,
3267  Previous))
3268  Method->setInvalidDecl();
3269 
3270  IsExplicitSpecialization = true;
3271  } else if (!FunctionTemplate || TemplateParams || isFriend) {
3273 
3274  // In C++, the previous declaration we find might be a tag type
3275  // (class or enum). In this case, the new declaration will hide the
3276  // tag type. Note that this does not apply if we're declaring a
3277  // typedef (C++ [dcl.typedef]p4).
3278  if (Previous.isSingleTagDecl())
3279  Previous.clear();
3280  }
3281 
3282  // Per [temp.inst], default arguments in member functions of local classes
3283  // are instantiated along with the member function declaration. For example:
3284  //
3285  // template<typename T>
3286  // void ft() {
3287  // struct lc {
3288  // int operator()(int p = []{ return T::value; }());
3289  // };
3290  // }
3291  // template void ft<int>(); // error: type 'int' cannot be used prior
3292  // to '::'because it has no members
3293  //
3294  // The error is issued during instantiation of ft<int>()::lc::operator()
3295  // because substitution into the default argument fails; the default argument
3296  // is instantiated even though it is never used.
3297  if (D->isInLocalScopeForInstantiation()) {
3298  for (unsigned P = 0; P < Params.size(); ++P) {
3299  if (!Params[P]->hasDefaultArg())
3300  continue;
3301  if (SemaRef.SubstDefaultArgument(StartLoc, Params[P], TemplateArgs)) {
3302  // If substitution fails, the default argument is set to a
3303  // RecoveryExpr that wraps the uninstantiated default argument so
3304  // that downstream diagnostics are omitted.
3305  Expr *UninstExpr = Params[P]->getUninstantiatedDefaultArg();
3306  ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
3307  UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
3308  { UninstExpr }, UninstExpr->getType());
3309  if (ErrorResult.isUsable())
3310  Params[P]->setDefaultArg(ErrorResult.get());
3311  }
3312  }
3313  }
3314 
3315  SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous,
3316  IsExplicitSpecialization,
3317  Method->isThisDeclarationADefinition());
3318 
3319  if (D->isPureVirtual())
3320  SemaRef.CheckPureMethod(Method, SourceRange());
3321 
3322  // Propagate access. For a non-friend declaration, the access is
3323  // whatever we're propagating from. For a friend, it should be the
3324  // previous declaration we just found.
3325  if (isFriend && Method->getPreviousDecl())
3326  Method->setAccess(Method->getPreviousDecl()->getAccess());
3327  else
3328  Method->setAccess(D->getAccess());
3329  if (FunctionTemplate)
3330  FunctionTemplate->setAccess(Method->getAccess());
3331 
3332  SemaRef.CheckOverrideControl(Method);
3333 
3334  // If a function is defined as defaulted or deleted, mark it as such now.
3335  if (D->isExplicitlyDefaulted()) {
3336  if (SubstDefaultedFunction(Method, D))
3337  return nullptr;
3338  }
3339  if (D->isDeletedAsWritten())
3340  SemaRef.SetDeclDeleted(Method, Method->getLocation(),
3341  D->getDeletedMessage());
3342 
3343  // If this is an explicit specialization, mark the implicitly-instantiated
3344  // template specialization as being an explicit specialization too.
3345  // FIXME: Is this necessary?
3346  if (IsExplicitSpecialization && !isFriend)
3347  SemaRef.CompleteMemberSpecialization(Method, Previous);
3348 
3349  // If the method is a special member function, we need to mark it as
3350  // ineligible so that Owner->addDecl() won't mark the class as non trivial.
3351  // At the end of the class instantiation, we calculate eligibility again and
3352  // then we adjust trivility if needed.
3353  // We need this check to happen only after the method parameters are set,
3354  // because being e.g. a copy constructor depends on the instantiated
3355  // arguments.
3356  if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Method)) {
3357  if (Constructor->isDefaultConstructor() ||
3358  Constructor->isCopyOrMoveConstructor())
3359  Method->setIneligibleOrNotSelected(true);
3360  } else if (Method->isCopyAssignmentOperator() ||
3361  Method->isMoveAssignmentOperator()) {
3362  Method->setIneligibleOrNotSelected(true);
3363  }
3364 
3365  // If there's a function template, let our caller handle it.
3366  if (FunctionTemplate) {
3367  // do nothing
3368 
3369  // Don't hide a (potentially) valid declaration with an invalid one.
3370  } else if (Method->isInvalidDecl() && !Previous.empty()) {
3371  // do nothing
3372 
3373  // Otherwise, check access to friends and make them visible.
3374  } else if (isFriend) {
3375  // We only need to re-check access for methods which we didn't
3376  // manage to match during parsing.
3377  if (!D->getPreviousDecl())
3378  SemaRef.CheckFriendAccess(Method);
3379 
3380  Record->makeDeclVisibleInContext(Method);
3381 
3382  // Otherwise, add the declaration. We don't need to do this for
3383  // class-scope specializations because we'll have matched them with
3384  // the appropriate template.
3385  } else {
3386  Owner->addDecl(Method);
3387  }
3388 
3389  // PR17480: Honor the used attribute to instantiate member function
3390  // definitions
3391  if (Method->hasAttr<UsedAttr>()) {
3392  if (const auto *A = dyn_cast<CXXRecordDecl>(Owner)) {
3394  if (const MemberSpecializationInfo *MSInfo =
3395  A->getMemberSpecializationInfo())
3396  Loc = MSInfo->getPointOfInstantiation();
3397  else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(A))
3398  Loc = Spec->getPointOfInstantiation();
3399  SemaRef.MarkFunctionReferenced(Loc, Method);
3400  }
3401  }
3402 
3403  return Method;
3404 }
3405 
3406 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
3407  return VisitCXXMethodDecl(D);
3408 }
3409 
3410 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
3411  return VisitCXXMethodDecl(D);
3412 }
3413 
3414 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
3415  return VisitCXXMethodDecl(D);
3416 }
3417 
3418 Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
3419  return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0,
3420  std::nullopt,
3421  /*ExpectParameterPack=*/false);
3422 }
3423 
3424 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
3425  TemplateTypeParmDecl *D) {
3426  assert(D->getTypeForDecl()->isTemplateTypeParmType());
3427 
3428  std::optional<unsigned> NumExpanded;
3429 
3430  if (const TypeConstraint *TC = D->getTypeConstraint()) {
3431  if (D->isPackExpansion() && !D->isExpandedParameterPack()) {
3432  assert(TC->getTemplateArgsAsWritten() &&
3433  "type parameter can only be an expansion when explicit arguments "
3434  "are specified");
3435  // The template type parameter pack's type is a pack expansion of types.
3436  // Determine whether we need to expand this parameter pack into separate
3437  // types.
3439  for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
3440  SemaRef.collectUnexpandedParameterPacks(ArgLoc, Unexpanded);
3441 
3442  // Determine whether the set of unexpanded parameter packs can and should
3443  // be expanded.
3444  bool Expand = true;
3445  bool RetainExpansion = false;
3446  if (SemaRef.CheckParameterPacksForExpansion(
3447  cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
3448  ->getEllipsisLoc(),
3449  SourceRange(TC->getConceptNameLoc(),
3450  TC->hasExplicitTemplateArgs() ?
3451  TC->getTemplateArgsAsWritten()->getRAngleLoc() :
3452  TC->getConceptNameInfo().getEndLoc()),
3453  Unexpanded, TemplateArgs, Expand, RetainExpansion, NumExpanded))
3454  return nullptr;
3455  }
3456  }
3457 
3459  SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(),
3460  D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
3462  D->hasTypeConstraint(), NumExpanded);
3463 
3464  Inst->setAccess(AS_public);
3465  Inst->setImplicit(D->isImplicit());
3466  if (auto *TC = D->getTypeConstraint()) {
3467  if (!D->isImplicit()) {
3468  // Invented template parameter type constraints will be instantiated
3469  // with the corresponding auto-typed parameter as it might reference
3470  // other parameters.
3471  if (SemaRef.SubstTypeConstraint(Inst, TC, TemplateArgs,
3472  EvaluateConstraints))
3473  return nullptr;
3474  }
3475  }
3476  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
3477  TemplateArgumentLoc Output;
3478  if (!SemaRef.SubstTemplateArgument(D->getDefaultArgument(), TemplateArgs,
3479  Output))
3480  Inst->setDefaultArgument(SemaRef.getASTContext(), Output);
3481  }
3482 
3483  // Introduce this template parameter's instantiation into the instantiation
3484  // scope.
3485  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
3486 
3487  return Inst;
3488 }
3489 
3490 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
3492  // Substitute into the type of the non-type template parameter.
3493  TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
3494  SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
3495  SmallVector<QualType, 4> ExpandedParameterPackTypes;
3496  bool IsExpandedParameterPack = false;
3497  TypeSourceInfo *DI;
3498  QualType T;
3499  bool Invalid = false;
3500 
3501  if (D->isExpandedParameterPack()) {
3502  // The non-type template parameter pack is an already-expanded pack
3503  // expansion of types. Substitute into each of the expanded types.
3504  ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
3505  ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
3506  for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
3507  TypeSourceInfo *NewDI =
3508  SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
3509  D->getLocation(), D->getDeclName());
3510  if (!NewDI)
3511  return nullptr;
3512 
3513  QualType NewT =
3514  SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
3515  if (NewT.isNull())
3516  return nullptr;
3517 
3518  ExpandedParameterPackTypesAsWritten.push_back(NewDI);
3519  ExpandedParameterPackTypes.push_back(NewT);
3520  }
3521 
3522  IsExpandedParameterPack = true;
3523  DI = D->getTypeSourceInfo();
3524  T = DI->getType();
3525  } else if (D->isPackExpansion()) {
3526  // The non-type template parameter pack's type is a pack expansion of types.
3527  // Determine whether we need to expand this parameter pack into separate
3528  // types.
3530  TypeLoc Pattern = Expansion.getPatternLoc();
3532  SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
3533 
3534  // Determine whether the set of unexpanded parameter packs can and should
3535  // be expanded.
3536  bool Expand = true;
3537  bool RetainExpansion = false;
3538  std::optional<unsigned> OrigNumExpansions =
3539  Expansion.getTypePtr()->getNumExpansions();
3540  std::optional<unsigned> NumExpansions = OrigNumExpansions;
3541  if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
3542  Pattern.getSourceRange(),
3543  Unexpanded,
3544  TemplateArgs,
3545  Expand, RetainExpansion,
3546  NumExpansions))
3547  return nullptr;
3548 
3549  if (Expand) {
3550  for (unsigned I = 0; I != *NumExpansions; ++I) {
3551  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3552  TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
3553  D->getLocation(),
3554  D->getDeclName());
3555  if (!NewDI)
3556  return nullptr;
3557 
3558  QualType NewT =
3559  SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
3560  if (NewT.isNull())
3561  return nullptr;
3562 
3563  ExpandedParameterPackTypesAsWritten.push_back(NewDI);
3564  ExpandedParameterPackTypes.push_back(NewT);
3565  }
3566 
3567  // Note that we have an expanded parameter pack. The "type" of this
3568  // expanded parameter pack is the original expansion type, but callers
3569  // will end up using the expanded parameter pack types for type-checking.
3570  IsExpandedParameterPack = true;
3571  DI = D->getTypeSourceInfo();
3572  T = DI->getType();
3573  } else {
3574  // We cannot fully expand the pack expansion now, so substitute into the
3575  // pattern and create a new pack expansion type.
3576  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3577  TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
3578  D->getLocation(),
3579  D->getDeclName());
3580  if (!NewPattern)
3581  return nullptr;
3582 
3583  SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
3584  DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
3585  NumExpansions);
3586  if (!DI)
3587  return nullptr;
3588 
3589  T = DI->getType();
3590  }
3591  } else {
3592  // Simple case: substitution into a parameter that is not a parameter pack.
3593  DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
3594  D->getLocation(), D->getDeclName());
3595  if (!DI)
3596  return nullptr;
3597 
3598  // Check that this type is acceptable for a non-type template parameter.
3599  T = SemaRef.CheckNonTypeTemplateParameterType(DI, D->getLocation());
3600  if (T.isNull()) {
3601  T = SemaRef.Context.IntTy;
3602  Invalid = true;
3603  }
3604  }
3605 
3606  NonTypeTemplateParmDecl *Param;
3607  if (IsExpandedParameterPack)
3609  SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3610  D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3611  D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
3612  ExpandedParameterPackTypesAsWritten);
3613  else
3615  SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3616  D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3617  D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI);
3618 
3619  if (AutoTypeLoc AutoLoc = DI->getTypeLoc().getContainedAutoTypeLoc())
3620  if (AutoLoc.isConstrained()) {
3621  SourceLocation EllipsisLoc;
3622  if (IsExpandedParameterPack)
3623  EllipsisLoc =
3624  DI->getTypeLoc().getAs<PackExpansionTypeLoc>().getEllipsisLoc();
3625  else if (auto *Constraint = dyn_cast_if_present<CXXFoldExpr>(
3627  EllipsisLoc = Constraint->getEllipsisLoc();
3628  // Note: We attach the uninstantiated constriant here, so that it can be
3629  // instantiated relative to the top level, like all our other
3630  // constraints.
3631  if (SemaRef.AttachTypeConstraint(AutoLoc, /*NewConstrainedParm=*/Param,
3632  /*OrigConstrainedParm=*/D, EllipsisLoc))
3633  Invalid = true;
3634  }
3635 
3636  Param->setAccess(AS_public);
3637  Param->setImplicit(D->isImplicit());
3638  if (Invalid)
3639  Param->setInvalidDecl();
3640 
3641  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
3642  EnterExpressionEvaluationContext ConstantEvaluated(
3644  TemplateArgumentLoc Result;
3645  if (!SemaRef.SubstTemplateArgument(D->getDefaultArgument(), TemplateArgs,
3646  Result))
3647  Param->setDefaultArgument(SemaRef.Context, Result);
3648  }
3649 
3650  // Introduce this template parameter's instantiation into the instantiation
3651  // scope.
3652  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
3653  return Param;
3654 }
3655 
3657  Sema &S,
3658  TemplateParameterList *Params,
3660  for (const auto &P : *Params) {
3661  if (P->isTemplateParameterPack())
3662  continue;
3663  if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
3664  S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
3665  Unexpanded);
3666  if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
3667  collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
3668  Unexpanded);
3669  }
3670 }
3671 
3672 Decl *
3673 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
3675  // Instantiate the template parameter list of the template template parameter.
3676  TemplateParameterList *TempParams = D->getTemplateParameters();
3677  TemplateParameterList *InstParams;
3679 
3680  bool IsExpandedParameterPack = false;
3681 
3682  if (D->isExpandedParameterPack()) {
3683  // The template template parameter pack is an already-expanded pack
3684  // expansion of template parameters. Substitute into each of the expanded
3685  // parameters.
3686  ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
3687  for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
3688  I != N; ++I) {
3689  LocalInstantiationScope Scope(SemaRef);
3690  TemplateParameterList *Expansion =
3692  if (!Expansion)
3693  return nullptr;
3694  ExpandedParams.push_back(Expansion);
3695  }
3696 
3697  IsExpandedParameterPack = true;
3698  InstParams = TempParams;
3699  } else if (D->isPackExpansion()) {
3700  // The template template parameter pack expands to a pack of template
3701  // template parameters. Determine whether we need to expand this parameter
3702  // pack into separate parameters.
3705  Unexpanded);
3706 
3707  // Determine whether the set of unexpanded parameter packs can and should
3708  // be expanded.
3709  bool Expand = true;
3710  bool RetainExpansion = false;
3711  std::optional<unsigned> NumExpansions;
3713  TempParams->getSourceRange(),
3714  Unexpanded,
3715  TemplateArgs,
3716  Expand, RetainExpansion,
3717  NumExpansions))
3718  return nullptr;
3719 
3720  if (Expand) {
3721  for (unsigned I = 0; I != *NumExpansions; ++I) {
3722  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3723  LocalInstantiationScope Scope(SemaRef);
3724  TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
3725  if (!Expansion)
3726  return nullptr;
3727  ExpandedParams.push_back(Expansion);
3728  }
3729 
3730  // Note that we have an expanded parameter pack. The "type" of this
3731  // expanded parameter pack is the original expansion type, but callers
3732  // will end up using the expanded parameter pack types for type-checking.
3733  IsExpandedParameterPack = true;
3734  InstParams = TempParams;
3735  } else {
3736  // We cannot fully expand the pack expansion now, so just substitute
3737  // into the pattern.
3738  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3739 
3740  LocalInstantiationScope Scope(SemaRef);
3741  InstParams = SubstTemplateParams(TempParams);
3742  if (!InstParams)
3743  return nullptr;
3744  }
3745  } else {
3746  // Perform the actual substitution of template parameters within a new,
3747  // local instantiation scope.
3748  LocalInstantiationScope Scope(SemaRef);
3749  InstParams = SubstTemplateParams(TempParams);
3750  if (!InstParams)
3751  return nullptr;
3752  }
3753 
3754  // Build the template template parameter.
3755  TemplateTemplateParmDecl *Param;
3756  if (IsExpandedParameterPack)
3758  SemaRef.Context, Owner, D->getLocation(),
3759  D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3761  InstParams, ExpandedParams);
3762  else
3764  SemaRef.Context, Owner, D->getLocation(),
3765  D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3766  D->getPosition(), D->isParameterPack(), D->getIdentifier(),
3767  D->wasDeclaredWithTypename(), InstParams);
3768  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
3769  NestedNameSpecifierLoc QualifierLoc =
3771  QualifierLoc =
3772  SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
3773  TemplateName TName = SemaRef.SubstTemplateName(
3774  QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
3775  D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
3776  if (!TName.isNull())
3777  Param->setDefaultArgument(
3778  SemaRef.Context,
3782  }
3783  Param->setAccess(AS_public);
3784  Param->setImplicit(D->isImplicit());
3785 
3786  // Introduce this template parameter's instantiation into the instantiation
3787  // scope.
3788  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
3789 
3790  return Param;
3791 }
3792 
3793 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
3794  // Using directives are never dependent (and never contain any types or
3795  // expressions), so they require no explicit instantiation work.
3796 
3797  UsingDirectiveDecl *Inst
3798  = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
3800  D->getQualifierLoc(),
3801  D->getIdentLocation(),
3802  D->getNominatedNamespace(),
3803  D->getCommonAncestor());
3804 
3805  // Add the using directive to its declaration context
3806  // only if this is not a function or method.
3807  if (!Owner->isFunctionOrMethod())
3808  Owner->addDecl(Inst);
3809 
3810  return Inst;
3811 }
3812 
3814  BaseUsingDecl *Inst,
3815  LookupResult *Lookup) {
3816 
3817  bool isFunctionScope = Owner->isFunctionOrMethod();
3818 
3819  for (auto *Shadow : D->shadows()) {
3820  // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
3821  // reconstruct it in the case where it matters. Hm, can we extract it from
3822  // the DeclSpec when parsing and save it in the UsingDecl itself?
3823  NamedDecl *OldTarget = Shadow->getTargetDecl();
3824  if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
3825  if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
3826  OldTarget = BaseShadow;
3827 
3828  NamedDecl *InstTarget = nullptr;
3829  if (auto *EmptyD =
3830  dyn_cast<UnresolvedUsingIfExistsDecl>(Shadow->getTargetDecl())) {
3832  SemaRef.Context, Owner, EmptyD->getLocation(), EmptyD->getDeclName());
3833  } else {
3834  InstTarget = cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
3835  Shadow->getLocation(), OldTarget, TemplateArgs));
3836  }
3837  if (!InstTarget)
3838  return nullptr;
3839 
3840  UsingShadowDecl *PrevDecl = nullptr;
3841  if (Lookup &&
3842  SemaRef.CheckUsingShadowDecl(Inst, InstTarget, *Lookup, PrevDecl))
3843  continue;
3844 
3845  if (UsingShadowDecl *OldPrev = getPreviousDeclForInstantiation(Shadow))
3846  PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
3847  Shadow->getLocation(), OldPrev, TemplateArgs));
3848 
3849  UsingShadowDecl *InstShadow = SemaRef.BuildUsingShadowDecl(
3850  /*Scope*/ nullptr, Inst, InstTarget, PrevDecl);
3851  SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
3852 
3853  if (isFunctionScope)
3854  SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
3855  }
3856 
3857  return Inst;
3858 }
3859 
3860 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
3861 
3862  // The nested name specifier may be dependent, for example
3863  // template <typename T> struct t {
3864  // struct s1 { T f1(); };
3865  // struct s2 : s1 { using s1::f1; };
3866  // };
3867  // template struct t<int>;
3868  // Here, in using s1::f1, s1 refers to t<T>::s1;
3869  // we need to substitute for t<int>::s1.
3870  NestedNameSpecifierLoc QualifierLoc
3872  TemplateArgs);
3873  if (!QualifierLoc)
3874  return nullptr;
3875 
3876  // For an inheriting constructor declaration, the name of the using
3877  // declaration is the name of a constructor in this class, not in the
3878  // base class.
3879  DeclarationNameInfo NameInfo = D->getNameInfo();
3881  if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
3883  SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
3884 
3885  // We only need to do redeclaration lookups if we're in a class scope (in
3886  // fact, it's not really even possible in non-class scopes).
3887  bool CheckRedeclaration = Owner->isRecord();
3888  LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
3890 
3891  UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
3892  D->getUsingLoc(),
3893  QualifierLoc,
3894  NameInfo,
3895  D->hasTypename());
3896 
3897  CXXScopeSpec SS;
3898  SS.Adopt(QualifierLoc);
3899  if (CheckRedeclaration) {
3900  Prev.setHideTags(false);
3901  SemaRef.LookupQualifiedName(Prev, Owner);
3902 
3903  // Check for invalid redeclarations.
3904  if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
3905  D->hasTypename(), SS,
3906  D->getLocation(), Prev))
3907  NewUD->setInvalidDecl();
3908  }
3909 
3910  if (!NewUD->isInvalidDecl() &&
3911  SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(), SS,
3912  NameInfo, D->getLocation(), nullptr, D))
3913  NewUD->setInvalidDecl();
3914 
3915  SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
3916  NewUD->setAccess(D->getAccess());
3917  Owner->addDecl(NewUD);
3918 
3919  // Don't process the shadow decls for an invalid decl.
3920  if (NewUD->isInvalidDecl())
3921  return NewUD;
3922 
3923  // If the using scope was dependent, or we had dependent bases, we need to
3924  // recheck the inheritance
3926  SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
3927 
3928  return VisitBaseUsingDecls(D, NewUD, CheckRedeclaration ? &Prev : nullptr);
3929 }
3930 
3931 Decl *TemplateDeclInstantiator::VisitUsingEnumDecl(UsingEnumDecl *D) {
3932  // Cannot be a dependent type, but still could be an instantiation
3933  EnumDecl *EnumD = cast_or_null<EnumDecl>(SemaRef.FindInstantiatedDecl(
3934  D->getLocation(), D->getEnumDecl(), TemplateArgs));
3935 
3936  if (SemaRef.RequireCompleteEnumDecl(EnumD, EnumD->getLocation()))
3937  return nullptr;
3938 
3939  TypeSourceInfo *TSI = SemaRef.SubstType(D->getEnumType(), TemplateArgs,
3940  D->getLocation(), D->getDeclName());
3941  UsingEnumDecl *NewUD =
3942  UsingEnumDecl::Create(SemaRef.Context, Owner, D->getUsingLoc(),
3943  D->getEnumLoc(), D->getLocation(), TSI);
3944 
3945  SemaRef.Context.setInstantiatedFromUsingEnumDecl(NewUD, D);
3946  NewUD->setAccess(D->getAccess());
3947  Owner->addDecl(NewUD);
3948 
3949  // Don't process the shadow decls for an invalid decl.
3950  if (NewUD->isInvalidDecl())
3951  return NewUD;
3952 
3953  // We don't have to recheck for duplication of the UsingEnumDecl itself, as it
3954  // cannot be dependent, and will therefore have been checked during template
3955  // definition.
3956 
3957  return VisitBaseUsingDecls(D, NewUD, nullptr);
3958 }
3959 
3960 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
3961  // Ignore these; we handle them in bulk when processing the UsingDecl.
3962  return nullptr;
3963 }
3964 
3965 Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
3967  // Ignore these; we handle them in bulk when processing the UsingDecl.
3968  return nullptr;
3969 }
3970 
3971 template <typename T>
3972 Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
3973  T *D, bool InstantiatingPackElement) {
3974  // If this is a pack expansion, expand it now.
3975  if (D->isPackExpansion() && !InstantiatingPackElement) {
3977  SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
3978  SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
3979 
3980  // Determine whether the set of unexpanded parameter packs can and should
3981  // be expanded.
3982  bool Expand = true;
3983  bool RetainExpansion = false;
3984  std::optional<unsigned> NumExpansions;
3985  if (SemaRef.CheckParameterPacksForExpansion(
3986  D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
3987  Expand, RetainExpansion, NumExpansions))
3988  return nullptr;
3989 
3990  // This declaration cannot appear within a function template signature,
3991  // so we can't have a partial argument list for a parameter pack.
3992  assert(!RetainExpansion &&
3993  "should never need to retain an expansion for UsingPackDecl");
3994 
3995  if (!Expand) {
3996  // We cannot fully expand the pack expansion now, so substitute into the
3997  // pattern and create a new pack expansion.
3998  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3999  return instantiateUnresolvedUsingDecl(D, true);
4000  }
4001 
4002  // Within a function, we don't have any normal way to check for conflicts
4003  // between shadow declarations from different using declarations in the
4004  // same pack expansion, but this is always ill-formed because all expansions
4005  // must produce (conflicting) enumerators.
4006  //
4007  // Sadly we can't just reject this in the template definition because it
4008  // could be valid if the pack is empty or has exactly one expansion.
4009  if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) {
4010  SemaRef.Diag(D->getEllipsisLoc(),
4011  diag::err_using_decl_redeclaration_expansion);
4012  return nullptr;
4013  }
4014 
4015  // Instantiate the slices of this pack and build a UsingPackDecl.
4016  SmallVector<NamedDecl*, 8> Expansions;
4017  for (unsigned I = 0; I != *NumExpansions; ++I) {
4018  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
4019  Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
4020  if (!Slice)
4021  return nullptr;
4022  // Note that we can still get unresolved using declarations here, if we
4023  // had arguments for all packs but the pattern also contained other
4024  // template arguments (this only happens during partial substitution, eg
4025  // into the body of a generic lambda in a function template).
4026  Expansions.push_back(cast<NamedDecl>(Slice));
4027  }
4028 
4029  auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
4030  if (isDeclWithinFunction(D))
4031  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
4032  return NewD;
4033  }
4034 
4035  UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
4036  SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation();
4037 
4038  NestedNameSpecifierLoc QualifierLoc
4039  = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
4040  TemplateArgs);
4041  if (!QualifierLoc)
4042  return nullptr;
4043 
4044  CXXScopeSpec SS;
4045  SS.Adopt(QualifierLoc);
4046 
4047  DeclarationNameInfo NameInfo
4048  = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
4049 
4050  // Produce a pack expansion only if we're not instantiating a particular
4051  // slice of a pack expansion.
4052  bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
4053  SemaRef.ArgumentPackSubstitutionIndex != -1;
4054  SourceLocation EllipsisLoc =
4055  InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc();
4056 
4057  bool IsUsingIfExists = D->template hasAttr<UsingIfExistsAttr>();
4058  NamedDecl *UD = SemaRef.BuildUsingDeclaration(
4059  /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
4060  /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
4062  /*IsInstantiation*/ true, IsUsingIfExists);
4063  if (UD) {
4064  SemaRef.InstantiateAttrs(TemplateArgs, D, UD);
4065  SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
4066  }
4067 
4068  return UD;
4069 }
4070 
4071 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
4073  return instantiateUnresolvedUsingDecl(D);
4074 }
4075 
4076 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
4078  return instantiateUnresolvedUsingDecl(D);
4079 }
4080 
4081 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingIfExistsDecl(
4083  llvm_unreachable("referring to unresolved decl out of UsingShadowDecl");
4084 }
4085 
4086 Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
4087  SmallVector<NamedDecl*, 8> Expansions;
4088  for (auto *UD : D->expansions()) {
4089  if (NamedDecl *NewUD =
4090  SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
4091  Expansions.push_back(NewUD);
4092  else
4093  return nullptr;
4094  }
4095 
4096  auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
4097  if (isDeclWithinFunction(D))
4098  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
4099  return NewD;
4100 }
4101 
4102 Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
4103  OMPThreadPrivateDecl *D) {
4105  for (auto *I : D->varlists()) {
4106  Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
4107  assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
4108  Vars.push_back(Var);
4109  }
4110 
4111  OMPThreadPrivateDecl *TD =
4112  SemaRef.OpenMP().CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
4113 
4114  TD->setAccess(AS_public);
4115  Owner->addDecl(TD);
4116 
4117  return TD;
4118 }
4119 
4120 Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
4122  for (auto *I : D->varlists()) {
4123  Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
4124  assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr");
4125  Vars.push_back(Var);
4126  }
4128  // Copy map clauses from the original mapper.
4129  for (OMPClause *C : D->clauselists()) {
4130  OMPClause *IC = nullptr;
4131  if (auto *AC = dyn_cast<OMPAllocatorClause>(C)) {
4132  ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs);
4133  if (!NewE.isUsable())
4134  continue;
4135  IC = SemaRef.OpenMP().ActOnOpenMPAllocatorClause(
4136  NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
4137  } else if (auto *AC = dyn_cast<OMPAlignClause>(C)) {
4138  ExprResult NewE = SemaRef.SubstExpr(AC->getAlignment(), TemplateArgs);
4139  if (!NewE.isUsable())
4140  continue;
4141  IC = SemaRef.OpenMP().ActOnOpenMPAlignClause(
4142  NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
4143  // If align clause value ends up being invalid, this can end up null.
4144  if (!IC)
4145  continue;
4146  }
4147  Clauses.push_back(IC);
4148  }
4149 
4151  D->getLocation(), Vars, Clauses, Owner);
4152  if (Res.get().isNull())
4153  return nullptr;
4154  return Res.get().getSingleDecl();
4155 }
4156 
4157 Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
4158  llvm_unreachable(
4159  "Requires directive cannot be instantiated within a dependent context");
4160 }
4161 
4162 Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
4164  // Instantiate type and check if it is allowed.
4165  const bool RequiresInstantiation =
4166  D->getType()->isDependentType() ||
4169  QualType SubstReductionType;
4170  if (RequiresInstantiation) {
4171  SubstReductionType = SemaRef.OpenMP().ActOnOpenMPDeclareReductionType(
4172  D->getLocation(),
4173  ParsedType::make(SemaRef.SubstType(
4174  D->getType(), TemplateArgs, D->getLocation(), DeclarationName())));
4175  } else {
4176  SubstReductionType = D->getType();
4177  }
4178  if (SubstReductionType.isNull())
4179  return nullptr;
4180  Expr *Combiner = D->getCombiner();
4181  Expr *Init = D->getInitializer();
4182  bool IsCorrect = true;
4183  // Create instantiated copy.
4184  std::pair<QualType, SourceLocation> ReductionTypes[] = {
4185  std::make_pair(SubstReductionType, D->getLocation())};
4186  auto *PrevDeclInScope = D->getPrevDeclInScope();
4187  if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
4188  PrevDeclInScope = cast<OMPDeclareReductionDecl>(
4189  SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
4190  ->get<Decl *>());
4191  }
4193  /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
4194  PrevDeclInScope);
4195  auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
4196  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
4197  Expr *SubstCombiner = nullptr;
4198  Expr *SubstInitializer = nullptr;
4199  // Combiners instantiation sequence.
4200  if (Combiner) {
4202  /*S=*/nullptr, NewDRD);
4204  cast<DeclRefExpr>(D->getCombinerIn())->getDecl(),
4205  cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl());
4207  cast<DeclRefExpr>(D->getCombinerOut())->getDecl(),
4208  cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl());
4209  auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
4210  Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
4211  ThisContext);
4212  SubstCombiner = SemaRef.SubstExpr(Combiner, TemplateArgs).get();
4214  SubstCombiner);
4215  }
4216  // Initializers instantiation sequence.
4217  if (Init) {
4218  VarDecl *OmpPrivParm =
4220  /*S=*/nullptr, NewDRD);
4222  cast<DeclRefExpr>(D->getInitOrig())->getDecl(),
4223  cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl());
4225  cast<DeclRefExpr>(D->getInitPriv())->getDecl(),
4226  cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl());
4228  SubstInitializer = SemaRef.SubstExpr(Init, TemplateArgs).get();
4229  } else {
4230  auto *OldPrivParm =
4231  cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl());
4232  IsCorrect = IsCorrect && OldPrivParm->hasInit();
4233  if (IsCorrect)
4234  SemaRef.InstantiateVariableInitializer(OmpPrivParm, OldPrivParm,
4235  TemplateArgs);
4236  }
4238  NewDRD, SubstInitializer, OmpPrivParm);
4239  }
4240  IsCorrect = IsCorrect && SubstCombiner &&
4241  (!Init ||
4243  SubstInitializer) ||
4245  !SubstInitializer));
4246 
4248  /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl());
4249 
4250  return NewDRD;
4251 }
4252 
4253 Decl *
4254 TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
4255  // Instantiate type and check if it is allowed.
4256  const bool RequiresInstantiation =
4257  D->getType()->isDependentType() ||
4260  QualType SubstMapperTy;
4261  DeclarationName VN = D->getVarName();
4262  if (RequiresInstantiation) {
4263  SubstMapperTy = SemaRef.OpenMP().ActOnOpenMPDeclareMapperType(
4264  D->getLocation(),
4265  ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
4266  D->getLocation(), VN)));
4267  } else {
4268  SubstMapperTy = D->getType();
4269  }
4270  if (SubstMapperTy.isNull())
4271  return nullptr;
4272  // Create an instantiated copy of mapper.
4273  auto *PrevDeclInScope = D->getPrevDeclInScope();
4274  if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
4275  PrevDeclInScope = cast<OMPDeclareMapperDecl>(
4276  SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
4277  ->get<Decl *>());
4278  }
4279  bool IsCorrect = true;
4281  // Instantiate the mapper variable.
4282  DeclarationNameInfo DirName;
4283  SemaRef.OpenMP().StartOpenMPDSABlock(llvm::omp::OMPD_declare_mapper, DirName,
4284  /*S=*/nullptr,
4285  (*D->clauselist_begin())->getBeginLoc());
4286  ExprResult MapperVarRef =
4288  /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN);
4290  cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(),
4291  cast<DeclRefExpr>(MapperVarRef.get())->getDecl());
4292  auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
4293  Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
4294  ThisContext);
4295  // Instantiate map clauses.
4296  for (OMPClause *C : D->clauselists()) {
4297  auto *OldC = cast<OMPMapClause>(C);
4298  SmallVector<Expr *, 4> NewVars;
4299  for (Expr *OE : OldC->varlists()) {
4300  Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get();
4301  if (!NE) {
4302  IsCorrect = false;
4303  break;
4304  }
4305  NewVars.push_back(NE);
4306  }
4307  if (!IsCorrect)
4308  break;
4309  NestedNameSpecifierLoc NewQualifierLoc =
4310  SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(),
4311  TemplateArgs);
4312  CXXScopeSpec SS;
4313  SS.Adopt(NewQualifierLoc);
4314  DeclarationNameInfo NewNameInfo =
4315  SemaRef.SubstDeclarationNameInfo(OldC->getMapperIdInfo(), TemplateArgs);
4316  OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(),
4317  OldC->getEndLoc());
4318  OMPClause *NewC = SemaRef.OpenMP().ActOnOpenMPMapClause(
4319  OldC->getIteratorModifier(), OldC->getMapTypeModifiers(),
4320  OldC->getMapTypeModifiersLoc(), SS, NewNameInfo, OldC->getMapType(),
4321  OldC->isImplicitMapType(), OldC->getMapLoc(), OldC->getColonLoc(),
4322  NewVars, Locs);
4323  Clauses.push_back(NewC);
4324  }
4325  SemaRef.OpenMP().EndOpenMPDSABlock(nullptr);
4326  if (!IsCorrect)
4327  return nullptr;
4329  /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(),
4330  VN, D->getAccess(), MapperVarRef.get(), Clauses, PrevDeclInScope);
4331  Decl *NewDMD = DG.get().getSingleDecl();
4332  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD);
4333  return NewDMD;
4334 }
4335 
4336 Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
4337  OMPCapturedExprDecl * /*D*/) {
4338  llvm_unreachable("Should not be met in templates");
4339 }
4340 
4342  return VisitFunctionDecl(D, nullptr);
4343 }
4344 
4345 Decl *
4346 TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
4347  Decl *Inst = VisitFunctionDecl(D, nullptr);
4348  if (Inst && !D->getDescribedFunctionTemplate())
4349  Owner->addDecl(Inst);
4350  return Inst;
4351 }
4352 
4354  return VisitCXXMethodDecl(D, nullptr);
4355 }
4356 
4357 Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
4358  llvm_unreachable("There are only CXXRecordDecls in C++");
4359 }
4360 
4361 Decl *
4362 TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
4364  // As a MS extension, we permit class-scope explicit specialization
4365  // of member class templates.
4366  ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
4367  assert(ClassTemplate->getDeclContext()->isRecord() &&
4369  "can only instantiate an explicit specialization "
4370  "for a member class template");
4371 
4372  // Lookup the already-instantiated declaration in the instantiation
4373  // of the class template.
4374  ClassTemplateDecl *InstClassTemplate =
4375  cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl(
4376  D->getLocation(), ClassTemplate, TemplateArgs));
4377  if (!InstClassTemplate)
4378  return nullptr;
4379 
4380  // Substitute into the template arguments of the class template explicit
4381  // specialization.
4382  TemplateArgumentListInfo InstTemplateArgs;
4383  if (const ASTTemplateArgumentListInfo *TemplateArgsInfo =
4384  D->getTemplateArgsAsWritten()) {
4385  InstTemplateArgs.setLAngleLoc(TemplateArgsInfo->getLAngleLoc());
4386  InstTemplateArgs.setRAngleLoc(TemplateArgsInfo->getRAngleLoc());
4387 
4388  if (SemaRef.SubstTemplateArguments(TemplateArgsInfo->arguments(),
4389  TemplateArgs, InstTemplateArgs))
4390  return nullptr;
4391  }
4392 
4393  // Check that the template argument list is well-formed for this
4394  // class template.
4395  SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4396  if (SemaRef.CheckTemplateArgumentList(InstClassTemplate, D->getLocation(),
4397  InstTemplateArgs, false,
4398  SugaredConverted, CanonicalConverted,
4399  /*UpdateArgsWithConversions=*/true))
4400  return nullptr;
4401 
4402  // Figure out where to insert this class template explicit specialization
4403  // in the member template's set of class template explicit specializations.
4404  void *InsertPos = nullptr;
4406  InstClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
4407 
4408  // Check whether we've already seen a conflicting instantiation of this
4409  // declaration (for instance, if there was a prior implicit instantiation).
4410  bool Ignored;
4411  if (PrevDecl &&
4413  D->getSpecializationKind(),
4414  PrevDecl,
4415  PrevDecl->getSpecializationKind(),
4416  PrevDecl->getPointOfInstantiation(),
4417  Ignored))
4418  return nullptr;
4419 
4420  // If PrevDecl was a definition and D is also a definition, diagnose.
4421  // This happens in cases like:
4422  //
4423  // template<typename T, typename U>
4424  // struct Outer {
4425  // template<typename X> struct Inner;
4426  // template<> struct Inner<T> {};
4427  // template<> struct Inner<U> {};
4428  // };
4429  //
4430  // Outer<int, int> outer; // error: the explicit specializations of Inner
4431  // // have the same signature.
4432  if (PrevDecl && PrevDecl->getDefinition() &&
4434  SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
4435  SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
4436  diag::note_previous_definition);
4437  return nullptr;
4438  }
4439 
4440  // Create the class template partial specialization declaration.
4443  SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
4444  D->getLocation(), InstClassTemplate, CanonicalConverted, PrevDecl);
4445  InstD->setTemplateArgsAsWritten(InstTemplateArgs);
4446 
4447  // Add this partial specialization to the set of class template partial
4448  // specializations.
4449  if (!PrevDecl)
4450  InstClassTemplate->AddSpecialization(InstD, InsertPos);
4451 
4452  // Substitute the nested name specifier, if any.
4453  if (SubstQualifier(D, InstD))
4454  return nullptr;
4455 
4456  InstD->setAccess(D->getAccess());
4461 
4462  Owner->addDecl(InstD);
4463 
4464  // Instantiate the members of the class-scope explicit specialization eagerly.
4465  // We don't have support for lazy instantiation of an explicit specialization
4466  // yet, and MSVC eagerly instantiates in this case.
4467  // FIXME: This is wrong in standard C++.
4468  if (D->isThisDeclarationADefinition() &&
4469  SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
4471  /*Complain=*/true))
4472  return nullptr;
4473 
4474  return InstD;
4475 }
4476 
4479 
4480  TemplateArgumentListInfo VarTemplateArgsInfo;
4481  VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
4482  assert(VarTemplate &&
4483  "A template specialization without specialized template?");
4484 
4485  VarTemplateDecl *InstVarTemplate =
4486  cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl(
4487  D->getLocation(), VarTemplate, TemplateArgs));
4488  if (!InstVarTemplate)
4489  return nullptr;
4490 
4491  // Substitute the current template arguments.
4492  if (const ASTTemplateArgumentListInfo *TemplateArgsInfo =
4493  D->getTemplateArgsAsWritten()) {
4494  VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo->getLAngleLoc());
4495  VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo->getRAngleLoc());
4496 
4497  if (SemaRef.SubstTemplateArguments(TemplateArgsInfo->arguments(),
4498  TemplateArgs, VarTemplateArgsInfo))
4499  return nullptr;
4500  }
4501 
4502  // Check that the template argument list is well-formed for this template.
4503  SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4504  if (SemaRef.CheckTemplateArgumentList(InstVarTemplate, D->getLocation(),
4505  VarTemplateArgsInfo, false,
4506  SugaredConverted, CanonicalConverted,
4507  /*UpdateArgsWithConversions=*/true))
4508  return nullptr;
4509 
4510  // Check whether we've already seen a declaration of this specialization.
4511  void *InsertPos = nullptr;
4512  VarTemplateSpecializationDecl *PrevDecl =
4513  InstVarTemplate->findSpecialization(CanonicalConverted, InsertPos);
4514 
4515  // Check whether we've already seen a conflicting instantiation of this
4516  // declaration (for instance, if there was a prior implicit instantiation).
4517  bool Ignored;
4518  if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl(
4519  D->getLocation(), D->getSpecializationKind(), PrevDecl,
4520  PrevDecl->getSpecializationKind(),
4521  PrevDecl->getPointOfInstantiation(), Ignored))
4522  return nullptr;
4523 
4525  InstVarTemplate, D, VarTemplateArgsInfo, CanonicalConverted, PrevDecl);
4526 }
4527 
4529  VarTemplateDecl *VarTemplate, VarDecl *D,
4530  const TemplateArgumentListInfo &TemplateArgsInfo,
4531  ArrayRef<TemplateArgument> Converted,
4532  VarTemplateSpecializationDecl *PrevDecl) {
4533 
4534  // Do substitution on the type of the declaration
4535  TypeSourceInfo *DI =
4536  SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
4537  D->getTypeSpecStartLoc(), D->getDeclName());
4538  if (!DI)
4539  return nullptr;
4540 
4541  if (DI->getType()->isFunctionType()) {
4542  SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
4543  << D->isStaticDataMember() << DI->getType();
4544  return nullptr;
4545  }
4546 
4547  // Build the instantiated declaration
4549  SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
4550  VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
4551  Var->setTemplateArgsAsWritten(TemplateArgsInfo);
4552  if (!PrevDecl) {
4553  void *InsertPos = nullptr;
4554  VarTemplate->findSpecialization(Converted, InsertPos);
4555  VarTemplate->AddSpecialization(Var, InsertPos);
4556  }
4557 
4558  if (SemaRef.getLangOpts().OpenCL)
4559  SemaRef.deduceOpenCLAddressSpace(Var);
4560 
4561  // Substitute the nested name specifier, if any.
4562  if (SubstQualifier(D, Var))
4563  return nullptr;
4564 
4565  SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
4566  StartingScope, false, PrevDecl);
4567 
4568  return Var;
4569 }
4570 
4571 Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
4572  llvm_unreachable("@defs is not supported in Objective-C++");
4573 }
4574 
4575 Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
4576  // FIXME: We need to be able to instantiate FriendTemplateDecls.
4577  unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
4579  "cannot instantiate %0 yet");
4580  SemaRef.Diag(D->getLocation(), DiagID)
4581  << D->getDeclKindName();
4582 
4583  return nullptr;
4584 }
4585 
4586 Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) {
4587  llvm_unreachable("Concept definitions cannot reside inside a template");
4588 }
4589 
4590 Decl *TemplateDeclInstantiator::VisitImplicitConceptSpecializationDecl(
4592  llvm_unreachable("Concept specializations cannot reside inside a template");
4593 }
4594 
4595 Decl *
4596 TemplateDeclInstantiator::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
4598  D->getBeginLoc());
4599 }
4600 
4602  llvm_unreachable("Unexpected decl");
4603 }
4604 
4606  const MultiLevelTemplateArgumentList &TemplateArgs) {
4607  TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
4608  if (D->isInvalidDecl())
4609  return nullptr;
4610 
4611  Decl *SubstD;
4613  SubstD = Instantiator.Visit(D);
4614  });
4615  return SubstD;
4616 }
4617 
4619  FunctionDecl *Orig, QualType &T,
4620  TypeSourceInfo *&TInfo,
4621  DeclarationNameInfo &NameInfo) {
4623 
4624  // C++2a [class.compare.default]p3:
4625  // the return type is replaced with bool
4626  auto *FPT = T->castAs<FunctionProtoType>();
4627  T = SemaRef.Context.getFunctionType(
4628  SemaRef.Context.BoolTy, FPT->getParamTypes(), FPT->getExtProtoInfo());
4629 
4630  // Update the return type in the source info too. The most straightforward
4631  // way is to create new TypeSourceInfo for the new type. Use the location of
4632  // the '= default' as the location of the new type.
4633  //
4634  // FIXME: Set the correct return type when we initially transform the type,
4635  // rather than delaying it to now.
4636  TypeSourceInfo *NewTInfo =
4637  SemaRef.Context.getTrivialTypeSourceInfo(T, Orig->getEndLoc());
4638  auto OldLoc = TInfo->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>();
4639  assert(OldLoc && "type of function is not a function type?");
4640  auto NewLoc = NewTInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>();
4641  for (unsigned I = 0, N = OldLoc.getNumParams(); I != N; ++I)
4642  NewLoc.setParam(I, OldLoc.getParam(I));
4643  TInfo = NewTInfo;
4644 
4645  // and the declarator-id is replaced with operator==
4646  NameInfo.setName(
4647  SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_EqualEqual));
4648 }
4649 
4652  if (Spaceship->isInvalidDecl())
4653  return nullptr;
4654 
4655  // C++2a [class.compare.default]p3:
4656  // an == operator function is declared implicitly [...] with the same
4657  // access and function-definition and in the same class scope as the
4658  // three-way comparison operator function
4659  MultiLevelTemplateArgumentList NoTemplateArgs;
4661  NoTemplateArgs.addOuterRetainedLevels(RD->getTemplateDepth());
4662  TemplateDeclInstantiator Instantiator(*this, RD, NoTemplateArgs);
4663  Decl *R;
4664  if (auto *MD = dyn_cast<CXXMethodDecl>(Spaceship)) {
4665  R = Instantiator.VisitCXXMethodDecl(
4666  MD, /*TemplateParams=*/nullptr,
4668  } else {
4669  assert(Spaceship->getFriendObjectKind() &&
4670  "defaulted spaceship is neither a member nor a friend");
4671 
4672  R = Instantiator.VisitFunctionDecl(
4673  Spaceship, /*TemplateParams=*/nullptr,
4675  if (!R)
4676  return nullptr;
4677 
4678  FriendDecl *FD =
4679  FriendDecl::Create(Context, RD, Spaceship->getLocation(),
4680  cast<NamedDecl>(R), Spaceship->getBeginLoc());
4681  FD->setAccess(AS_public);
4682  RD->addDecl(FD);
4683  }
4684  return cast_or_null<FunctionDecl>(R);
4685 }
4686 
4687 /// Instantiates a nested template parameter list in the current
4688 /// instantiation context.
4689 ///
4690 /// \param L The parameter list to instantiate
4691 ///
4692 /// \returns NULL if there was an error
4695  // Get errors for all the parameters before bailing out.
4696  bool Invalid = false;
4697 
4698  unsigned N = L->size();
4699  typedef SmallVector<NamedDecl *, 8> ParamVector;
4700  ParamVector Params;
4701  Params.reserve(N);
4702  for (auto &P : *L) {
4703  NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
4704  Params.push_back(D);
4705  Invalid = Invalid || !D || D->isInvalidDecl();
4706  }
4707 
4708  // Clean up if we had an error.
4709  if (Invalid)
4710  return nullptr;
4711 
4712  Expr *InstRequiresClause = L->getRequiresClause();
4713 
4714  TemplateParameterList *InstL
4716  L->getLAngleLoc(), Params,
4717  L->getRAngleLoc(), InstRequiresClause);
4718  return InstL;
4719 }
4720 
4723  const MultiLevelTemplateArgumentList &TemplateArgs,
4724  bool EvaluateConstraints) {
4725  TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
4726  Instantiator.setEvaluateConstraints(EvaluateConstraints);
4727  return Instantiator.SubstTemplateParams(Params);
4728 }
4729 
4730 /// Instantiate the declaration of a class template partial
4731 /// specialization.
4732 ///
4733 /// \param ClassTemplate the (instantiated) class template that is partially
4734 // specialized by the instantiation of \p PartialSpec.
4735 ///
4736 /// \param PartialSpec the (uninstantiated) class template partial
4737 /// specialization that we are instantiating.
4738 ///
4739 /// \returns The instantiated partial specialization, if successful; otherwise,
4740 /// NULL to indicate an error.
4743  ClassTemplateDecl *ClassTemplate,
4745  // Create a local instantiation scope for this class template partial
4746  // specialization, which will contain the instantiations of the template
4747  // parameters.
4748  LocalInstantiationScope Scope(SemaRef);
4749 
4750  // Substitute into the template parameters of the class template partial
4751  // specialization.
4752  TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4753  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4754  if (!InstParams)
4755  return nullptr;
4756 
4757  // Substitute into the template arguments of the class template partial
4758  // specialization.
4759  const ASTTemplateArgumentListInfo *TemplArgInfo
4760  = PartialSpec->getTemplateArgsAsWritten();
4761  TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4762  TemplArgInfo->RAngleLoc);
4763  if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4764  InstTemplateArgs))
4765  return nullptr;
4766 
4767  // Check that the template argument list is well-formed for this
4768  // class template.
4769  SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4770  if (SemaRef.CheckTemplateArgumentList(
4771  ClassTemplate, PartialSpec->getLocation(), InstTemplateArgs,
4772  /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted))
4773  return nullptr;
4774 
4775  // Check these arguments are valid for a template partial specialization.
4777  PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
4778  CanonicalConverted))
4779  return nullptr;
4780 
4781  // Figure out where to insert this class template partial specialization
4782  // in the member template's set of class template partial specializations.
4783  void *InsertPos = nullptr;
4785  ClassTemplate->findPartialSpecialization(CanonicalConverted, InstParams,
4786  InsertPos);
4787 
4788  // Build the canonical type that describes the converted template
4789  // arguments of the class template partial specialization.
4790  QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
4791  TemplateName(ClassTemplate), CanonicalConverted);
4792 
4793  // Create the class template partial specialization declaration.
4794  ClassTemplatePartialSpecializationDecl *InstPartialSpec =
4796  SemaRef.Context, PartialSpec->getTagKind(), Owner,
4797  PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
4798  ClassTemplate, CanonicalConverted, CanonType,
4799  /*PrevDecl=*/nullptr);
4800 
4801  InstPartialSpec->setTemplateArgsAsWritten(InstTemplateArgs);
4802 
4803  // Substitute the nested name specifier, if any.
4804  if (SubstQualifier(PartialSpec, InstPartialSpec))
4805  return nullptr;
4806 
4807  InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4808 
4809  if (PrevDecl) {
4810  // We've already seen a partial specialization with the same template
4811  // parameters and template arguments. This can happen, for example, when
4812  // substituting the outer template arguments ends up causing two
4813  // class template partial specializations of a member class template
4814  // to have identical forms, e.g.,
4815  //
4816  // template<typename T, typename U>
4817  // struct Outer {
4818  // template<typename X, typename Y> struct Inner;
4819  // template<typename Y> struct Inner<T, Y>;
4820  // template<typename Y> struct Inner<U, Y>;
4821  // };
4822  //
4823  // Outer<int, int> outer; // error: the partial specializations of Inner
4824  // // have the same signature.
4825  SemaRef.Diag(InstPartialSpec->getLocation(),
4826  diag::err_partial_spec_redeclared)
4827  << InstPartialSpec;
4828  SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
4829  << SemaRef.Context.getTypeDeclType(PrevDecl);
4830  return nullptr;
4831  }
4832 
4833  // Check the completed partial specialization.
4834  SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4835 
4836  // Add this partial specialization to the set of class template partial
4837  // specializations.
4838  ClassTemplate->AddPartialSpecialization(InstPartialSpec,
4839  /*InsertPos=*/nullptr);
4840  return InstPartialSpec;
4841 }
4842 
4843 /// Instantiate the declaration of a variable template partial
4844 /// specialization.
4845 ///
4846 /// \param VarTemplate the (instantiated) variable template that is partially
4847 /// specialized by the instantiation of \p PartialSpec.
4848 ///
4849 /// \param PartialSpec the (uninstantiated) variable template partial
4850 /// specialization that we are instantiating.
4851 ///
4852 /// \returns The instantiated partial specialization, if successful; otherwise,
4853 /// NULL to indicate an error.
4856  VarTemplateDecl *VarTemplate,
4857  VarTemplatePartialSpecializationDecl *PartialSpec) {
4858  // Create a local instantiation scope for this variable template partial
4859  // specialization, which will contain the instantiations of the template
4860  // parameters.
4861  LocalInstantiationScope Scope(SemaRef);
4862 
4863  // Substitute into the template parameters of the variable template partial
4864  // specialization.
4865  TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4866  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4867  if (!InstParams)
4868  return nullptr;
4869 
4870  // Substitute into the template arguments of the variable template partial
4871  // specialization.
4872  const ASTTemplateArgumentListInfo *TemplArgInfo
4873  = PartialSpec->getTemplateArgsAsWritten();
4874  TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4875  TemplArgInfo->RAngleLoc);
4876  if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4877  InstTemplateArgs))
4878  return nullptr;
4879 
4880  // Check that the template argument list is well-formed for this
4881  // class template.
4882  SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4883  if (SemaRef.CheckTemplateArgumentList(
4884  VarTemplate, PartialSpec->getLocation(), InstTemplateArgs,
4885  /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted))
4886  return nullptr;
4887 
4888  // Check these arguments are valid for a template partial specialization.
4890  PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
4891  CanonicalConverted))
4892  return nullptr;
4893 
4894  // Figure out where to insert this variable template partial specialization
4895  // in the member template's set of variable template partial specializations.
4896  void *InsertPos = nullptr;
4897  VarTemplateSpecializationDecl *PrevDecl =
4898  VarTemplate->findPartialSpecialization(CanonicalConverted, InstParams,
4899  InsertPos);
4900 
4901  // Do substitution on the type of the declaration
4902  TypeSourceInfo *DI = SemaRef.SubstType(
4903  PartialSpec->getTypeSourceInfo(), TemplateArgs,
4904  PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
4905  if (!DI)
4906  return nullptr;
4907 
4908  if (DI->getType()->isFunctionType()) {
4909  SemaRef.Diag(PartialSpec->getLocation(),
4910  diag::err_variable_instantiates_to_function)
4911  << PartialSpec->isStaticDataMember() << DI->getType();
4912  return nullptr;
4913  }
4914 
4915  // Create the variable template partial specialization declaration.
4916  VarTemplatePartialSpecializationDecl *InstPartialSpec =
4918  SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
4919  PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
4920  DI, PartialSpec->getStorageClass(), CanonicalConverted);
4921 
4922  InstPartialSpec->setTemplateArgsAsWritten(InstTemplateArgs);
4923 
4924  // Substitute the nested name specifier, if any.
4925  if (SubstQualifier(PartialSpec, InstPartialSpec))
4926  return nullptr;
4927 
4928  InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4929 
4930  if (PrevDecl) {
4931  // We've already seen a partial specialization with the same template
4932  // parameters and template arguments. This can happen, for example, when
4933  // substituting the outer template arguments ends up causing two
4934  // variable template partial specializations of a member variable template
4935  // to have identical forms, e.g.,
4936  //
4937  // template<typename T, typename U>
4938  // struct Outer {
4939  // template<typename X, typename Y> pair<X,Y> p;
4940  // template<typename Y> pair<T, Y> p;
4941  // template<typename Y> pair<U, Y> p;
4942  // };
4943  //
4944  // Outer<int, int> outer; // error: the partial specializations of Inner
4945  // // have the same signature.
4946  SemaRef.Diag(PartialSpec->getLocation(),
4947  diag::err_var_partial_spec_redeclared)
4948  << InstPartialSpec;
4949  SemaRef.Diag(PrevDecl->getLocation(),
4950  diag::note_var_prev_partial_spec_here);
4951  return nullptr;
4952  }
4953  // Check the completed partial specialization.
4954  SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4955 
4956  // Add this partial specialization to the set of variable template partial
4957  // specializations. The instantiation of the initializer is not necessary.
4958  VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
4959 
4960  SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
4961  LateAttrs, Owner, StartingScope);
4962 
4963  return InstPartialSpec;
4964 }
4965 
4969  TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
4970  assert(OldTInfo && "substituting function without type source info");
4971  assert(Params.empty() && "parameter vector is non-empty at start");
4972 
4973  CXXRecordDecl *ThisContext = nullptr;
4974  Qualifiers ThisTypeQuals;
4975  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4976  ThisContext = cast<CXXRecordDecl>(Owner);
4977  ThisTypeQuals = Method->getFunctionObjectParameterType().getQualifiers();
4978  }
4979 
4980  TypeSourceInfo *NewTInfo = SemaRef.SubstFunctionDeclType(
4981  OldTInfo, TemplateArgs, D->getTypeSpecStartLoc(), D->getDeclName(),
4982  ThisContext, ThisTypeQuals, EvaluateConstraints);
4983  if (!NewTInfo)
4984  return nullptr;
4985 
4986  TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
4987  if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
4988  if (NewTInfo != OldTInfo) {
4989  // Get parameters from the new type info.
4990  TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
4991  FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
4992  unsigned NewIdx = 0;
4993  for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
4994  OldIdx != NumOldParams; ++OldIdx) {
4995  ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
4996  if (!OldParam)
4997  return nullptr;
4998 
5000 
5001  std::optional<unsigned> NumArgumentsInExpansion;
5002  if (OldParam->isParameterPack())
5003  NumArgumentsInExpansion =
5004  SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
5005  TemplateArgs);
5006  if (!NumArgumentsInExpansion) {
5007  // Simple case: normal parameter, or a parameter pack that's
5008  // instantiated to a (still-dependent) parameter pack.
5009  ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
5010  Params.push_back(NewParam);
5011  Scope->InstantiatedLocal(OldParam, NewParam);
5012  } else {
5013  // Parameter pack expansion: make the instantiation an argument pack.
5014  Scope->MakeInstantiatedLocalArgPack(OldParam);
5015  for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
5016  ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
5017  Params.push_back(NewParam);
5018  Scope->InstantiatedLocalPackArg(OldParam, NewParam);
5019  }
5020  }
5021  }
5022  } else {
5023  // The function type itself was not dependent and therefore no
5024  // substitution occurred. However, we still need to instantiate
5025  // the function parameters themselves.
5026  const FunctionProtoType *OldProto =
5027  cast<FunctionProtoType>(OldProtoLoc.getType());
5028  for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
5029  ++i) {
5030  ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
5031  if (!OldParam) {
5032  Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
5033  D, D->getLocation(), OldProto->getParamType(i)));
5034  continue;
5035  }
5036 
5037  ParmVarDecl *Parm =
5038  cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
5039  if (!Parm)
5040  return nullptr;
5041  Params.push_back(Parm);
5042  }
5043  }
5044  } else {
5045  // If the type of this function, after ignoring parentheses, is not
5046  // *directly* a function type, then we're instantiating a function that
5047  // was declared via a typedef or with attributes, e.g.,
5048  //
5049  // typedef int functype(int, int);
5050  // functype func;
5051  // int __cdecl meth(int, int);
5052  //
5053  // In this case, we'll just go instantiate the ParmVarDecls that we
5054  // synthesized in the method declaration.
5055  SmallVector<QualType, 4> ParamTypes;
5056  Sema::ExtParameterInfoBuilder ExtParamInfos;
5057  if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
5058  TemplateArgs, ParamTypes, &Params,
5059  ExtParamInfos))
5060  return nullptr;
5061  }
5062 
5063  return NewTInfo;
5064 }
5065 
5066 /// Introduce the instantiated local variables into the local
5067 /// instantiation scope.
5068 void Sema::addInstantiatedLocalVarsToScope(FunctionDecl *Function,
5069  const FunctionDecl *PatternDecl,
5071  LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(getFunctionScopes().back());
5072 
5073  for (auto *decl : PatternDecl->decls()) {
5074  if (!isa<VarDecl>(decl) || isa<ParmVarDecl>(decl))
5075  continue;
5076 
5077  VarDecl *VD = cast<VarDecl>(decl);
5078  IdentifierInfo *II = VD->getIdentifier();
5079 
5080  auto it = llvm::find_if(Function->decls(), [&](Decl *inst) {
5081  VarDecl *InstVD = dyn_cast<VarDecl>(inst);
5082  return InstVD && InstVD->isLocalVarDecl() &&
5083  InstVD->getIdentifier() == II;
5084  });
5085 
5086  if (it == Function->decls().end())
5087  continue;
5088 
5089  Scope.InstantiatedLocal(VD, *it);
5090  LSI->addCapture(cast<VarDecl>(*it), /*isBlock=*/false, /*isByref=*/false,
5091  /*isNested=*/false, VD->getLocation(), SourceLocation(),
5092  VD->getType(), /*Invalid=*/false);
5093  }
5094 }
5095 
5096 /// Introduce the instantiated function parameters into the local
5097 /// instantiation scope, and set the parameter names to those used
5098 /// in the template.
5099 bool Sema::addInstantiatedParametersToScope(
5100  FunctionDecl *Function, const FunctionDecl *PatternDecl,
5102  const MultiLevelTemplateArgumentList &TemplateArgs) {
5103  unsigned FParamIdx = 0;
5104  for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
5105  const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
5106  if (!PatternParam->isParameterPack()) {
5107  // Simple case: not a parameter pack.
5108  assert(FParamIdx < Function->getNumParams());
5109  ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
5110  FunctionParam->setDeclName(PatternParam->getDeclName());
5111  // If the parameter's type is not dependent, update it to match the type
5112  // in the pattern. They can differ in top-level cv-qualifiers, and we want
5113  // the pattern's type here. If the type is dependent, they can't differ,
5114  // per core issue 1668. Substitute into the type from the pattern, in case
5115  // it's instantiation-dependent.
5116  // FIXME: Updating the type to work around this is at best fragile.
5117  if (!PatternDecl->getType()->isDependentType()) {
5118  QualType T = SubstType(PatternParam->getType(), TemplateArgs,
5119  FunctionParam->getLocation(),
5120  FunctionParam->getDeclName());
5121  if (T.isNull())
5122  return true;
5123  FunctionParam->setType(T);
5124  }
5125 
5126  Scope.InstantiatedLocal(PatternParam, FunctionParam);
5127  ++FParamIdx;
5128  continue;
5129  }
5130 
5131  // Expand the parameter pack.
5132  Scope.MakeInstantiatedLocalArgPack(PatternParam);
5133  std::optional<unsigned> NumArgumentsInExpansion =
5134  getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
5135  if (NumArgumentsInExpansion) {
5136  QualType PatternType =
5137  PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
5138  for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
5139  ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
5140  FunctionParam->setDeclName(PatternParam->getDeclName());
5141  if (!PatternDecl->getType()->isDependentType()) {
5142  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, Arg);
5143  QualType T =
5144  SubstType(PatternType, TemplateArgs, FunctionParam->getLocation(),
5145  FunctionParam->getDeclName());
5146  if (T.isNull())
5147  return true;
5148  FunctionParam->setType(T);
5149  }
5150 
5151  Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
5152  ++FParamIdx;
5153  }
5154  }
5155  }
5156 
5157  return false;
5158 }
5159 
5161  ParmVarDecl *Param) {
5162  assert(Param->hasUninstantiatedDefaultArg());
5163 
5164  // Instantiate the expression.
5165  //
5166  // FIXME: Pass in a correct Pattern argument, otherwise
5167  // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
5168  //
5169  // template<typename T>
5170  // struct A {
5171  // static int FooImpl();
5172  //
5173  // template<typename Tp>
5174  // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
5175  // // template argument list [[T], [Tp]], should be [[Tp]].
5176  // friend A<Tp> Foo(int a);
5177  // };
5178  //
5179  // template<typename T>
5180  // A<T> Foo(int a = A<T>::FooImpl());
5181  MultiLevelTemplateArgumentList TemplateArgs =
5183  /*Final=*/false, /*Innermost=*/std::nullopt,
5184  /*RelativeToPrimary=*/true);
5185 
5186  if (SubstDefaultArgument(CallLoc, Param, TemplateArgs, /*ForCallExpr*/ true))
5187  return true;
5188 
5190  L->DefaultArgumentInstantiated(Param);
5191 
5192  return false;
5193 }
5194 
5196  FunctionDecl *Decl) {
5197  const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
5198  if (Proto->getExceptionSpecType() != EST_Uninstantiated)
5199  return;
5200 
5201  InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
5203  if (Inst.isInvalid()) {
5204  // We hit the instantiation depth limit. Clear the exception specification
5205  // so that our callers don't have to cope with EST_Uninstantiated.
5207  return;
5208  }
5209  if (Inst.isAlreadyInstantiating()) {
5210  // This exception specification indirectly depends on itself. Reject.
5211  // FIXME: Corresponding rule in the standard?
5212  Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
5214  return;
5215  }
5216 
5217  // Enter the scope of this instantiation. We don't use
5218  // PushDeclContext because we don't have a scope.
5219  Sema::ContextRAII savedContext(*this, Decl);
5221 
5222  MultiLevelTemplateArgumentList TemplateArgs =
5224  /*Final=*/false, /*Innermost=*/std::nullopt,
5225  /*RelativeToPrimary*/ true);
5226 
5227  // FIXME: We can't use getTemplateInstantiationPattern(false) in general
5228  // here, because for a non-defining friend declaration in a class template,
5229  // we don't store enough information to map back to the friend declaration in
5230  // the template.
5231  FunctionDecl *Template = Proto->getExceptionSpecTemplate();
5232  if (addInstantiatedParametersToScope(Decl, Template, Scope, TemplateArgs)) {
5234  return;
5235  }
5236 
5238  TemplateArgs);
5239 }
5240 
5241 /// Initializes the common fields of an instantiation function
5242 /// declaration (New) from the corresponding fields of its template (Tmpl).
5243 ///
5244 /// \returns true if there was an error
5245 bool
5247  FunctionDecl *Tmpl) {
5248  New->setImplicit(Tmpl->isImplicit());
5249 
5250  // Forward the mangling number from the template to the instantiated decl.
5251  SemaRef.Context.setManglingNumber(New,
5252  SemaRef.Context.getManglingNumber(Tmpl));
5253 
5254  // If we are performing substituting explicitly-specified template arguments
5255  // or deduced template arguments into a function template and we reach this
5256  // point, we are now past the point where SFINAE applies and have committed
5257  // to keeping the new function template specialization. We therefore
5258  // convert the active template instantiation for the function template
5259  // into a template instantiation for this specific function template
5260  // specialization, which is not a SFINAE context, so that we diagnose any
5261  // further errors in the declaration itself.
5262  //
5263  // FIXME: This is a hack.
5264  typedef Sema::CodeSynthesisContext ActiveInstType;
5265  ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
5266  if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
5267  ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
5268  if (isa<FunctionTemplateDecl>(ActiveInst.Entity)) {
5269  SemaRef.InstantiatingSpecializations.erase(
5270  {ActiveInst.Entity->getCanonicalDecl(), ActiveInst.Kind});
5271  atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
5272  ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
5273  ActiveInst.Entity = New;
5274  atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
5275  }
5276  }
5277 
5278  const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
5279  assert(Proto && "Function template without prototype?");
5280 
5281  if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
5283 
5284  // DR1330: In C++11, defer instantiation of a non-trivial
5285  // exception specification.
5286  // DR1484: Local classes and their members are instantiated along with the
5287  // containing function.
5288  if (SemaRef.getLangOpts().CPlusPlus11 &&
5289  EPI.ExceptionSpec.Type != EST_None &&
5292  !Tmpl->isInLocalScopeForInstantiation()) {
5293  FunctionDecl *ExceptionSpecTemplate = Tmpl;
5295  ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
5297  if (EPI.ExceptionSpec.Type == EST_Unevaluated)
5298  NewEST = EST_Unevaluated;
5299 
5300  // Mark the function has having an uninstantiated exception specification.
5301  const FunctionProtoType *NewProto
5302  = New->getType()->getAs<FunctionProtoType>();
5303  assert(NewProto && "Template instantiation without function prototype?");
5304  EPI = NewProto->getExtProtoInfo();
5305  EPI.ExceptionSpec.Type = NewEST;
5306  EPI.ExceptionSpec.SourceDecl = New;
5307  EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
5308  New->setType(SemaRef.Context.getFunctionType(
5309  NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
5310  } else {
5311  Sema::ContextRAII SwitchContext(SemaRef, New);
5312  SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
5313  }
5314  }
5315 
5316  // Get the definition. Leaves the variable unchanged if undefined.
5317  const FunctionDecl *Definition = Tmpl;
5318  Tmpl->isDefined(Definition);
5319 
5320  SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
5321  LateAttrs, StartingScope);
5322 
5323  return false;
5324 }
5325 
5326 /// Initializes common fields of an instantiated method
5327 /// declaration (New) from the corresponding fields of its template
5328 /// (Tmpl).
5329 ///
5330 /// \returns true if there was an error
5331 bool
5333  CXXMethodDecl *Tmpl) {
5334  if (InitFunctionInstantiation(New, Tmpl))
5335  return true;
5336 
5337  if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11)
5338  SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New));
5339 
5340  New->setAccess(Tmpl->getAccess());
5341  if (Tmpl->isVirtualAsWritten())
5342  New->setVirtualAsWritten(true);
5343 
5344  // FIXME: New needs a pointer to Tmpl
5345  return false;
5346 }
5347 
5349  FunctionDecl *Tmpl) {
5350  // Transfer across any unqualified lookups.
5351  if (auto *DFI = Tmpl->getDefalutedOrDeletedInfo()) {
5353  Lookups.reserve(DFI->getUnqualifiedLookups().size());
5354  bool AnyChanged = false;
5355  for (DeclAccessPair DA : DFI->getUnqualifiedLookups()) {
5356  NamedDecl *D = SemaRef.FindInstantiatedDecl(New->getLocation(),
5357  DA.getDecl(), TemplateArgs);
5358  if (!D)
5359  return true;
5360  AnyChanged |= (D != DA.getDecl());
5361  Lookups.push_back(DeclAccessPair::make(D, DA.getAccess()));
5362  }
5363 
5364  // It's unlikely that substitution will change any declarations. Don't
5365  // store an unnecessary copy in that case.
5368  SemaRef.Context, Lookups)
5369  : DFI);
5370  }
5371 
5372  SemaRef.SetDeclDefaulted(New, Tmpl->getLocation());
5373  return false;
5374 }
5375 
5376 /// Instantiate (or find existing instantiation of) a function template with a
5377 /// given set of template arguments.
5378 ///
5379 /// Usually this should not be used, and template argument deduction should be
5380 /// used in its place.
5382  FunctionTemplateDecl *FTD, const TemplateArgumentList *Args,
5384  FunctionDecl *FD = FTD->getTemplatedDecl();
5385 
5387  InstantiatingTemplate Inst(*this, Loc, FTD, Args->asArray(), CSC, Info);
5388  if (Inst.isInvalid())
5389  return nullptr;
5390 
5391  ContextRAII SavedContext(*this, FD);
5392  MultiLevelTemplateArgumentList MArgs(FTD, Args->asArray(),
5393  /*Final=*/false);
5394 
5395  return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs));
5396 }
5397 
5398 /// Instantiate the definition of the given function from its
5399 /// template.
5400 ///
5401 /// \param PointOfInstantiation the point at which the instantiation was
5402 /// required. Note that this is not precisely a "point of instantiation"
5403 /// for the function, but it's close.
5404 ///
5405 /// \param Function the already-instantiated declaration of a
5406 /// function template specialization or member function of a class template
5407 /// specialization.
5408 ///
5409 /// \param Recursive if true, recursively instantiates any functions that
5410 /// are required by this instantiation.
5411 ///
5412 /// \param DefinitionRequired if true, then we are performing an explicit
5413 /// instantiation where the body of the function is required. Complain if
5414 /// there is no such body.
5416  FunctionDecl *Function,
5417  bool Recursive,
5418  bool DefinitionRequired,
5419  bool AtEndOfTU) {
5420  if (Function->isInvalidDecl() || isa<CXXDeductionGuideDecl>(Function))
5421  return;
5422 
5423  // Never instantiate an explicit specialization except if it is a class scope
5424  // explicit specialization.
5426  Function->getTemplateSpecializationKindForInstantiation();
5427  if (TSK == TSK_ExplicitSpecialization)
5428  return;
5429 
5430  // Never implicitly instantiate a builtin; we don't actually need a function
5431  // body.
5432  if (Function->getBuiltinID() && TSK == TSK_ImplicitInstantiation &&
5433  !DefinitionRequired)
5434  return;
5435 
5436  // Don't instantiate a definition if we already have one.
5437  const FunctionDecl *ExistingDefn = nullptr;
5438  if (Function->isDefined(ExistingDefn,
5439  /*CheckForPendingFriendDefinition=*/true)) {
5440  if (ExistingDefn->isThisDeclarationADefinition())
5441  return;
5442 
5443  // If we're asked to instantiate a function whose body comes from an
5444  // instantiated friend declaration, attach the instantiated body to the
5445  // corresponding declaration of the function.
5447  Function = const_cast<FunctionDecl*>(ExistingDefn);
5448  }
5449 
5450  // Find the function body that we'll be substituting.
5451  const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
5452  assert(PatternDecl && "instantiating a non-template");
5453 
5454  const FunctionDecl *PatternDef = PatternDecl->getDefinition();
5455  Stmt *Pattern = nullptr;
5456  if (PatternDef) {
5457  Pattern = PatternDef->getBody(PatternDef);
5458  PatternDecl = PatternDef;
5459  if (PatternDef->willHaveBody())
5460  PatternDef = nullptr;
5461  }
5462 
5463  // FIXME: We need to track the instantiation stack in order to know which
5464  // definitions should be visible within this instantiation.
5465  if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function,
5466  Function->getInstantiatedFromMemberFunction(),
5467  PatternDecl, PatternDef, TSK,
5468  /*Complain*/DefinitionRequired)) {
5469  if (DefinitionRequired)
5470  Function->setInvalidDecl();
5471  else if (TSK == TSK_ExplicitInstantiationDefinition ||
5472  (Function->isConstexpr() && !Recursive)) {
5473  // Try again at the end of the translation unit (at which point a
5474  // definition will be required).
5475  assert(!Recursive);
5476  Function->setInstantiationIsPending(true);
5477  PendingInstantiations.push_back(
5478  std::make_pair(Function, PointOfInstantiation));
5479  } else if (TSK == TSK_ImplicitInstantiation) {
5480  if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
5481  !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
5482  Diag(PointOfInstantiation, diag::warn_func_template_missing)
5483  << Function;
5484  Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
5485  if (getLangOpts().CPlusPlus11)
5486  Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
5487  << Function;
5488  }
5489  }
5490 
5491  return;
5492  }
5493 
5494  // Postpone late parsed template instantiations.
5495  if (PatternDecl->isLateTemplateParsed() &&
5496  !LateTemplateParser) {
5497  Function->setInstantiationIsPending(true);
5498  LateParsedInstantiations.push_back(
5499  std::make_pair(Function, PointOfInstantiation));
5500  return;
5501  }
5502 
5503  llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() {
5504  std::string Name;
5505  llvm::raw_string_ostream OS(Name);
5506  Function->getNameForDiagnostic(OS, getPrintingPolicy(),
5507  /*Qualified=*/true);
5508  return Name;
5509  });
5510 
5511  // If we're performing recursive template instantiation, create our own
5512  // queue of pending implicit instantiations that we will instantiate later,
5513  // while we're still within our own instantiation context.
5514  // This has to happen before LateTemplateParser below is called, so that
5515  // it marks vtables used in late parsed templates as used.
5516  GlobalEagerInstantiationScope GlobalInstantiations(*this,
5517  /*Enabled=*/Recursive);
5518  LocalEagerInstantiationScope LocalInstantiations(*this);
5519 
5520  // Call the LateTemplateParser callback if there is a need to late parse
5521  // a templated function definition.
5522  if (!Pattern && PatternDecl->isLateTemplateParsed() &&
5524  // FIXME: Optimize to allow individual templates to be deserialized.
5525  if (PatternDecl->isFromASTFile())
5526  ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
5527 
5528  auto LPTIter = LateParsedTemplateMap.find(PatternDecl);
5529  assert(LPTIter != LateParsedTemplateMap.end() &&
5530  "missing LateParsedTemplate");
5531  LateTemplateParser(OpaqueParser, *LPTIter->second);
5532  Pattern = PatternDecl->getBody(PatternDecl);
5534  }
5535 
5536  // Note, we should never try to instantiate a deleted function template.
5537  assert((Pattern || PatternDecl->isDefaulted() ||
5538  PatternDecl->hasSkippedBody()) &&
5539  "unexpected kind of function template definition");
5540 
5541  // C++1y [temp.explicit]p10:
5542  // Except for inline functions, declarations with types deduced from their
5543  // initializer or return value, and class template specializations, other
5544  // explicit instantiation declarations have the effect of suppressing the
5545  // implicit instantiation of the entity to which they refer.
5547  !PatternDecl->isInlined() &&
5548  !PatternDecl->getReturnType()->getContainedAutoType())
5549  return;
5550 
5551  if (PatternDecl->isInlined()) {
5552  // Function, and all later redeclarations of it (from imported modules,
5553  // for instance), are now implicitly inline.
5554  for (auto *D = Function->getMostRecentDecl(); /**/;
5555  D = D->getPreviousDecl()) {
5556  D->setImplicitlyInline();
5557  if (D == Function)
5558  break;
5559  }
5560  }
5561 
5562  InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
5563  if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
5564  return;
5566  "instantiating function definition");
5567 
5568  // The instantiation is visible here, even if it was first declared in an
5569  // unimported module.
5570  Function->setVisibleDespiteOwningModule();
5571 
5572  // Copy the source locations from the pattern.
5573  Function->setLocation(PatternDecl->getLocation());
5574  Function->setInnerLocStart(PatternDecl->getInnerLocStart());
5575  Function->setRangeEnd(PatternDecl->getEndLoc());
5576  Function->setDeclarationNameLoc(PatternDecl->getNameInfo().getInfo());
5577 
5580 
5581  Qualifiers ThisTypeQuals;
5582  CXXRecordDecl *ThisContext = nullptr;
5583  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5584  ThisContext = Method->getParent();
5585  ThisTypeQuals = Method->getMethodQualifiers();
5586  }
5587  CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals);
5588 
5589  // Introduce a new scope where local variable instantiations will be
5590  // recorded, unless we're actually a member function within a local
5591  // class, in which case we need to merge our results with the parent
5592  // scope (of the enclosing function). The exception is instantiating
5593  // a function template specialization, since the template to be
5594  // instantiated already has references to locals properly substituted.
5595  bool MergeWithParentScope = false;
5596  if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
5597  MergeWithParentScope =
5598  Rec->isLocalClass() && !Function->isFunctionTemplateSpecialization();
5599 
5600  LocalInstantiationScope Scope(*this, MergeWithParentScope);
5601  auto RebuildTypeSourceInfoForDefaultSpecialMembers = [&]() {
5602  // Special members might get their TypeSourceInfo set up w.r.t the
5603  // PatternDecl context, in which case parameters could still be pointing
5604  // back to the original class, make sure arguments are bound to the
5605  // instantiated record instead.
5606  assert(PatternDecl->isDefaulted() &&
5607  "Special member needs to be defaulted");
5608  auto PatternSM = getDefaultedFunctionKind(PatternDecl).asSpecialMember();
5609  if (!(PatternSM == CXXSpecialMemberKind::CopyConstructor ||
5610  PatternSM == CXXSpecialMemberKind::CopyAssignment ||
5613  return;
5614 
5615  auto *NewRec = dyn_cast<CXXRecordDecl>(Function->getDeclContext());
5616  const auto *PatternRec =
5617  dyn_cast<CXXRecordDecl>(PatternDecl->getDeclContext());
5618  if (!NewRec || !PatternRec)
5619  return;
5620  if (!PatternRec->isLambda())
5621  return;
5622 
5623  struct SpecialMemberTypeInfoRebuilder
5624  : TreeTransform<SpecialMemberTypeInfoRebuilder> {
5626  const CXXRecordDecl *OldDecl;
5627  CXXRecordDecl *NewDecl;
5628 
5629  SpecialMemberTypeInfoRebuilder(Sema &SemaRef, const CXXRecordDecl *O,
5630  CXXRecordDecl *N)
5631  : TreeTransform(SemaRef), OldDecl(O), NewDecl(N) {}
5632 
5633  bool TransformExceptionSpec(SourceLocation Loc,
5635  SmallVectorImpl<QualType> &Exceptions,
5636  bool &Changed) {
5637  return false;
5638  }
5639 
5640  QualType TransformRecordType(TypeLocBuilder &TLB, RecordTypeLoc TL) {
5641  const RecordType *T = TL.getTypePtr();
5642  RecordDecl *Record = cast_or_null<RecordDecl>(
5643  getDerived().TransformDecl(TL.getNameLoc(), T->getDecl()));
5644  if (Record != OldDecl)
5645  return Base::TransformRecordType(TLB, TL);
5646 
5647  QualType Result = getDerived().RebuildRecordType(NewDecl);
5648  if (Result.isNull())
5649  return QualType();
5650 
5651  RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
5652  NewTL.setNameLoc(TL.getNameLoc());
5653  return Result;
5654  }
5655  } IR{*this, PatternRec, NewRec};
5656 
5657  TypeSourceInfo *NewSI = IR.TransformType(Function->getTypeSourceInfo());
5658  assert(NewSI && "Type Transform failed?");
5659  Function->setType(NewSI->getType());
5660  Function->setTypeSourceInfo(NewSI);
5661 
5662  ParmVarDecl *Parm = Function->getParamDecl(0);
5663  TypeSourceInfo *NewParmSI = IR.TransformType(Parm->getTypeSourceInfo());
5664  assert(NewParmSI && "Type transformation failed.");
5665  Parm->setType(NewParmSI->getType());
5666  Parm->setTypeSourceInfo(NewParmSI);
5667  };
5668 
5669  if (PatternDecl->isDefaulted()) {
5670  RebuildTypeSourceInfoForDefaultSpecialMembers();
5671  SetDeclDefaulted(Function, PatternDecl->getLocation());
5672  } else {
5674  Function, Function->getLexicalDeclContext(), /*Final=*/false,
5675  /*Innermost=*/std::nullopt, false, PatternDecl);
5676 
5677  // Substitute into the qualifier; we can get a substitution failure here
5678  // through evil use of alias templates.
5679  // FIXME: Is CurContext correct for this? Should we go to the (instantiation
5680  // of the) lexical context of the pattern?
5681  SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
5682 
5684 
5685  // Enter the scope of this instantiation. We don't use
5686  // PushDeclContext because we don't have a scope.
5687  Sema::ContextRAII savedContext(*this, Function);
5688 
5689  FPFeaturesStateRAII SavedFPFeatures(*this);
5691  FpPragmaStack.CurrentValue = FPOptionsOverride();
5692 
5693  if (addInstantiatedParametersToScope(Function, PatternDecl, Scope,
5694  TemplateArgs))
5695  return;
5696 
5697  StmtResult Body;
5698  if (PatternDecl->hasSkippedBody()) {
5700  Body = nullptr;
5701  } else {
5702  if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) {
5703  // If this is a constructor, instantiate the member initializers.
5704  InstantiateMemInitializers(Ctor, cast<CXXConstructorDecl>(PatternDecl),
5705  TemplateArgs);
5706 
5707  // If this is an MS ABI dllexport default constructor, instantiate any
5708  // default arguments.
5710  Ctor->isDefaultConstructor()) {
5712  }
5713  }
5714 
5715  // Instantiate the function body.
5716  Body = SubstStmt(Pattern, TemplateArgs);
5717 
5718  if (Body.isInvalid())
5719  Function->setInvalidDecl();
5720  }
5721  // FIXME: finishing the function body while in an expression evaluation
5722  // context seems wrong. Investigate more.
5723  ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true);
5724 
5725  PerformDependentDiagnostics(PatternDecl, TemplateArgs);
5726 
5727  if (auto *Listener = getASTMutationListener())
5728  Listener->FunctionDefinitionInstantiated(Function);
5729 
5730  savedContext.pop();
5731  }
5732 
5733  DeclGroupRef DG(Function);
5735 
5736  // This class may have local implicit instantiations that need to be
5737  // instantiation within this scope.
5738  LocalInstantiations.perform();
5739  Scope.Exit();
5740  GlobalInstantiations.perform();
5741 }
5742 
5744  VarTemplateDecl *VarTemplate, VarDecl *FromVar,
5745  const TemplateArgumentList *PartialSpecArgs,
5746  const TemplateArgumentListInfo &TemplateArgsInfo,
5748  SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs,
5749  LocalInstantiationScope *StartingScope) {
5750  if (FromVar->isInvalidDecl())
5751  return nullptr;
5752 
5753  InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
5754  if (Inst.isInvalid())
5755  return nullptr;
5756 
5757  // Instantiate the first declaration of the variable template: for a partial
5758  // specialization of a static data member template, the first declaration may
5759  // or may not be the declaration in the class; if it's in the class, we want
5760  // to instantiate a member in the class (a declaration), and if it's outside,
5761  // we want to instantiate a definition.
5762  //
5763  // If we're instantiating an explicitly-specialized member template or member
5764  // partial specialization, don't do this. The member specialization completely
5765  // replaces the original declaration in this case.
5766  bool IsMemberSpec = false;
5767  MultiLevelTemplateArgumentList MultiLevelList;
5768  if (auto *PartialSpec =
5769  dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar)) {
5770  assert(PartialSpecArgs);
5771  IsMemberSpec = PartialSpec->isMemberSpecialization();
5772  MultiLevelList.addOuterTemplateArguments(
5773  PartialSpec, PartialSpecArgs->asArray(), /*Final=*/false);
5774  } else {
5775  assert(VarTemplate == FromVar->getDescribedVarTemplate());
5776  IsMemberSpec = VarTemplate->isMemberSpecialization();
5777  MultiLevelList.addOuterTemplateArguments(VarTemplate, Converted,
5778  /*Final=*/false);
5779  }
5780  if (!IsMemberSpec)
5781  FromVar = FromVar->getFirstDecl();
5782 
5783  TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
5784  MultiLevelList);
5785 
5786  // TODO: Set LateAttrs and StartingScope ...
5787 
5788  auto *VD = cast_or_null<VarTemplateSpecializationDecl>(
5790  VarTemplate, FromVar, TemplateArgsInfo, Converted));
5791 
5792  SYCL().addSyclVarDecl(VD);
5793 
5794  return VD;
5795 }
5796 
5797 /// Instantiates a variable template specialization by completing it
5798 /// with appropriate type information and initializer.
5800  VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
5801  const MultiLevelTemplateArgumentList &TemplateArgs) {
5802  assert(PatternDecl->isThisDeclarationADefinition() &&
5803  "don't have a definition to instantiate from");
5804 
5805  // Do substitution on the type of the declaration
5806  TypeSourceInfo *DI =
5807  SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
5808  PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
5809  if (!DI)
5810  return nullptr;
5811 
5812  // Update the type of this variable template specialization.
5813  VarSpec->setType(DI->getType());
5814 
5815  // Convert the declaration into a definition now.
5816  VarSpec->setCompleteDefinition();
5817 
5818  // Instantiate the initializer.
5819  InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
5820 
5821  if (getLangOpts().OpenCL)
5822  deduceOpenCLAddressSpace(VarSpec);
5823 
5824  return VarSpec;
5825 }
5826 
5827 /// BuildVariableInstantiation - Used after a new variable has been created.
5828 /// Sets basic variable data and decides whether to postpone the
5829 /// variable instantiation.
5831  VarDecl *NewVar, VarDecl *OldVar,
5832  const MultiLevelTemplateArgumentList &TemplateArgs,
5833  LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
5834  LocalInstantiationScope *StartingScope,
5835  bool InstantiatingVarTemplate,
5836  VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) {
5837  // Instantiating a partial specialization to produce a partial
5838  // specialization.
5839  bool InstantiatingVarTemplatePartialSpec =
5840  isa<VarTemplatePartialSpecializationDecl>(OldVar) &&
5841  isa<VarTemplatePartialSpecializationDecl>(NewVar);
5842  // Instantiating from a variable template (or partial specialization) to
5843  // produce a variable template specialization.
5844  bool InstantiatingSpecFromTemplate =
5845  isa<VarTemplateSpecializationDecl>(NewVar) &&
5846  (OldVar->getDescribedVarTemplate() ||
5847  isa<VarTemplatePartialSpecializationDecl>(OldVar));
5848 
5849  // If we are instantiating a local extern declaration, the
5850  // instantiation belongs lexically to the containing function.
5851  // If we are instantiating a static data member defined
5852  // out-of-line, the instantiation will have the same lexical
5853  // context (which will be a namespace scope) as the template.
5854  if (OldVar->isLocalExternDecl()) {
5855  NewVar->setLocalExternDecl();
5856  NewVar->setLexicalDeclContext(Owner);
5857  } else if (OldVar->isOutOfLine())
5858  NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
5859  NewVar->setTSCSpec(OldVar->getTSCSpec());
5860  NewVar->setInitStyle(OldVar->getInitStyle());
5861  NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
5862  NewVar->setObjCForDecl(OldVar->isObjCForDecl());
5863  NewVar->setConstexpr(OldVar->isConstexpr());
5864  NewVar->setInitCapture(OldVar->isInitCapture());
5866  OldVar->isPreviousDeclInSameBlockScope());
5867  NewVar->setAccess(OldVar->getAccess());
5868 
5869  if (!OldVar->isStaticDataMember()) {
5870  if (OldVar->isUsed(false))
5871  NewVar->setIsUsed();
5872  NewVar->setReferenced(OldVar->isReferenced());
5873  }
5874 
5875  InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
5876 
5878  *this, NewVar->getDeclName(), NewVar->getLocation(),
5883 
5884  if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
5886  OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
5887  // We have a previous declaration. Use that one, so we merge with the
5888  // right type.
5889  if (NamedDecl *NewPrev = FindInstantiatedDecl(
5890  NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
5891  Previous.addDecl(NewPrev);
5892  } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
5893  OldVar->hasLinkage()) {
5894  LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
5895  } else if (PrevDeclForVarTemplateSpecialization) {
5896  Previous.addDecl(PrevDeclForVarTemplateSpecialization);
5897  }
5899 
5900  if (!InstantiatingVarTemplate) {
5901  NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
5902  if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
5903  NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
5904  }
5905 
5906  if (!OldVar->isOutOfLine()) {
5907  if (NewVar->getDeclContext()->isFunctionOrMethod())
5909  }
5910 
5911  // Link instantiations of static data members back to the template from
5912  // which they were instantiated.
5913  //
5914  // Don't do this when instantiating a template (we link the template itself
5915  // back in that case) nor when instantiating a static data member template
5916  // (that's not a member specialization).
5917  if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate &&
5918  !InstantiatingSpecFromTemplate)
5919  NewVar->setInstantiationOfStaticDataMember(OldVar,
5921 
5922  // If the pattern is an (in-class) explicit specialization, then the result
5923  // is also an explicit specialization.
5924  if (VarTemplateSpecializationDecl *OldVTSD =
5925  dyn_cast<VarTemplateSpecializationDecl>(OldVar)) {
5926  if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization &&
5927  !isa<VarTemplatePartialSpecializationDecl>(OldVTSD))
5928  cast<VarTemplateSpecializationDecl>(NewVar)->setSpecializationKind(
5930  }
5931 
5932  // Forward the mangling number from the template to the instantiated decl.
5935 
5936  // Figure out whether to eagerly instantiate the initializer.
5937  if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) {
5938  // We're producing a template. Don't instantiate the initializer yet.
5939  } else if (NewVar->getType()->isUndeducedType()) {
5940  // We need the type to complete the declaration of the variable.
5941  InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
5942  } else if (InstantiatingSpecFromTemplate ||
5943  (OldVar->isInline() && OldVar->isThisDeclarationADefinition() &&
5944  !NewVar->isThisDeclarationADefinition())) {
5945  // Delay instantiation of the initializer for variable template
5946  // specializations or inline static data members until a definition of the
5947  // variable is needed.
5948  } else {
5949  InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
5950  }
5951 
5952  // Diagnose unused local variables with dependent types, where the diagnostic
5953  // will have been deferred.
5954  if (!NewVar->isInvalidDecl() &&
5955  NewVar->getDeclContext()->isFunctionOrMethod() &&
5956  OldVar->getType()->isDependentType())
5957  DiagnoseUnusedDecl(NewVar);
5958 }
5959 
5960 /// Instantiate the initializer of a variable.
5962  VarDecl *Var, VarDecl *OldVar,
5963  const MultiLevelTemplateArgumentList &TemplateArgs) {
5965  L->VariableDefinitionInstantiated(Var);
5966 
5967  // We propagate the 'inline' flag with the initializer, because it
5968  // would otherwise imply that the variable is a definition for a
5969  // non-static data member.
5970  if (OldVar->isInlineSpecified())
5971  Var->setInlineSpecified();
5972  else if (OldVar->isInline())
5973  Var->setImplicitlyInline();
5974 
5975  if (OldVar->getInit()) {
5978 
5980  // Instantiate the initializer.
5981  ExprResult Init;
5982 
5983  {
5984  ContextRAII SwitchContext(*this, Var->getDeclContext());
5985  Init = SubstInitializer(OldVar->getInit(), TemplateArgs,
5986  OldVar->getInitStyle() == VarDecl::CallInit);
5987  }
5988 
5989  if (!Init.isInvalid()) {
5990  Expr *InitExpr = Init.get();
5991 
5992  if (Var->hasAttr<DLLImportAttr>() &&
5993  (!InitExpr ||
5994  !InitExpr->isConstantInitializer(getASTContext(), false))) {
5995  // Do not dynamically initialize dllimport variables.
5996  } else if (InitExpr) {
5997  bool DirectInit = OldVar->isDirectInit();
5998  AddInitializerToDecl(Var, InitExpr, DirectInit);
5999  } else
6001  } else {
6002  // FIXME: Not too happy about invalidating the declaration
6003  // because of a bogus initializer.
6004  Var->setInvalidDecl();
6005  }
6006  } else {
6007  // `inline` variables are a definition and declaration all in one; we won't
6008  // pick up an initializer from anywhere else.
6009  if (Var->isStaticDataMember() && !Var->isInline()) {
6010  if (!Var->isOutOfLine())
6011  return;
6012 
6013  // If the declaration inside the class had an initializer, don't add
6014  // another one to the out-of-line definition.
6015  if (OldVar->getFirstDecl()->hasInit())
6016  return;
6017  }
6018 
6019  // We'll add an initializer to a for-range declaration later.
6020  if (Var->isCXXForRangeDecl() || Var->isObjCForDecl())
6021  return;
6022 
6024  }
6025 
6026  if (getLangOpts().CUDA)
6028 }
6029 
6030 /// Instantiate the definition of the given variable from its
6031 /// template.
6032 ///
6033 /// \param PointOfInstantiation the point at which the instantiation was
6034 /// required. Note that this is not precisely a "point of instantiation"
6035 /// for the variable, but it's close.
6036 ///
6037 /// \param Var the already-instantiated declaration of a templated variable.
6038 ///
6039 /// \param Recursive if true, recursively instantiates any functions that
6040 /// are required by this instantiation.
6041 ///
6042 /// \param DefinitionRequired if true, then we are performing an explicit
6043 /// instantiation where a definition of the variable is required. Complain
6044 /// if there is no such definition.
6046  VarDecl *Var, bool Recursive,
6047  bool DefinitionRequired, bool AtEndOfTU) {
6048  if (Var->isInvalidDecl())
6049  return;
6050 
6051  // Never instantiate an explicitly-specialized entity.
6054  if (TSK == TSK_ExplicitSpecialization)
6055  return;
6056 
6057  // Find the pattern and the arguments to substitute into it.
6058  VarDecl *PatternDecl = Var->getTemplateInstantiationPattern();
6059  assert(PatternDecl && "no pattern for templated variable");
6060  MultiLevelTemplateArgumentList TemplateArgs =
6062 
6064  dyn_cast<VarTemplateSpecializationDecl>(Var);
6065  if (VarSpec) {
6066  // If this is a static data member template, there might be an
6067  // uninstantiated initializer on the declaration. If so, instantiate
6068  // it now.
6069  //
6070  // FIXME: This largely duplicates what we would do below. The difference
6071  // is that along this path we may instantiate an initializer from an
6072  // in-class declaration of the template and instantiate the definition
6073  // from a separate out-of-class definition.
6074  if (PatternDecl->isStaticDataMember() &&
6075  (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
6076  !Var->hasInit()) {
6077  // FIXME: Factor out the duplicated instantiation context setup/tear down
6078  // code here.
6079  InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
6080  if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
6081  return;
6083  "instantiating variable initializer");
6084 
6085  // The instantiation is visible here, even if it was first declared in an
6086  // unimported module.
6088 
6089  // If we're performing recursive template instantiation, create our own
6090  // queue of pending implicit instantiations that we will instantiate
6091  // later, while we're still within our own instantiation context.
6092  GlobalEagerInstantiationScope GlobalInstantiations(*this,
6093  /*Enabled=*/Recursive);
6094  LocalInstantiationScope Local(*this);
6095  LocalEagerInstantiationScope LocalInstantiations(*this);
6096 
6097  // Enter the scope of this instantiation. We don't use
6098  // PushDeclContext because we don't have a scope.
6099  ContextRAII PreviousContext(*this, Var->getDeclContext());
6100  InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
6101  PreviousContext.pop();
6102 
6103  // This variable may have local implicit instantiations that need to be
6104  // instantiated within this scope.
6105  LocalInstantiations.perform();
6106  Local.Exit();
6107  GlobalInstantiations.perform();
6108  }
6109  } else {
6110  assert(Var->isStaticDataMember() && PatternDecl->isStaticDataMember() &&
6111  "not a static data member?");
6112  }
6113 
6114  VarDecl *Def = PatternDecl->getDefinition(getASTContext());
6115 
6116  // If we don't have a definition of the variable template, we won't perform
6117  // any instantiation. Rather, we rely on the user to instantiate this
6118  // definition (or provide a specialization for it) in another translation
6119  // unit.
6120  if (!Def && !DefinitionRequired) {
6122  PendingInstantiations.push_back(
6123  std::make_pair(Var, PointOfInstantiation));
6124  } else if (TSK == TSK_ImplicitInstantiation) {
6125  // Warn about missing definition at the end of translation unit.
6126  if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
6127  !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
6128  Diag(PointOfInstantiation, diag::warn_var_template_missing)
6129  << Var;
6130  Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
6131  if (getLangOpts().CPlusPlus11)
6132  Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
6133  }
6134  return;
6135  }
6136  }
6137 
6138  // FIXME: We need to track the instantiation stack in order to know which
6139  // definitions should be visible within this instantiation.
6140  // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
6141  if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var,
6142  /*InstantiatedFromMember*/false,
6143  PatternDecl, Def, TSK,
6144  /*Complain*/DefinitionRequired))
6145  return;
6146 
6147  // C++11 [temp.explicit]p10:
6148  // Except for inline functions, const variables of literal types, variables
6149  // of reference types, [...] explicit instantiation declarations
6150  // have the effect of suppressing the implicit instantiation of the entity
6151  // to which they refer.
6152  //
6153  // FIXME: That's not exactly the same as "might be usable in constant
6154  // expressions", which only allows constexpr variables and const integral
6155  // types, not arbitrary const literal types.
6158  return;
6159 
6160  // Make sure to pass the instantiated variable to the consumer at the end.
6161  struct PassToConsumerRAII {
6162  Sema &SemaRef;
6164  VarDecl *Var;
6165 
6166  PassToConsumerRAII(Sema &SemaRef, ASTConsumer &Consumer, VarDecl *Var)
6167  : SemaRef(SemaRef), Consumer(Consumer), Var(Var) {}
6168 
6169  ~PassToConsumerRAII() {
6170  // Do not explicitly emit non-const static data member definitions
6171  // on SYCL device.
6172  if (!SemaRef.getLangOpts().SYCLIsDevice || !Var->isStaticDataMember() ||
6173  Var->isConstexpr() ||
6174  (Var->getType().isConstQualified() && Var->getInit() &&
6176  false)))
6178  }
6179  } PassToConsumerRAII(*this, Consumer, Var);
6180 
6181  // If we already have a definition, we're done.
6182  if (VarDecl *Def = Var->getDefinition()) {
6183  // We may be explicitly instantiating something we've already implicitly
6184  // instantiated.
6186  PointOfInstantiation);
6187  return;
6188  }
6189 
6190  InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
6191  if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
6192  return;
6194  "instantiating variable definition");
6195 
6196  // If we're performing recursive template instantiation, create our own
6197  // queue of pending implicit instantiations that we will instantiate later,
6198  // while we're still within our own instantiation context.
6199  GlobalEagerInstantiationScope GlobalInstantiations(*this,
6200  /*Enabled=*/Recursive);
6201 
6202  // Enter the scope of this instantiation. We don't use
6203  // PushDeclContext because we don't have a scope.
6204  ContextRAII PreviousContext(*this, Var->getDeclContext());
6205  LocalInstantiationScope Local(*this);
6206 
6207  LocalEagerInstantiationScope LocalInstantiations(*this);
6208 
6209  VarDecl *OldVar = Var;
6210  if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
6211  // We're instantiating an inline static data member whose definition was
6212  // provided inside the class.
6213  InstantiateVariableInitializer(Var, Def, TemplateArgs);
6214  } else if (!VarSpec) {
6215  Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
6216  TemplateArgs));
6217  } else if (Var->isStaticDataMember() &&
6218  Var->getLexicalDeclContext()->isRecord()) {
6219  // We need to instantiate the definition of a static data member template,
6220  // and all we have is the in-class declaration of it. Instantiate a separate
6221  // declaration of the definition.
6222  TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
6223  TemplateArgs);
6224 
6225  TemplateArgumentListInfo TemplateArgInfo;
6226  if (const ASTTemplateArgumentListInfo *ArgInfo =
6227  VarSpec->getTemplateArgsAsWritten()) {
6228  TemplateArgInfo.setLAngleLoc(ArgInfo->getLAngleLoc());
6229  TemplateArgInfo.setRAngleLoc(ArgInfo->getRAngleLoc());
6230  for (const TemplateArgumentLoc &Arg : ArgInfo->arguments())
6231  TemplateArgInfo.addArgument(Arg);
6232  }
6233 
6234  Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
6235  VarSpec->getSpecializedTemplate(), Def, TemplateArgInfo,
6236  VarSpec->getTemplateArgs().asArray(), VarSpec));
6237  if (Var) {
6238  llvm::PointerUnion<VarTemplateDecl *,
6239  VarTemplatePartialSpecializationDecl *> PatternPtr =
6242  PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
6243  cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
6244  Partial, &VarSpec->getTemplateInstantiationArgs());
6245 
6246  // Attach the initializer.
6247  InstantiateVariableInitializer(Var, Def, TemplateArgs);
6248  }
6249  } else
6250  // Complete the existing variable's definition with an appropriately
6251  // substituted type and initializer.
6252  Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
6253 
6254  PreviousContext.pop();
6255 
6256  if (Var) {
6257  PassToConsumerRAII.Var = Var;
6259  OldVar->getPointOfInstantiation());
6260  }
6261 
6262  // This variable may have local implicit instantiations that need to be
6263  // instantiated within this scope.
6264  LocalInstantiations.perform();
6265  Local.Exit();
6266  GlobalInstantiations.perform();
6267 }
6268 
6269 void
6271  const CXXConstructorDecl *Tmpl,
6272  const MultiLevelTemplateArgumentList &TemplateArgs) {
6273 
6275  bool AnyErrors = Tmpl->isInvalidDecl();
6276 
6277  // Instantiate all the initializers.
6278  for (const auto *Init : Tmpl->inits()) {
6279  // Only instantiate written initializers, let Sema re-construct implicit
6280  // ones.
6281  if (!Init->isWritten())
6282  continue;
6283 
6284  SourceLocation EllipsisLoc;
6285 
6286  if (Init->isPackExpansion()) {
6287  // This is a pack expansion. We should expand it now.
6288  TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
6290  collectUnexpandedParameterPacks(BaseTL, Unexpanded);
6291  collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
6292  bool ShouldExpand = false;
6293  bool RetainExpansion = false;
6294  std::optional<unsigned> NumExpansions;
6295  if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
6296  BaseTL.getSourceRange(),
6297  Unexpanded,
6298  TemplateArgs, ShouldExpand,
6299  RetainExpansion,
6300  NumExpansions)) {
6301  AnyErrors = true;
6302  New->setInvalidDecl();
6303  continue;
6304  }
6305  assert(ShouldExpand && "Partial instantiation of base initializer?");
6306 
6307  // Loop over all of the arguments in the argument pack(s),
6308  for (unsigned I = 0; I != *NumExpansions; ++I) {
6309  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
6310 
6311  // Instantiate the initializer.
6312  ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
6313  /*CXXDirectInit=*/true);
6314  if (TempInit.isInvalid()) {
6315  AnyErrors = true;
6316  break;
6317  }
6318 
6319  // Instantiate the base type.
6320  TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
6321  TemplateArgs,
6322  Init->getSourceLocation(),
6323  New->getDeclName());
6324  if (!BaseTInfo) {
6325  AnyErrors = true;
6326  break;
6327  }
6328 
6329  // Build the initializer.
6330  MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
6331  BaseTInfo, TempInit.get(),
6332  New->getParent(),
6333  SourceLocation());
6334  if (NewInit.isInvalid()) {
6335  AnyErrors = true;
6336  break;
6337  }
6338 
6339  NewInits.push_back(NewInit.get());
6340  }
6341 
6342  continue;
6343  }
6344 
6345  // Instantiate the initializer.
6346  ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
6347  /*CXXDirectInit=*/true);
6348  if (TempInit.isInvalid()) {
6349  AnyErrors = true;
6350  continue;
6351  }
6352 
6353  MemInitResult NewInit;
6354  if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
6355  TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
6356  TemplateArgs,
6357  Init->getSourceLocation(),
6358  New->getDeclName());
6359  if (!TInfo) {
6360  AnyErrors = true;
6361  New->setInvalidDecl();
6362  continue;
6363  }
6364 
6365  if (Init->isBaseInitializer())
6366  NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
6367  New->getParent(), EllipsisLoc);
6368  else
6369  NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
6370  cast<CXXRecordDecl>(CurContext->getParent()));
6371  } else if (Init->isMemberInitializer()) {
6372  FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
6373  Init->getMemberLocation(),
6374  Init->getMember(),
6375  TemplateArgs));
6376  if (!Member) {
6377  AnyErrors = true;
6378  New->setInvalidDecl();
6379  continue;
6380  }
6381 
6382  NewInit = BuildMemberInitializer(Member, TempInit.get(),
6383  Init->getSourceLocation());
6384  } else if (Init->isIndirectMemberInitializer()) {
6385  IndirectFieldDecl *IndirectMember =
6386  cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
6387  Init->getMemberLocation(),
6388  Init->getIndirectMember(), TemplateArgs));
6389 
6390  if (!IndirectMember) {
6391  AnyErrors = true;
6392  New->setInvalidDecl();
6393  continue;
6394  }
6395 
6396  NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
6397  Init->getSourceLocation());
6398  }
6399 
6400  if (NewInit.isInvalid()) {
6401  AnyErrors = true;
6402  New->setInvalidDecl();
6403  } else {
6404  NewInits.push_back(NewInit.get());
6405  }
6406  }
6407 
6408  // Assign all the initializers to the new constructor.
6410  /*FIXME: ColonLoc */
6411  SourceLocation(),
6412  NewInits,
6413  AnyErrors);
6414 }
6415 
6416 // TODO: this could be templated if the various decl types used the
6417 // same method name.
6419  ClassTemplateDecl *Instance) {
6420  Pattern = Pattern->getCanonicalDecl();
6421 
6422  do {
6423  Instance = Instance->getCanonicalDecl();
6424  if (Pattern == Instance) return true;
6425  Instance = Instance->getInstantiatedFromMemberTemplate();
6426  } while (Instance);
6427 
6428  return false;
6429 }
6430 
6432  FunctionTemplateDecl *Instance) {
6433  Pattern = Pattern->getCanonicalDecl();
6434 
6435  do {
6436  Instance = Instance->getCanonicalDecl();
6437  if (Pattern == Instance) return true;
6438  Instance = Instance->getInstantiatedFromMemberTemplate();
6439  } while (Instance);
6440 
6441  return false;
6442 }
6443 
6444 static bool
6447  Pattern
6448  = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
6449  do {
6450  Instance = cast<ClassTemplatePartialSpecializationDecl>(
6451  Instance->getCanonicalDecl());
6452  if (Pattern == Instance)
6453  return true;
6454  Instance = Instance->getInstantiatedFromMember();
6455  } while (Instance);
6456 
6457  return false;
6458 }
6459 
6460 static bool isInstantiationOf(CXXRecordDecl *Pattern,
6461  CXXRecordDecl *Instance) {
6462  Pattern = Pattern->getCanonicalDecl();
6463 
6464  do {
6465  Instance = Instance->getCanonicalDecl();
6466  if (Pattern == Instance) return true;
6467  Instance = Instance->getInstantiatedFromMemberClass();
6468  } while (Instance);
6469 
6470  return false;
6471 }
6472 
6473 static bool isInstantiationOf(FunctionDecl *Pattern,
6474  FunctionDecl *Instance) {
6475  Pattern = Pattern->getCanonicalDecl();
6476 
6477  do {
6478  Instance = Instance->getCanonicalDecl();
6479  if (Pattern == Instance) return true;
6480  Instance = Instance->getInstantiatedFromMemberFunction();
6481  } while (Instance);
6482 
6483  return false;
6484 }
6485 
6486 static bool isInstantiationOf(EnumDecl *Pattern,
6487  EnumDecl *Instance) {
6488  Pattern = Pattern->getCanonicalDecl();
6489 
6490  do {
6491  Instance = Instance->getCanonicalDecl();
6492  if (Pattern == Instance) return true;
6493  Instance = Instance->getInstantiatedFromMemberEnum();
6494  } while (Instance);
6495 
6496  return false;
6497 }
6498 
6499 static bool isInstantiationOf(UsingShadowDecl *Pattern,
6500  UsingShadowDecl *Instance,
6501  ASTContext &C) {
6502  return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
6503  Pattern);
6504 }
6505 
6506 static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance,
6507  ASTContext &C) {
6508  return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
6509 }
6510 
6511 template<typename T>
6512 static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other,
6513  ASTContext &Ctx) {
6514  // An unresolved using declaration can instantiate to an unresolved using
6515  // declaration, or to a using declaration or a using declaration pack.
6516  //
6517  // Multiple declarations can claim to be instantiated from an unresolved
6518  // using declaration if it's a pack expansion. We want the UsingPackDecl
6519  // in that case, not the individual UsingDecls within the pack.
6520  bool OtherIsPackExpansion;
6521  NamedDecl *OtherFrom;
6522  if (auto *OtherUUD = dyn_cast<T>(Other)) {
6523  OtherIsPackExpansion = OtherUUD->isPackExpansion();
6524  OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD);
6525  } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) {
6526  OtherIsPackExpansion = true;
6527  OtherFrom = OtherUPD->getInstantiatedFromUsingDecl();
6528  } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) {
6529  OtherIsPackExpansion = false;
6530  OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD);
6531  } else {
6532  return false;
6533  }
6534  return Pattern->isPackExpansion() == OtherIsPackExpansion &&
6535  declaresSameEntity(OtherFrom, Pattern);
6536 }
6537 
6539  VarDecl *Instance) {
6540  assert(Instance->isStaticDataMember());
6541 
6542  Pattern = Pattern->getCanonicalDecl();
6543 
6544  do {
6545  Instance = Instance->getCanonicalDecl();
6546  if (Pattern == Instance) return true;
6547  Instance = Instance->getInstantiatedFromStaticDataMember();
6548  } while (Instance);
6549 
6550  return false;
6551 }
6552 
6553 // Other is the prospective instantiation
6554 // D is the prospective pattern
6555 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
6556  if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D))
6557  return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
6558 
6559  if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D))
6560  return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
6561 
6562  if (D->getKind() != Other->getKind())
6563  return false;
6564 
6565  if (auto *Record = dyn_cast<CXXRecordDecl>(Other))
6566  return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
6567 
6568  if (auto *Function = dyn_cast<FunctionDecl>(Other))
6569  return isInstantiationOf(cast<FunctionDecl>(D), Function);
6570 
6571  if (auto *Enum = dyn_cast<EnumDecl>(Other))
6572  return isInstantiationOf(cast<EnumDecl>(D), Enum);
6573 
6574  if (auto *Var = dyn_cast<VarDecl>(Other))
6575  if (Var->isStaticDataMember())
6576  return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
6577 
6578  if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other))
6579  return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
6580 
6581  if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other))
6582  return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
6583 
6584  if (auto *PartialSpec =
6585  dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
6586  return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
6587  PartialSpec);
6588 
6589  if (auto *Field = dyn_cast<FieldDecl>(Other)) {
6590  if (!Field->getDeclName()) {
6591  // This is an unnamed field.
6593  cast<FieldDecl>(D));
6594  }
6595  }
6596 
6597  if (auto *Using = dyn_cast<UsingDecl>(Other))
6598  return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
6599 
6600  if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other))
6601  return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
6602 
6603  return D->getDeclName() &&
6604  D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
6605 }
6606 
6607 template<typename ForwardIterator>
6609  NamedDecl *D,
6610  ForwardIterator first,
6611  ForwardIterator last) {
6612  for (; first != last; ++first)
6613  if (isInstantiationOf(Ctx, D, *first))
6614  return cast<NamedDecl>(*first);
6615 
6616  return nullptr;
6617 }
6618 
6619 /// Finds the instantiation of the given declaration context
6620 /// within the current instantiation.
6621 ///
6622 /// \returns NULL if there was an error
6624  const MultiLevelTemplateArgumentList &TemplateArgs) {
6625  if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
6626  Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true);
6627  return cast_or_null<DeclContext>(ID);
6628  } else return DC;
6629 }
6630 
6631 /// Determine whether the given context is dependent on template parameters at
6632 /// level \p Level or below.
6633 ///
6634 /// Sometimes we only substitute an inner set of template arguments and leave
6635 /// the outer templates alone. In such cases, contexts dependent only on the
6636 /// outer levels are not effectively dependent.
6637 static bool isDependentContextAtLevel(DeclContext *DC, unsigned Level) {
6638  if (!DC->isDependentContext())
6639  return false;
6640  if (!Level)
6641  return true;
6642  return cast<Decl>(DC)->getTemplateDepth() > Level;
6643 }
6644 
6645 /// Find the instantiation of the given declaration within the
6646 /// current instantiation.
6647 ///
6648 /// This routine is intended to be used when \p D is a declaration
6649 /// referenced from within a template, that needs to mapped into the
6650 /// corresponding declaration within an instantiation. For example,
6651 /// given:
6652 ///
6653 /// \code
6654 /// template<typename T>
6655 /// struct X {
6656 /// enum Kind {
6657 /// KnownValue = sizeof(T)
6658 /// };
6659 ///
6660 /// bool getKind() const { return KnownValue; }
6661 /// };
6662 ///
6663 /// template struct X<int>;
6664 /// \endcode
6665 ///
6666 /// In the instantiation of X<int>::getKind(), we need to map the \p
6667 /// EnumConstantDecl for \p KnownValue (which refers to
6668 /// X<T>::<Kind>::KnownValue) to its instantiation (X<int>::<Kind>::KnownValue).
6669 /// \p FindInstantiatedDecl performs this mapping from within the instantiation
6670 /// of X<int>.
6672  const MultiLevelTemplateArgumentList &TemplateArgs,
6673  bool FindingInstantiatedContext) {
6674  DeclContext *ParentDC = D->getDeclContext();
6675  // Determine whether our parent context depends on any of the template
6676  // arguments we're currently substituting.
6677  bool ParentDependsOnArgs = isDependentContextAtLevel(
6678  ParentDC, TemplateArgs.getNumRetainedOuterLevels());
6679  // FIXME: Parameters of pointer to functions (y below) that are themselves
6680  // parameters (p below) can have their ParentDC set to the translation-unit
6681  // - thus we can not consistently check if the ParentDC of such a parameter
6682  // is Dependent or/and a FunctionOrMethod.
6683  // For e.g. this code, during Template argument deduction tries to
6684  // find an instantiated decl for (T y) when the ParentDC for y is
6685  // the translation unit.
6686  // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
6687  // float baz(float(*)()) { return 0.0; }
6688  // Foo(baz);
6689  // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
6690  // it gets here, always has a FunctionOrMethod as its ParentDC??
6691  // For now:
6692  // - as long as we have a ParmVarDecl whose parent is non-dependent and
6693  // whose type is not instantiation dependent, do nothing to the decl
6694  // - otherwise find its instantiated decl.
6695  if (isa<ParmVarDecl>(D) && !ParentDependsOnArgs &&
6696  !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
6697  return D;
6698  if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
6699  isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
6700  (ParentDependsOnArgs && (ParentDC->isFunctionOrMethod() ||
6701  isa<OMPDeclareReductionDecl>(ParentDC) ||
6702  isa<OMPDeclareMapperDecl>(ParentDC))) ||
6703  (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda() &&
6704  cast<CXXRecordDecl>(D)->getTemplateDepth() >
6705  TemplateArgs.getNumRetainedOuterLevels())) {
6706  // D is a local of some kind. Look into the map of local
6707  // declarations to their instantiations.
6709  if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
6710  if (Decl *FD = Found->dyn_cast<Decl *>())
6711  return cast<NamedDecl>(FD);
6712 
6713  int PackIdx = ArgumentPackSubstitutionIndex;
6714  assert(PackIdx != -1 &&
6715  "found declaration pack but not pack expanding");
6716  typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
6717  return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
6718  }
6719  }
6720 
6721  // If we're performing a partial substitution during template argument
6722  // deduction, we may not have values for template parameters yet. They
6723  // just map to themselves.
6724  if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
6725  isa<TemplateTemplateParmDecl>(D))
6726  return D;
6727 
6728  if (D->isInvalidDecl())
6729  return nullptr;
6730 
6731  // Normally this function only searches for already instantiated declaration
6732  // however we have to make an exclusion for local types used before
6733  // definition as in the code:
6734  //
6735  // template<typename T> void f1() {
6736  // void g1(struct x1);
6737  // struct x1 {};
6738  // }
6739  //
6740  // In this case instantiation of the type of 'g1' requires definition of
6741  // 'x1', which is defined later. Error recovery may produce an enum used
6742  // before definition. In these cases we need to instantiate relevant
6743  // declarations here.
6744  bool NeedInstantiate = false;
6745  if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
6746  NeedInstantiate = RD->isLocalClass();
6747  else if (isa<TypedefNameDecl>(D) &&
6748  isa<CXXDeductionGuideDecl>(D->getDeclContext()))
6749  NeedInstantiate = true;
6750  else
6751  NeedInstantiate = isa<EnumDecl>(D);
6752  if (NeedInstantiate) {
6753  Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
6755  return cast<TypeDecl>(Inst);
6756  }
6757 
6758  // If we didn't find the decl, then we must have a label decl that hasn't
6759  // been found yet. Lazily instantiate it and return it now.
6760  assert(isa<LabelDecl>(D));
6761 
6762  Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
6763  assert(Inst && "Failed to instantiate label??");
6764 
6766  return cast<LabelDecl>(Inst);
6767  }
6768 
6769  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
6770  if (!Record->isDependentContext())
6771  return D;
6772 
6773  // Determine whether this record is the "templated" declaration describing
6774  // a class template or class template specialization.
6775  ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
6776  if (ClassTemplate)
6777  ClassTemplate = ClassTemplate->getCanonicalDecl();
6778  else if (ClassTemplateSpecializationDecl *Spec =
6779  dyn_cast<ClassTemplateSpecializationDecl>(Record))
6780  ClassTemplate = Spec->getSpecializedTemplate()->getCanonicalDecl();
6781 
6782  // Walk the current context to find either the record or an instantiation of
6783  // it.
6784  DeclContext *DC = CurContext;
6785  while (!DC->isFileContext()) {
6786  // If we're performing substitution while we're inside the template
6787  // definition, we'll find our own context. We're done.
6788  if (DC->Equals(Record))
6789  return Record;
6790 
6791  if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
6792  // Check whether we're in the process of instantiating a class template
6793  // specialization of the template we're mapping.
6794  if (ClassTemplateSpecializationDecl *InstSpec
6795  = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
6796  ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
6797  if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
6798  return InstRecord;
6799  }
6800 
6801  // Check whether we're in the process of instantiating a member class.
6802  if (isInstantiationOf(Record, InstRecord))
6803  return InstRecord;
6804  }
6805 
6806  // Move to the outer template scope.
6807  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
6808  if (FD->getFriendObjectKind() &&
6810  DC = FD->getLexicalDeclContext();
6811  continue;
6812  }
6813  // An implicit deduction guide acts as if it's within the class template
6814  // specialization described by its name and first N template params.
6815  auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD);
6816  if (Guide && Guide->isImplicit()) {
6817  TemplateDecl *TD = Guide->getDeducedTemplate();
6818  // Convert the arguments to an "as-written" list.
6820  for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front(
6821  TD->getTemplateParameters()->size())) {
6822  ArrayRef<TemplateArgument> Unpacked(Arg);
6823  if (Arg.getKind() == TemplateArgument::Pack)
6824  Unpacked = Arg.pack_elements();
6825  for (TemplateArgument UnpackedArg : Unpacked)
6826  Args.addArgument(
6827  getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc));
6828  }
6830  if (T.isNull())
6831  return nullptr;
6832  CXXRecordDecl *SubstRecord = T->getAsCXXRecordDecl();
6833 
6834  if (!SubstRecord) {
6835  // T can be a dependent TemplateSpecializationType when performing a
6836  // substitution for building a deduction guide.
6837  assert(CodeSynthesisContexts.back().Kind ==
6839  // Return a nullptr as a sentinel value, we handle it properly in
6840  // the TemplateInstantiator::TransformInjectedClassNameType
6841  // override, which we transform it to a TemplateSpecializationType.
6842  return nullptr;
6843  }
6844  // Check that this template-id names the primary template and not a
6845  // partial or explicit specialization. (In the latter cases, it's
6846  // meaningless to attempt to find an instantiation of D within the
6847  // specialization.)
6848  // FIXME: The standard doesn't say what should happen here.
6849  if (FindingInstantiatedContext &&
6851  Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) {
6852  Diag(Loc, diag::err_specialization_not_primary_template)
6853  << T << (SubstRecord->getTemplateSpecializationKind() ==
6855  return nullptr;
6856  }
6857  DC = SubstRecord;
6858  continue;
6859  }
6860  }
6861 
6862  DC = DC->getParent();
6863  }
6864 
6865  // Fall through to deal with other dependent record types (e.g.,
6866  // anonymous unions in class templates).
6867  }
6868 
6869  if (!ParentDependsOnArgs)
6870  return D;
6871 
6872  ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
6873  if (!ParentDC)
6874  return nullptr;
6875 
6876  if (ParentDC != D->getDeclContext()) {
6877  // We performed some kind of instantiation in the parent context,
6878  // so now we need to look into the instantiated parent context to
6879  // find the instantiation of the declaration D.
6880 
6881  // If our context used to be dependent, we may need to instantiate
6882  // it before performing lookup into that context.
6883  bool IsBeingInstantiated = false;
6884  if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
6885  if (!Spec->isDependentContext()) {
6887  const RecordType *Tag = T->getAs<RecordType>();
6888  assert(Tag && "type of non-dependent record is not a RecordType");
6889  if (Tag->isBeingDefined())
6890  IsBeingInstantiated = true;
6891  if (!Tag->isBeingDefined() &&
6892  RequireCompleteType(Loc, T, diag::err_incomplete_type))
6893  return nullptr;
6894 
6895  ParentDC = Tag->getDecl();
6896  }
6897  }
6898 
6899  NamedDecl *Result = nullptr;
6900  // FIXME: If the name is a dependent name, this lookup won't necessarily
6901  // find it. Does that ever matter?
6902  if (auto Name = D->getDeclName()) {
6903  DeclarationNameInfo NameInfo(Name, D->getLocation());
6904  DeclarationNameInfo NewNameInfo =
6905  SubstDeclarationNameInfo(NameInfo, TemplateArgs);
6906  Name = NewNameInfo.getName();
6907  if (!Name)
6908  return nullptr;
6909  DeclContext::lookup_result Found = ParentDC->lookup(Name);
6910 
6911  Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
6912  } else {
6913  // Since we don't have a name for the entity we're looking for,
6914  // our only option is to walk through all of the declarations to
6915  // find that name. This will occur in a few cases:
6916  //
6917  // - anonymous struct/union within a template
6918  // - unnamed class/struct/union/enum within a template
6919  //
6920  // FIXME: Find a better way to find these instantiations!
6921  Result = findInstantiationOf(Context, D,
6922  ParentDC->decls_begin(),
6923  ParentDC->decls_end());
6924  }
6925 
6926  if (!Result) {
6927  if (isa<UsingShadowDecl>(D)) {
6928  // UsingShadowDecls can instantiate to nothing because of using hiding.
6929  } else if (hasUncompilableErrorOccurred()) {
6930  // We've already complained about some ill-formed code, so most likely
6931  // this declaration failed to instantiate. There's no point in
6932  // complaining further, since this is normal in invalid code.
6933  // FIXME: Use more fine-grained 'invalid' tracking for this.
6934  } else if (IsBeingInstantiated) {
6935  // The class in which this member exists is currently being
6936  // instantiated, and we haven't gotten around to instantiating this
6937  // member yet. This can happen when the code uses forward declarations
6938  // of member classes, and introduces ordering dependencies via
6939  // template instantiation.
6940  Diag(Loc, diag::err_member_not_yet_instantiated)
6941  << D->getDeclName()
6942  << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
6943  Diag(D->getLocation(), diag::note_non_instantiated_member_here);
6944  } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
6945  // This enumeration constant was found when the template was defined,
6946  // but can't be found in the instantiation. This can happen if an
6947  // unscoped enumeration member is explicitly specialized.
6948  EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
6949  EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
6950  TemplateArgs));
6951  assert(Spec->getTemplateSpecializationKind() ==
6953  Diag(Loc, diag::err_enumerator_does_not_exist)
6954  << D->getDeclName()
6955  << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
6956  Diag(Spec->getLocation(), diag::note_enum_specialized_here)
6957  << Context.getTypeDeclType(Spec);
6958  } else {
6959  // We should have found something, but didn't.
6960  llvm_unreachable("Unable to find instantiation of declaration!");
6961  }
6962  }
6963 
6964  D = Result;
6965  }
6966 
6967  return D;
6968 }
6969 
6971  SourceLocation PointOfInstantiation,
6972  FunctionDecl *FD,
6973  bool DefinitionRequired,
6974  MangleContext &MC) {
6975  S.InstantiateFunctionDefinition(/*FIXME:*/ PointOfInstantiation, FD, true,
6976  DefinitionRequired, true);
6977  if (!FD->isDefined())
6978  return;
6979  if (S.LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
6980  S.SYCL().ConstructOpenCLKernel(FD, MC);
6981  FD->setInstantiationIsPending(false);
6982 }
6983 
6984 /// Performs template instantiation for all implicit template
6985 /// instantiations we have seen until this point.
6987  std::unique_ptr<MangleContext> MangleCtx(
6988  getASTContext().createMangleContext());
6989  std::deque<PendingImplicitInstantiation> delayedPCHInstantiations;
6990  while (!PendingLocalImplicitInstantiations.empty() ||
6991  (!LocalOnly && !PendingInstantiations.empty())) {
6993 
6994  if (PendingLocalImplicitInstantiations.empty()) {
6995  Inst = PendingInstantiations.front();
6996  PendingInstantiations.pop_front();
6997  } else {
6998  Inst = PendingLocalImplicitInstantiations.front();
7000  }
7001 
7002  // Instantiate function definitions
7003  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
7004  bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
7006  if (Function->isMultiVersion())
7008  Function,
7009  [this, Inst, DefinitionRequired, &MangleCtx](FunctionDecl *CurFD) {
7010  processFunctionInstantiation(*this, Inst.second, CurFD,
7011  DefinitionRequired, *MangleCtx);
7012  });
7013  else
7014  processFunctionInstantiation(*this, Inst.second, Function,
7015  DefinitionRequired, *MangleCtx);
7016  // Definition of a PCH-ed template declaration may be available only in the TU.
7017  if (!LocalOnly && LangOpts.PCHInstantiateTemplates &&
7018  TUKind == TU_Prefix && Function->instantiationIsPending())
7019  delayedPCHInstantiations.push_back(Inst);
7020  continue;
7021  }
7022 
7023  // Instantiate variable definitions
7024  VarDecl *Var = cast<VarDecl>(Inst.first);
7025 
7026  assert((Var->isStaticDataMember() ||
7027  isa<VarTemplateSpecializationDecl>(Var)) &&
7028  "Not a static data member, nor a variable template"
7029  " specialization?");
7030 
7031  // Don't try to instantiate declarations if the most recent redeclaration
7032  // is invalid.
7033  if (Var->getMostRecentDecl()->isInvalidDecl())
7034  continue;
7035 
7036  // Check if the most recent declaration has changed the specialization kind
7037  // and removed the need for implicit instantiation.
7038  switch (Var->getMostRecentDecl()
7040  case TSK_Undeclared:
7041  llvm_unreachable("Cannot instantitiate an undeclared specialization.");
7044  continue; // No longer need to instantiate this type.
7046  // We only need an instantiation if the pending instantiation *is* the
7047  // explicit instantiation.
7048  if (Var != Var->getMostRecentDecl())
7049  continue;
7050  break;
7052  break;
7053  }
7054 
7056  "instantiating variable definition");
7057  bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
7059 
7060  // Instantiate static data member definitions or variable template
7061  // specializations.
7062  InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
7063  DefinitionRequired, true);
7064  }
7065 
7066  if (!LocalOnly && LangOpts.PCHInstantiateTemplates)
7067  PendingInstantiations.swap(delayedPCHInstantiations);
7068 }
7069 
7071  const MultiLevelTemplateArgumentList &TemplateArgs) {
7072  for (auto *DD : Pattern->ddiags()) {
7073  switch (DD->getKind()) {
7075  HandleDependentAccessCheck(*DD, TemplateArgs);
7076  break;
7077  }
7078  }
7079 }
Defines the clang::ASTContext interface.
NodeId Parent
Definition: ASTDiff.cpp:191
StringRef P
static char ID
Definition: Arena.cpp:183
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
llvm::MachO::Record Record
Definition: MachO.h:31
@ ForExternalRedeclaration
The lookup results will be used for redeclaration of a name with external linkage; non-visible lookup...
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
This file declares semantic analysis for CUDA constructs.
SourceLocation Loc
Definition: SemaObjC.cpp:755
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenMP constructs and clauses.
static void instantiateSYCLIntelMaxConcurrencyAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const SYCLIntelMaxConcurrencyAttr *A, Decl *New)
static void instantiateSYCLIntelMaxWorkGroupSizeAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const SYCLIntelMaxWorkGroupSizeAttr *A, Decl *New)
static void instantiateDependentAMDGPUWavesPerEUAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const AMDGPUWavesPerEUAttr &Attr, Decl *New)
static void instantiateDependentAMDGPUMaxNumWorkGroupsAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const AMDGPUMaxNumWorkGroupsAttr &Attr, Decl *New)
static void instantiateDependentAMDGPUFlatWorkGroupSizeAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New)
static void instantiateSYCLDeviceHasAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const SYCLDeviceHasAttr *Attr, Decl *New)
static void instantiateDependentDiagnoseIfAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New)
static QualType adjustFunctionTypeForInstantiation(ASTContext &Context, FunctionDecl *D, TypeSourceInfo *TInfo)
Adjust the given function type for an instantiation of the given declaration, to cope with modificati...
static void instantiateSYCLIntelPipeIOAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const SYCLIntelPipeIOAttr *Attr, Decl *New)
static bool isRelevantAttr(Sema &S, const Decl *D, const Attr *A)
Determine whether the attribute A might be relevant to the declaration D.
static void instantiateSYCLIntelBankBitsAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const SYCLIntelBankBitsAttr *Attr, Decl *New)
static void instantiateSYCLIntelSchedulerTargetFmaxMhzAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const SYCLIntelSchedulerTargetFmaxMhzAttr *A, Decl *New)
static Expr * instantiateDependentFunctionAttrCondition(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New)
static bool isDependentContextAtLevel(DeclContext *DC, unsigned Level)
Determine whether the given context is dependent on template parameters at level Level or below.
static void instantiateSYCLAddIRAttributesGlobalVariableAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const SYCLAddIRAttributesGlobalVariableAttr *A, Decl *New)
static void instantiateSYCLIntelBankWidthAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const SYCLIntelBankWidthAttr *Attr, Decl *New)
static void instantiateDependentModeAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const ModeAttr &Attr, Decl *New)
static void instantiateSYCLIntelLoopFuseAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const SYCLIntelLoopFuseAttr *Attr, Decl *New)
static void instantiateDependentCUDALaunchBoundsAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const CUDALaunchBoundsAttr &Attr, Decl *New)
static bool isDeclWithinFunction(const Decl *D)
static void instantiateDependentAssumeAlignedAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const AssumeAlignedAttr *Aligned, Decl *New)
static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl, const MultiLevelTemplateArgumentList &TemplateArgs)
static void collectUnexpandedParameterPacks(Sema &S, TemplateParameterList *Params, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
static void instantiateSYCLIntelESimdVectorizeAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const SYCLIntelESimdVectorizeAttr *A, Decl *New)
static DeclT * getPreviousDeclForInstantiation(DeclT *D)
Get the previous declaration of a declaration for the purposes of template instantiation.
static void instantiateSYCLWorkGroupSizeHintAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const SYCLWorkGroupSizeHintAttr *A, Decl *New)
static void instantiateSYCLIntelPrivateCopiesAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const SYCLIntelPrivateCopiesAttr *A, Decl *New)
static void instantiateSYCLIntelMaxGlobalWorkDimAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const SYCLIntelMaxGlobalWorkDimAttr *A, Decl *New)
static void instantiateSYCLIntelNumBanksAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const SYCLIntelNumBanksAttr *Attr, Decl *New)
static bool isInstantiationOf(ClassTemplateDecl *Pattern, ClassTemplateDecl *Instance)
static void instantiateDependentHLSLParamModifierAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const HLSLParamModifierAttr *Attr, Decl *New)
static void instantiateDependentAllocAlignAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const AllocAlignAttr *Align, Decl *New)
static void instantiateSYCLIntelNoGlobalWorkOffsetAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const SYCLIntelNoGlobalWorkOffsetAttr *A, Decl *New)
static void instantiateIntelReqdSubGroupSize(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const IntelReqdSubGroupSizeAttr *A, Decl *New)
static void instantiateSYCLAddIRAnnotationsMemberAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const SYCLAddIRAnnotationsMemberAttr *A, Decl *New)
static void processFunctionInstantiation(Sema &S, SourceLocation PointOfInstantiation, FunctionDecl *FD, bool DefinitionRequired, MangleContext &MC)
static void instantiateSYCLAddIRAttributesFunctionAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const SYCLAddIRAttributesFunctionAttr *A, Decl *New)
static bool isInstantiationOfStaticDataMember(VarDecl *Pattern, VarDecl *Instance)
static void instantiateSYCLIntelMaxWorkGroupsPerMultiprocessorAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const SYCLIntelMaxWorkGroupsPerMultiprocessorAttr *A, Decl *New)
static void instantiateOMPDeclareSimdDeclAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const OMPDeclareSimdDeclAttr &Attr, Decl *New)
Instantiation of 'declare simd' attribute and its arguments.
static void instantiateSYCLIntelNumSimdWorkItemsAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const SYCLIntelNumSimdWorkItemsAttr *A, Decl *New)
static void instantiateDependentSYCLKernelAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const SYCLKernelAttr &Attr, Decl *New)
static void instantiateDependentAlignValueAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const AlignValueAttr *Aligned, Decl *New)
static void instantiateDependentAlignedAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion)
static void instantiateOMPDeclareVariantAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const OMPDeclareVariantAttr &Attr, Decl *New)
Instantiation of 'declare variant' attribute and its arguments.
static void instantiateSYCLAddIRAttributesKernelParameterAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const SYCLAddIRAttributesKernelParameterAttr *A, Decl *New)
static void instantiateDependentEnableIfAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New)
static void instantiateSYCLIntelForcePow2DepthAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const SYCLIntelForcePow2DepthAttr *Attr, Decl *New)
static NamedDecl * findInstantiationOf(ASTContext &Ctx, NamedDecl *D, ForwardIterator first, ForwardIterator last)
static void instantiateSYCLIntelMinWorkGroupsPerComputeUnitAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const SYCLIntelMinWorkGroupsPerComputeUnitAttr *A, Decl *New)
static void instantiateSYCLIntelInitiationIntervalAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const SYCLIntelInitiationIntervalAttr *A, Decl *New)
static void instantiateSYCLIntelMaxReplicatesAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const SYCLIntelMaxReplicatesAttr *A, Decl *New)
static void instantiateDependentAnnotationAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const AnnotateAttr *Attr, Decl *New)
static void instantiateSYCLReqdWorkGroupSizeAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const SYCLReqdWorkGroupSizeAttr *A, Decl *New)
static Sema::RetainOwnershipKind attrToRetainOwnershipKind(const Attr *A)
static void instantiateSYCLUsesAspectsAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const SYCLUsesAspectsAttr *Attr, Decl *New)
static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other, ASTContext &Ctx)
static bool isInvalid(LocType Loc, bool *Invalid)
Defines the SourceManager interface.
Defines the clang::TypeLoc interface and its subclasses.
StateNode * Previous
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Definition: ASTConsumer.h:33
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Definition: ASTConsumer.cpp:18
virtual void HandleCXXStaticMemberVarInstantiation(VarDecl *D)
HandleCXXStaticMemberVarInstantiation - Tell the consumer that this.
Definition: ASTConsumer.h:116
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:185
unsigned getManglingNumber(const NamedDecl *ND, bool ForAuxTarget=false) const
TypedefNameDecl * getTypedefNameForUnnamedTagDecl(const TagDecl *TD)
void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern)
Remember that the using decl Inst is an instantiation of the using decl Pattern of a class template.
QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool AllowCXX=false, bool IsConditionalOperator=false)
NamedDecl * getInstantiatedFromUsingDecl(NamedDecl *Inst)
If the given using decl Inst is an instantiation of another (possibly unresolved) using decl,...
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:651
QualType getTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args, QualType Canon=QualType()) const
QualType getRecordType(const RecordDecl *Decl) const
QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const
getInjectedClassNameType - Return the unique reference to the injected class name type for the specif...
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2589
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2605
void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, UsingShadowDecl *Pattern)
unsigned getStaticLocalNumber(const VarDecl *VD) const
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1605
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
void setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst, UsingEnumDecl *Pattern)
Remember that the using enum decl Inst is an instantiation of the using enum decl Pattern of a class ...
CanQualType BoolTy
Definition: ASTContext.h:1095
void setStaticLocalNumber(const VarDecl *VD, unsigned Number)
FieldDecl * getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field)
OMPTraitInfo & getNewOMPTraitInfo()
Return a new OMPTraitInfo object owned by this context.
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType IntTy
Definition: ASTContext.h:1103
void setManglingNumber(const NamedDecl *ND, unsigned Number)
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)
DeclaratorDecl * getDeclaratorForUnnamedTagDecl(const TagDecl *TD)
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1105
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1583
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:760
void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl)
void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND)
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
Represents an access specifier followed by colon ':'.
Definition: DeclCXX.h:86
static AccessSpecDecl * Create(ASTContext &C, AccessSpecifier AS, DeclContext *DC, SourceLocation ASLoc, SourceLocation ColonLoc)
Definition: DeclCXX.h:117
SourceLocation getColonLoc() const
The location of the colon following the access specifier.
Definition: DeclCXX.h:108
SourceLocation getAccessSpecifierLoc() const
The location of the access specifier.
Definition: DeclCXX.h:102
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
Attr - This represents one attribute.
Definition: Attr.h:46
Attr * clone(ASTContext &C) const
attr::Kind getKind() const
Definition: Attr.h:92
SourceLocation getLocation() const
Definition: Attr.h:99
SourceLocation getLoc() const
Represents a C++ declaration that introduces decls from somewhere else.
Definition: DeclCXX.h:3417
shadow_range shadows() const
Definition: DeclCXX.h:3483
A binding in a decomposition declaration.
Definition: DeclCXX.h:4107
static BindingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id)
Definition: DeclCXX.cpp:3336
Represents the builtin template declaration which is used to implement __make_integer_seq and other b...
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2535
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition: DeclCXX.cpp:2753
static CXXConstructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, InheritedConstructor Inherited=InheritedConstructor(), Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2723
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2862
static CXXConversionDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, ExplicitSpecifier ES, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2890
Represents a C++ deduction guide declaration.
Definition: DeclCXX.h:1952
static CXXDeductionGuideDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, SourceLocation EndLocation, CXXConstructorDecl *Ctor=nullptr, DeductionCandidate Kind=DeductionCandidate::Normal)
Definition: DeclCXX.cpp:2157
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2799
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2857
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2186
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2488
static CXXMethodDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, bool isInline, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2274
bool isStatic() const
Definition: DeclCXX.cpp:2186
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2466
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition: DeclCXX.cpp:1564
unsigned getLambdaDependencyKind() const
Definition: DeclCXX.h:1856
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition: DeclCXX.h:1548
TypeSourceInfo * getLambdaTypeInfo() const
Definition: DeclCXX.h:1862
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1022
static CXXRecordDecl * CreateLambda(const ASTContext &C, DeclContext *DC, TypeSourceInfo *Info, SourceLocation Loc, unsigned DependencyKind, bool IsGeneric, LambdaCaptureDefault CaptureDefault)
Definition: DeclCXX.cpp:148
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr, bool DelayTypeCreation=false)
Definition: DeclCXX.cpp:132
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1905
void setInstantiationOfMemberClass(CXXRecordDecl *RD, TemplateSpecializationKind TSK)
Specify that this record is an instantiation of the member class RD.
Definition: DeclCXX.cpp:1888
LambdaCaptureDefault getLambdaCaptureDefault() const
Definition: DeclCXX.h:1063
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:523
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition: DeclCXX.cpp:1901
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:564
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:132
Declaration of a class template.
void AddPartialSpecialization(ClassTemplatePartialSpecializationDecl *D, void *InsertPos)
Insert the specified partial specialization knowing that it is not already in.
ClassTemplateDecl * getMostRecentDecl()
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
Common * getCommonPtr() const
llvm::FoldingSetVector< ClassTemplatePartialSpecializationDecl > & getPartialSpecializations() const
Retrieve the set of partial specializations of this class template.
ClassTemplatePartialSpecializationDecl * findPartialSpecialization(ArrayRef< TemplateArgument > Args, TemplateParameterList *TPL, void *&InsertPos)
Return the partial specialization with the provided arguments if it exists, otherwise return the inse...
static ClassTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a class template node.
ClassTemplatePartialSpecializationDecl * findPartialSpecInstantiatedFromMember(ClassTemplatePartialSpecializationDecl *D)
Find a class template partial specialization which was instantiated from the given member partial spe...
ClassTemplateDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this template.
void AddSpecialization(ClassTemplateSpecializationDecl *D, void *InsertPos)
Insert the specified specialization knowing that it is not already in.
void setCommonPtr(Common *C)
QualType getInjectedClassNameSpecialization()
Retrieve the template specialization type of the injected-class-name for this class template.
ClassTemplateSpecializationDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
void setInstantiatedFromMember(ClassTemplatePartialSpecializationDecl *PartialSpec)
static ClassTemplatePartialSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, QualType CanonInjectedType, ClassTemplatePartialSpecializationDecl *PrevDecl)
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a class template specialization, which refers to a class template with a given set of temp...
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
ClassTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Retrieve the template argument list as written in the sources, if any.
void setExternKeywordLoc(SourceLocation Loc)
Sets the location of the extern keyword.
void setSpecializationKind(TemplateSpecializationKind TSK)
SourceLocation getExternKeywordLoc() const
Gets the location of the extern keyword, if present.
SourceLocation getTemplateKeywordLoc() const
Gets the location of the template keyword, if present.
void setTemplateKeywordLoc(SourceLocation Loc)
Sets the location of the template keyword.
static ClassTemplateSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, ClassTemplateSpecializationDecl *PrevDecl)
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
Declaration of a C++20 concept.
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:421
Represents a shadow constructor declaration introduced into a class by a C++11 using-declaration that...
Definition: DeclCXX.h:3598
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1369
reference front() const
Definition: DeclBase.h:1392
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2191
bool isFileContext() const
Definition: DeclBase.h:2137
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:1993
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1282
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2066
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1802
bool isTranslationUnit() const
Definition: DeclBase.h:2142
bool isRecord() const
Definition: DeclBase.h:2146
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1938
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1716
decl_iterator decls_end() const
Definition: DeclBase.h:2324
ddiag_range ddiags() const
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2322
bool isFunctionOrMethod() const
Definition: DeclBase.h:2118
void addHiddenDecl(Decl *D)
Add the declaration D to this context without modifying any lookup tables.
Definition: DeclBase.cpp:1690
decl_iterator decls_begin() const
Definition: DeclBase.cpp:1572
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition: Expr.cpp:488
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:441
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1216
void addAttr(Attr *A)
Definition: DeclBase.cpp:991
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:599
void setLocalExternDecl()
Changes the namespace of this declaration to reflect that it's a function-local extern declaration.
Definition: DeclBase.h:1141
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition: Decl.cpp:100
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
bool isInIdentifierNamespace(unsigned NS) const
Definition: DeclBase.h:883
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1207
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition: DeclBase.cpp:555
unsigned getTemplateDepth() const
Determine the number of levels of template parameter surrounding this declaration.
Definition: DeclBase.cpp:274
void setObjectOfFriendDecl(bool PerformFriendInjection=false)
Changes the namespace of this declaration to reflect that it's the object of a friend declaration.
Definition: DeclBase.h:1170
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition: DeclBase.h:776
bool isInLocalScopeForInstantiation() const
Determine whether a substitution into this declaration would occur as part of a substitution into a d...
Definition: DeclBase.cpp:376
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1051
DeclContext * getNonTransparentDeclContext()
Return the non transparent context.
Definition: DeclBase.cpp:1165
bool isInvalidDecl() const
Definition: DeclBase.h:594
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition: DeclBase.h:1159
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:508
SourceLocation getLocation() const
Definition: DeclBase.h:445
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:565
const char * getDeclKindName() const
Definition: DeclBase.cpp:123
@ IDNS_Ordinary
Ordinary names.
Definition: DeclBase.h:144
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:908
void setImplicit(bool I=true)
Definition: DeclBase.h:600
void setReferenced(bool R=true)
Definition: DeclBase.h:629
void setIsUsed()
Set whether the declaration is used, in the sense of odr-use.
Definition: DeclBase.h:614
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition: DeclBase.cpp:530
attr_range attrs() const
Definition: DeclBase.h:541
AccessSpecifier getAccess() const
Definition: DeclBase.h:513
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:437
bool hasAttr() const
Definition: DeclBase.h:583
void setNonMemberOperator()
Specifies that this declaration is a C++ overloaded non-member.
Definition: DeclBase.h:1225
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:340
Kind getKind() const
Definition: DeclBase.h:448
T * getAttr() const
Definition: DeclBase.h:579
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:433
DeclContext * getDeclContext()
Definition: DeclBase.h:454
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition: DeclBase.h:860
DeclarationName getCXXDestructorName(CanQualType Ty)
Returns the name of a C++ destructor for the given Type.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
DeclarationName getCXXConstructorName(CanQualType Ty)
Returns the name of a C++ constructor for the given Type.
The name of a declaration.
NameKind getNameKind() const
Determine what kind of name this is.
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:771
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:847
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:814
TemplateParameterList * getTemplateParameterList(unsigned index) const
Definition: Decl.h:863
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1989
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:823
unsigned getNumTemplateParameterLists() const
Definition: Decl.h:859
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:806
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:2001
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:800
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier (with source-location information) that qualifies the name of this...
Definition: Decl.h:837
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:2035
Represents the type decltype(expr) (C++11).
Definition: Type.h:5370
Expr * getUnderlyingExpr() const
Definition: Type.h:5380
A decomposition declaration.
Definition: DeclCXX.h:4166
static DecompositionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation LSquareLoc, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< BindingDecl * > Bindings)
Definition: DeclCXX.cpp:3360
ArrayRef< BindingDecl * > bindings() const
Definition: DeclCXX.h:4198
Provides information about a dependent function-template specialization declaration.
Definition: DeclTemplate.h:689
Represents a qualified type name for which the type name is dependent.
Definition: Type.h:6464
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:879
RAII object that enters a new expression evaluation context.
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3300
Represents an enum.
Definition: Decl.h:3870
enumerator_range enumerators() const
Definition: Decl.h:4003
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4075
bool isScopedUsingClassTag() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4078
EnumDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.h:3951
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition: Decl.cpp:4856
EnumDecl * getDefinition() const
Definition: Decl.h:3973
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:4084
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4030
TypeSourceInfo * getIntegerTypeSourceInfo() const
Return the type source info for the underlying integer type, if no type source info exists,...
Definition: Decl.h:4046
TemplateSpecializationKind getTemplateSpecializationKind() const
If this enumeration is a member of a specialization of a templated class, determine what kind of temp...
Definition: Decl.cpp:4909
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1897
const Expr * getExpr() const
Definition: DeclCXX.h:1906
ExplicitSpecKind getKind() const
Definition: DeclCXX.h:1905
bool isInvalid() const
Determine if the explicit specifier is invalid.
Definition: DeclCXX.h:1926
static ExplicitSpecifier Invalid()
Definition: DeclCXX.h:1937
void setKind(ExplicitSpecKind Kind)
Definition: DeclCXX.h:1930
static ExplicitSpecifier getFromDecl(FunctionDecl *Function)
Definition: DeclCXX.cpp:2144
This represents one expression.
Definition: Expr.h:110
static bool isPotentialConstantExprUnevaluated(Expr *E, const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExprUnevaluated - Return true if this expression might be usable in a constant exp...
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
bool isConstantInitializer(ASTContext &Ctx, bool ForRef, const Expr **Culprit=nullptr) const
isConstantInitializer - Returns true if this expression can be emitted to IR as a constant,...
Definition: Expr.cpp:3339
QualType getType() const
Definition: Expr.h:142
Declaration context for names declared as extern "C" in C++.
Definition: Decl.h:222
Represents difference between two FPOptions values.
Definition: LangOptions.h:956
Represents a member of a struct/union/class.
Definition: Decl.h:3060
bool isMutable() const
Determines whether this field is mutable (C++ only).
Definition: Decl.h:3148
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition: Decl.h:3215
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition: Decl.h:3164
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition: DeclFriend.h:54
NamedDecl * getFriendDecl() const
If this friend declaration doesn't name a type, return the inner declaration.
Definition: DeclFriend.h:137
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, ArrayRef< TemplateParameterList * > FriendTypeTPLists=std::nullopt)
Definition: DeclFriend.cpp:34
bool isUnsupportedFriend() const
Determines if this friend kind is unsupported.
Definition: DeclFriend.h:173
SourceLocation getFriendLoc() const
Retrieves the location of the 'friend' keyword.
Definition: DeclFriend.h:142
void setUnsupportedFriend(bool Unsupported)
Definition: DeclFriend.h:176
TypeSourceInfo * getFriendType() const
If this friend declaration names an (untemplated but possibly dependent) type, return the type; other...
Definition: DeclFriend.h:122
Declaration of a friend template.
static DefaultedOrDeletedFunctionInfo * Create(ASTContext &Context, ArrayRef< DeclAccessPair > Lookups, StringLiteral *DeletedMessage=nullptr)
Definition: Decl.cpp:3100
Represents a function declaration or definition.
Definition: Decl.h:1972
void setInstantiationIsPending(bool IC)
State that the instantiation of this function is pending.
Definition: Decl.h:2478
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:3240
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2441
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition: Decl.cpp:4051
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4046
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:2286
void setDefaultedOrDeletedInfo(DefaultedOrDeletedFunctionInfo *Info)
Definition: Decl.cpp:3121
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2833
bool UsesFPIntrin() const
Determine whether the function was declared in source context that requires constrained FP intrinsics...
Definition: Decl.h:2821
void setInstantiationOfMemberFunction(FunctionDecl *FD, TemplateSpecializationKind TSK)
Specify that this record is an instantiation of the member function FD.
Definition: Decl.h:2886
QualType getReturnType() const
Definition: Decl.h:2757
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition: Decl.h:2354
bool hasWrittenPrototype() const
Whether this function has a written prototype.
Definition: Decl.h:2413
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3621
DependentFunctionTemplateSpecializationInfo * getDependentSpecializationInfo() const
Definition: Decl.cpp:4241
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2505
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:2800
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function.
Definition: Decl.cpp:4376
bool FriendConstraintRefersToEnclosingTemplate() const
Definition: Decl.h:2620
StringLiteral * getDeletedMessage() const
Get the message that indicates why this function was deleted.
Definition: Decl.h:2670
bool isDeletedAsWritten() const
Definition: Decl.h:2509
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition: Decl.h:2325
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, Expr *TrailingRequiresClause=nullptr)
Definition: Decl.h:2161
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition: Decl.h:2329
void setVirtualAsWritten(bool V)
State that this function is marked as virtual explicitly.
Definition: Decl.h:2321
bool hasSkippedBody() const
True if the function was a definition but its body was skipped.
Definition: Decl.h:2592
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition: Decl.h:2828
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition: Decl.cpp:3184
void setRangeEnd(SourceLocation E)
Definition: Decl.h:2190
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2350
void setIneligibleOrNotSelected(bool II)
Definition: Decl.h:2386
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4399
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2686
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition: Decl.h:2316
void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template, TemplateArgumentList *TemplateArgs, void *InsertPos, TemplateSpecializationKind TSK=TSK_ImplicitInstantiation, TemplateArgumentListInfo *TemplateArgsAsWritten=nullptr, SourceLocation PointOfInstantiation=SourceLocation())
Specify that this function declaration is actually a function template specialization.
Definition: Decl.h:2986
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3696
DeclarationNameInfo getNameInfo() const
Definition: Decl.h:2183
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition: Decl.h:2254
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition: Decl.cpp:3207
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition: Decl.h:2811
DefaultedOrDeletedFunctionInfo * getDefalutedOrDeletedInfo() const
Definition: Decl.cpp:3155
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition: Decl.h:2717
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2598
const ASTTemplateArgumentListInfo * getTemplateSpecializationArgsAsWritten() const
Retrieve the template argument list as written in the sources, if any.
Definition: Decl.cpp:4192
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2709
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4668
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:4908
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:4927
FunctionDecl * getExceptionSpecTemplate() const
If this function type has an uninstantiated exception specification, this is the function whose excep...
Definition: Type.h:5006
QualType getParamType(unsigned i) const
Definition: Type.h:4903
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:4933
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4912
Declaration of a template function.
Definition: DeclTemplate.h:957
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
FunctionDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
FunctionTemplateDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this template.
static FunctionTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
FunctionTemplateDecl * getPreviousDecl()
Retrieve the previous declaration of this function template, or nullptr if no such declaration exists...
FunctionTemplateDecl * getInstantiatedFromMemberTemplate() const
void setParam(unsigned i, ParmVarDecl *VD)
Definition: TypeLoc.h:1507
ParmVarDecl * getParam(unsigned i) const
Definition: TypeLoc.h:1506
ExtInfo getExtInfo() const
Definition: Type.h:4597
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition: Type.h:4593
QualType getReturnType() const
Definition: Type.h:4585
HLSLBufferDecl - Represent a cbuffer or tbuffer declaration.
Definition: Decl.h:4943
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3344
ArrayRef< NamedDecl * > chain() const
Definition: Decl.h:3366
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id, QualType T, llvm::MutableArrayRef< NamedDecl * > CH)
Definition: Decl.cpp:5485
unsigned getChainingSize() const
Definition: Decl.h:3372
Description of a constructor that was inherited from a base class.
Definition: DeclCXX.h:2506
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:514
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:1032
Represents the declaration of a label.
Definition: Decl.h:500
static LabelDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II)
Definition: Decl.cpp:5343
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:365
LocalInstantiationScope * cloneScopes(LocalInstantiationScope *Outermost)
Clone this scope, and all outer scopes, down to the given outermost scope.
Definition: Template.h:458
void InstantiatedLocal(const Decl *D, Decl *Inst)
llvm::PointerUnion< Decl *, DeclArgumentPack * > * findInstantiationOf(const Decl *D)
Find the instantiation of the declaration D within the current instantiation scope.
Represents the results of name lookup.
Definition: Lookup.h:46
A global _GUID constant.
Definition: DeclCXX.h:4289
An instance of this class represents the declaration of a property member.
Definition: DeclCXX.h:4235
static MSPropertyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName N, QualType T, TypeSourceInfo *TInfo, SourceLocation StartL, IdentifierInfo *Getter, IdentifierInfo *Setter)
Definition: DeclCXX.cpp:3401
IdentifierInfo * getSetterId() const
Definition: DeclCXX.h:4259
IdentifierInfo * getGetterId() const
Definition: DeclCXX.h:4257
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition: Mangle.h:45
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:615
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:76
const ArgList & getInnermost() const
Retrieve the innermost template argument list.
Definition: Template.h:265
void addOuterTemplateArguments(Decl *AssociatedDecl, ArgList Args, bool Final)
Add a new outmost level to the multi-level template argument list.
Definition: Template.h:210
unsigned getNumLevels() const
Determine the number of levels in this template argument list.
Definition: Template.h:123
void setKind(TemplateSubstitutionKind K)
Definition: Template.h:109
unsigned getNumSubstitutedLevels() const
Determine the number of substituted levels in this template argument list.
Definition: Template.h:129
void addOuterRetainedLevels(unsigned Num)
Definition: Template.h:260
unsigned getNumRetainedOuterLevels() const
Definition: Template.h:139
This represents a decl that may have a name.
Definition: Decl.h:249
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1931
void setDeclName(DeclarationName N)
Set the name of this declaration.
Definition: Decl.h:318
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:373
Represents a C++ namespace alias.
Definition: DeclCXX.h:3120
static NamespaceAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Namespace)
Definition: DeclCXX.cpp:3038
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier that qualifies the name of the namespace, with source-location inf...
Definition: DeclCXX.h:3183
SourceLocation getAliasLoc() const
Returns the location of the alias name, i.e.
Definition: DeclCXX.h:3205
SourceLocation getNamespaceLoc() const
Returns the location of the namespace keyword.
Definition: DeclCXX.h:3208
SourceLocation getTargetNameLoc() const
Returns the location of the identifier in the named namespace.
Definition: DeclCXX.h:3211
NamespaceDecl * getNamespace()
Retrieve the namespace declaration aliased by this directive.
Definition: DeclCXX.h:3192
Represent a C++ namespace.
Definition: Decl.h:548
A C++ nested-name-specifier augmented with source location information.
bool hasQualifier() const
Evaluates true when this nested-name-specifier location is non-empty.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
bool defaultArgumentWasInherited() const
Determines whether the default argument was inherited from a previous declaration of this template.
unsigned getNumExpansionTypes() const
Retrieves the number of expansion types in an expanded parameter pack.
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
bool isExpandedParameterPack() const
Whether this parameter is a non-type template parameter pack that has a known list of different types...
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, unsigned D, unsigned P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
bool isParameterPack() const
Whether this parameter is a non-type template parameter pack.
TypeSourceInfo * getExpansionTypeSourceInfo(unsigned I) const
Retrieve a particular expansion type source info within an expanded parameter pack.
unsigned getDepth() const
Get the nesting depth of the template parameter.
Expr * getPlaceholderTypeConstraint() const
Return the constraint introduced by the placeholder type of this non-type template parameter (if any)...
void setDefaultArgument(const ASTContext &C, const TemplateArgumentLoc &DefArg)
Set the default argument for this template parameter, and whether that default argument was inherited...
This represents '#pragma omp allocate ...' directive.
Definition: DeclOpenMP.h:474
varlist_range varlists()
Definition: DeclOpenMP.h:516
clauselist_range clauselists()
Definition: DeclOpenMP.h:527
Pseudo declaration for capturing expressions.
Definition: DeclOpenMP.h:383
This is a basic class for representing single OpenMP clause.
Definition: OpenMPClause.h:55
This represents '#pragma omp declare mapper ...' directive.
Definition: DeclOpenMP.h:287
OMPDeclareMapperDecl * getPrevDeclInScope()
Get reference to previous declare mapper construct in the same scope with the same name.
Definition: DeclOpenMP.cpp:160
clauselist_iterator clauselist_begin()
Definition: DeclOpenMP.h:339
clauselist_range clauselists()
Definition: DeclOpenMP.h:333
DeclarationName getVarName()
Get the name of the variable declared in the mapper.
Definition: DeclOpenMP.h:359
Expr * getMapperVarRef()
Get the variable declared in the mapper.
Definition: DeclOpenMP.h:349
This represents '#pragma omp declare reduction ...' directive.
Definition: DeclOpenMP.h:177
Expr * getInitOrig()
Get Orig variable of the initializer.
Definition: DeclOpenMP.h:246
Expr * getCombinerOut()
Get Out variable of the combiner.
Definition: DeclOpenMP.h:226
Expr * getCombinerIn()
Get In variable of the combiner.
Definition: DeclOpenMP.h:223
Expr * getInitializer()
Get initializer expression (if specified) of the declare reduction construct.
Definition: DeclOpenMP.h:238
Expr * getInitPriv()
Get Priv variable of the initializer.
Definition: DeclOpenMP.h:249
OMPDeclareReductionDecl * getPrevDeclInScope()
Get reference to previous declare reduction construct in the same scope with the same name.
Definition: DeclOpenMP.cpp:128
OMPDeclareReductionInitKind getInitializerKind() const
Get initializer kind.
Definition: DeclOpenMP.h:241
Expr * getCombiner()
Get combiner expression of the declare reduction construct.
Definition: DeclOpenMP.h:220
This represents '#pragma omp requires...' directive.
Definition: DeclOpenMP.h:417
This represents '#pragma omp threadprivate ...' directive.
Definition: DeclOpenMP.h:110
varlist_range varlists()
Definition: DeclOpenMP.h:146
Helper data structure representing the traits in a match clause of an declare variant or metadirectiv...
bool anyScoreOrCondition(llvm::function_ref< bool(Expr *&, bool)> Cond)
Represents a field declaration created by an @defs(...).
Definition: DeclObjC.h:2028
Wrapper for void* pointer.
Definition: Ownership.h:50
PtrTy get() const
Definition: Ownership.h:80
static OpaquePtr make(QualType P)
Definition: Ownership.h:60
SourceLocation getEllipsisLoc() const
Definition: TypeLoc.h:2578
TypeLoc getPatternLoc() const
Definition: TypeLoc.h:2594
Represents a pack expansion of types.
Definition: Type.h:6581
std::optional< unsigned > getNumExpansions() const
Retrieve the number of expansions that this pack expansion will generate, if known.
Definition: Type.h:6606
Represents a parameter to a function.
Definition: Decl.h:1762
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1895
Represents a #pragma comment line.
Definition: Decl.h:142
Represents a #pragma detect_mismatch line.
Definition: Decl.h:176
PrettyDeclStackTraceEntry - If a crash occurs in the parser while parsing something related to a decl...
A (possibly-)qualified type.
Definition: Type.h:940
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1007
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:7572
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7444
The collection of all-type qualifiers we support.
Definition: Type.h:318
Represents a struct/union/class.
Definition: Decl.h:4171
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition: Decl.cpp:5039
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition: Decl.h:4223
Wrapper for source info for record types.
Definition: TypeLoc.h:741
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5561
RecordDecl * getDecl() const
Definition: Type.h:5571
bool isMemberSpecialization() const
Determines whether this template was a specialization of a member template.
Definition: DeclTemplate.h:860
void setInstantiatedFromMemberTemplate(RedeclarableTemplateDecl *TD)
Definition: DeclTemplate.h:911
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:226
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:216
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:4997
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:204
Represents the body of a requires-expression.
Definition: DeclCXX.h:2029
static RequiresExprBodyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc)
Definition: DeclCXX.cpp:2174
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:57
Sema & SemaRef
Definition: SemaBase.h:40
void checkAllowedInitializer(VarDecl *VD)
Definition: SemaCUDA.cpp:733
bool inferObjCARCLifetime(ValueDecl *decl)
DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid)
Called at the end of '#pragma omp declare reduction'.
void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner)
Finish current declare reduction construct initializer.
ExprResult ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S, QualType MapperType, SourceLocation StartLoc, DeclarationName VN)
Build the mapper variable of '#pragma omp declare mapper'.
VarDecl * ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D)
Initialize declare reduction construct initializer.
QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, TypeResult ParsedType)
Check if the specified type is allowed to be used in 'omp declare reduction' construct.
DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc, ArrayRef< Expr * > VarList, ArrayRef< OMPClause * > Clauses, DeclContext *Owner=nullptr)
Called on well-formed '#pragma omp allocate'.
OMPClause * ActOnOpenMPAllocatorClause(Expr *Allocator, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc)
Called on well-formed 'allocator' clause.
void EndOpenMPDSABlock(Stmt *CurDirective)
Called on end of data sharing attribute block.
QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, TypeResult ParsedType)
Check if the specified type is allowed to be used in 'omp declare mapper' construct.
OMPClause * ActOnOpenMPMapClause(Expr *IteratorModifier, ArrayRef< OpenMPMapModifierKind > MapTypeModifiers, ArrayRef< SourceLocation > MapTypeModifiersLoc, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef< Expr * > VarList, const OMPVarListLocTy &Locs, bool NoDiagnose=false, ArrayRef< Expr * > UnresolvedMappers=std::nullopt)
Called on well-formed 'map' clause.
std::optional< std::pair< FunctionDecl *, Expr * > > checkOpenMPDeclareVariantFunction(DeclGroupPtrTy DG, Expr *VariantRef, OMPTraitInfo &TI, unsigned NumAppendArgs, SourceRange SR)
Checks '#pragma omp declare variant' variant function and original functions after parsing of the ass...
DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(Scope *S, DeclContext *DC, DeclarationName Name, ArrayRef< std::pair< QualType, SourceLocation >> ReductionTypes, AccessSpecifier AS, Decl *PrevDeclInScope=nullptr)
Called on start of '#pragma omp declare reduction'.
void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D)
Initialize declare reduction construct initializer.
void StartOpenMPDSABlock(OpenMPDirectiveKind K, const DeclarationNameInfo &DirName, Scope *CurScope, SourceLocation Loc)
Called on start of new data sharing attribute block.
OMPThreadPrivateDecl * CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef< Expr * > VarList)
Builds a new OpenMPThreadPrivateDecl and checks its correctness.
void ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI, ArrayRef< Expr * > AdjustArgsNothing, ArrayRef< Expr * > AdjustArgsNeedDevicePtr, ArrayRef< OMPInteropInfo > AppendArgs, SourceLocation AdjustArgsLoc, SourceLocation AppendArgsLoc, SourceRange SR)
Called on well-formed '#pragma omp declare variant' after parsing of the associated method/function.
void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, VarDecl *OmpPrivParm)
Finish current declare reduction construct initializer.
DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, ArrayRef< Expr * > Uniforms, ArrayRef< Expr * > Aligneds, ArrayRef< Expr * > Alignments, ArrayRef< Expr * > Linears, ArrayRef< unsigned > LinModifiers, ArrayRef< Expr * > Steps, SourceRange SR)
Called on well-formed '#pragma omp declare simd' after parsing of the associated method/function.
OMPClause * ActOnOpenMPAlignClause(Expr *Alignment, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc)
Called on well-formed 'align' clause.
DeclGroupPtrTy ActOnOpenMPDeclareMapperDirective(Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, Expr *MapperVarRef, ArrayRef< OMPClause * > Clauses, Decl *PrevDeclInScope=nullptr)
Called on start of '#pragma omp declare mapper'.
static bool isTypeDecoratedWithDeclAttribute(QualType Ty)
Definition: SemaSYCL.h:363
void ConstructOpenCLKernel(FunctionDecl *KernelCallerFunc, MangleContext &MC)
Definition: SemaSYCL.cpp:4949
void addSyclVarDecl(VarDecl *VD)
Definition: SemaSYCL.h:291
RAII object used to change the argument pack substitution index within a Sema object.
Definition: Sema.h:10425
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:6674
A RAII object to temporarily push a declaration context.
Definition: Sema.h:2558
CXXSpecialMemberKind asSpecialMember() const
Definition: Sema.h:4852
A helper class for building up ExtParameterInfos.
Definition: Sema.h:9874
Records and restores the CurFPFeatures state on entry/exit of compound statements.
Definition: Sema.h:10676
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition: Sema.h:9649
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:462
void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI, RetainOwnershipKind K, bool IsTemplateInstantiation)
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl)
VarTemplateSpecializationDecl * BuildVarTemplateInstantiation(VarTemplateDecl *VarTemplate, VarDecl *FromVar, const TemplateArgumentList *PartialSpecArgs, const TemplateArgumentListInfo &TemplateArgsInfo, SmallVectorImpl< TemplateArgument > &Converted, SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *StartingScope=nullptr)
bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC, const MultiLevelTemplateArgumentList &TemplateArgs, bool EvaluateConstraint)
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument >> Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
SemaObjC & ObjC()
Definition: Sema.h:1012
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition: Sema.h:10359
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:9903
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, SourceLocation NameLoc, const LookupResult *R=nullptr, const UsingDecl *UD=nullptr)
Checks that the given nested-name qualifier used in a using decl in the current context is appropriat...
DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD)
Determine the kind of defaulting that would be done for a given function.
bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef< UnexpandedParameterPack > Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand, bool &RetainExpansion, std::optional< unsigned > &NumExpansions)
Determine whether we could expand a pack expansion with the given set of parameter packs into separat...
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:7487
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition: Sema.h:7514
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition: Sema.h:7519
Decl * ActOnSkippedFunctionBody(Decl *Decl)
Definition: SemaDecl.cpp:16036
Decl * BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc, bool Failed)
TemplateName SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, SourceLocation Loc, const MultiLevelTemplateArgumentList &TemplateArgs)
ParmVarDecl * SubstParmVarDecl(ParmVarDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, int indexAdjustment, std::optional< unsigned > NumExpansions, bool ExpectParameterPack, bool EvaluateConstraints=true)
void AddSYCLIntelMaxConcurrencyAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
AddSYCLIntelMaxConcurrencyAttr - Adds a max_concurrency attribute to a particular declaration.
ArrayRef< sema::FunctionScopeInfo * > getFunctionScopes() const
Definition: Sema.h:8908
NamedDecl * FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, bool FindingInstantiatedContext=false)
Find the instantiation of the given declaration within the current instantiation.
MemInitResult BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, Expr *Init, CXXRecordDecl *ClassDecl, SourceLocation EllipsisLoc)
RetainOwnershipKind
Definition: Sema.h:3697
void AddSYCLIntelMaxReplicatesAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name, bool InInstantiation=false)
AddModeAttr - Adds a mode attribute to a particular declaration.
AccessResult CheckFriendAccess(NamedDecl *D)
Checks access to the target of a friend declaration.
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition: Sema.h:824
bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain=true)
Determine whether we would be unable to instantiate this template (because it either has no definitio...
void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, FunctionDecl *Function)
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
void CheckOverrideControl(NamedDecl *D)
CheckOverrideControl - Check C++11 override control semantics.
void AddSYCLIntelMaxWorkGroupsPerMultiprocessorAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
llvm::DenseSet< std::pair< Decl *, unsigned > > InstantiatingSpecializations
Specializations whose definitions are currently being instantiated.
Definition: Sema.h:10362
void deduceOpenCLAddressSpace(ValueDecl *decl)
Definition: SemaDecl.cpp:7007
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition: Sema.h:1448
FunctionDecl * InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc, CodeSynthesisContext::SynthesisKind CSC=CodeSynthesisContext::ExplicitTemplateArgumentSubstitution)
Instantiate (or find existing instantiation of) a function template with a given set of template argu...
void AddSYCLUsesAspectsAttr(Decl *D, const AttributeCommonInfo &CI, Expr **Exprs, unsigned Size)
bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec)
tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
ExprResult SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs, bool CXXDirectInit)
MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init, SourceLocation IdLoc)
UsingShadowDecl * BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD, NamedDecl *Target, UsingShadowDecl *PrevDecl)
Builds a shadow declaration corresponding to a 'using' declaration.
void CheckThreadLocalForLargeAlignment(VarDecl *VD)
Definition: SemaDecl.cpp:14831
void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args)
LateParsedTemplateMapT LateParsedTemplateMap
Definition: Sema.h:8916
bool SubstExprs(ArrayRef< Expr * > Exprs, bool IsCall, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl< Expr * > &Outputs)
Substitute the given template arguments into a list of expressions, expanding pack expansions if requ...
void CheckTemplatePartialSpecialization(ClassTemplatePartialSpecializationDecl *Partial)
StmtResult SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs)
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:15333
ASTContext & Context
Definition: Sema.h:857
bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, TemplateDecl *PrimaryTemplate, unsigned NumExplicitArgs, ArrayRef< TemplateArgument > Args)
Check the non-type template arguments of a class template partial specialization according to C++ [te...
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
TypeSourceInfo * CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, std::optional< unsigned > NumExpansions)
Construct a pack expansion type from the pattern of the pack expansion.
void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *MaxThreads, Expr *MinBlocks, Expr *MaxBlocks)
AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular declaration.
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition: SemaDecl.cpp:69
void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max)
addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a particular declaration.
void InstantiateMemInitializers(CXXConstructorDecl *New, const CXXConstructorDecl *Tmpl, const MultiLevelTemplateArgumentList &TemplateArgs)
void CleanupVarDeclMarking()
Definition: SemaExpr.cpp:19543
void AddSYCLWorkGroupSizeHintAttr(Decl *D, const AttributeCommonInfo &CI, Expr *XDim, Expr *YDim, Expr *ZDim)
TypeSourceInfo * SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST=false)
Perform substitution on the type T with a given set of template arguments.
void AddSYCLDeviceHasAttr(Decl *D, const AttributeCommonInfo &CI, Expr **Exprs, unsigned Size)
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given variable from its template.
void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord)
Add gsl::Pointer attribute to std::container::iterator.
Definition: SemaAttr.cpp:111
NamedDecl * BuildUsingDeclaration(Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList, bool IsInstantiation, bool IsUsingIfExists)
Builds a using declaration.
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:774
bool SubstTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Outputs)
void HandleDependentAccessCheck(const DependentDiagnostic &DD, const MultiLevelTemplateArgumentList &TemplateArgs)
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition: Sema.h:9368
void AddSYCLIntelBankWidthAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend=false)
Perform semantic analysis for the given function template specialization.
void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI, ParameterABI ABI)
void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc)
NamedReturnInfo getNamedReturnInfo(Expr *&E, SimplerImplicitMoveMode Mode=SimplerImplicitMoveMode::Normal)
Determine whether the given expression might be move-eligible or copy-elidable in either a (co_)retur...
Definition: SemaStmt.cpp:3280
bool CheckEnumUnderlyingType(TypeSourceInfo *TI)
Check that this is a valid underlying type for an enum declaration.
Definition: SemaDecl.cpp:17053
void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
void AddSYCLReqdWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI, Expr *XDim, Expr *YDim, Expr *ZDim)
void CheckAlignasUnderalignment(Decl *D)
void * OpaqueParser
Definition: Sema.h:904
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument.
void AddSYCLAddIRAnnotationsMemberAttr(Decl *D, const AttributeCommonInfo &CI, MutableArrayRef< Expr * > Args)
void AddSYCLIntelPrivateCopiesAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
const LangOptions & LangOpts
Definition: Sema.h:855
void InstantiateClassMembers(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK)
Instantiates the definitions of all of the member of the given class, which is an instantiation of a ...
const LangOptions & getLangOpts() const
Definition: Sema.h:519
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted, bool UpdateArgsWithConversions=true, bool *ConstraintsNotSatisfied=nullptr, bool PartialOrderingTTP=false)
Check that the given template arguments can be provided to the given template, converting the argumen...
void PerformPendingInstantiations(bool LocalOnly=false)
Performs template instantiation for all implicit template instantiations we have seen until this poin...
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
Definition: SemaDecl.cpp:15521
VarTemplateSpecializationDecl * CompleteVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiates a variable template specialization by completing it with appropriate type information an...
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization, bool DeclIsDefn)
Perform semantic checking of a new function declaration.
Definition: SemaDecl.cpp:12083
FieldDecl * CheckFieldDecl(DeclarationName Name, QualType T, TypeSourceInfo *TInfo, RecordDecl *Record, SourceLocation Loc, bool Mutable, Expr *BitfieldWidth, InClassInitStyle InitStyle, SourceLocation TSSL, AccessSpecifier AS, NamedDecl *PrevDecl, Declarator *D=nullptr)
Build a new FieldDecl and check its well-formedness.
Definition: SemaDecl.cpp:18707
void updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst)
Update instantiation attributes after template was late parsed.
bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange)
Mark the given method pure.
void InstantiateVariableInitializer(VarDecl *Var, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiate the initializer of a variable.
void AddSYCLIntelNumBanksAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
SmallVector< PendingImplicitInstantiation, 1 > LateParsedInstantiations
Queue of implicit template instantiations that cannot be performed eagerly.
Definition: Sema.h:10637
DeclarationNameInfo SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, const MultiLevelTemplateArgumentList &TemplateArgs)
Do template substitution on declaration name info.
std::vector< std::unique_ptr< TemplateInstantiationCallback > > TemplateInstCallbacks
The template instantiation callbacks to trace or track instantiations (objects can be chained).
Definition: Sema.h:10411
const VarDecl * getCopyElisionCandidate(NamedReturnInfo &Info, QualType ReturnType)
Updates given NamedReturnInfo's move-eligible and copy-elidable statuses, considering the function re...
Definition: SemaStmt.cpp:3375
void AddSYCLIntelSchedulerTargetFmaxMhzAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L, CXXScopeSpec *SS=nullptr)
Require that the EnumDecl is completed with its enumerators defined or instantiated.
bool usesPartialOrExplicitSpecialization(SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec)
std::optional< unsigned > getNumArgumentsInExpansion(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs)
Determine the number of arguments in the given pack expansion type.
ExplicitSpecifier instantiateExplicitSpecifier(const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES)
bool SubstParmTypes(SourceLocation Loc, ArrayRef< ParmVarDecl * > Params, const FunctionProtoType::ExtParameterInfo *ExtParamInfos, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl< QualType > &ParamTypes, SmallVectorImpl< ParmVarDecl * > *OutParams, ExtParameterInfoBuilder &ParamInfos)
Substitute the given template arguments into the given set of parameters, producing the set of parame...
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous)
Perform semantic checking on a newly-created variable declaration.
Definition: SemaDecl.cpp:9050
int ArgumentPackSubstitutionIndex
The current index into pack expansion arguments that will be used for substitution of parameter packs...
Definition: Sema.h:10419
void AddIntelReqdSubGroupSize(Decl *D, const AttributeCommonInfo &CI, Expr *E)
bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target, const LookupResult &PreviousDecls, UsingShadowDecl *&PrevShadow)
Determines whether to create a using shadow decl for a particular decl, given the set of decls existi...
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition: Sema.cpp:2428
bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI, const Expr *E, StringRef &Str, SourceLocation *ArgLocation=nullptr)
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:995
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition: Sema.h:10650
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
SemaSYCL & SYCL()
Definition: Sema.h:1037
void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T)
Mark all of the declarations referenced within a particular AST node as referenced.
Definition: SemaExpr.cpp:20004
SourceManager & getSourceManager() const
Definition: Sema.h:524
void AddSYCLIntelNoGlobalWorkOffsetAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind ActOnExplicitInstantiationNewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew)
Diagnose cases where we have an explicit template specialization before/after an explicit template in...
void AddSYCLAddIRAttributesKernelParameterAttr(Decl *D, const AttributeCommonInfo &CI, MutableArrayRef< Expr * > Args)
void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, Expr *OE)
AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular declaration.
void AddSYCLIntelMaxGlobalWorkDimAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
FunctionDecl * SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, FunctionDecl *Spaceship)
Substitute the name and return type of a defaulted 'operator<=>' to form an implicit 'operator=='.
void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef< Decl * > Elements, Scope *S, const ParsedAttributesView &Attr)
Definition: SemaDecl.cpp:20218
Decl * SubstDecl(Decl *D, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs)
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
void AddSYCLIntelForcePow2DepthAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, SourceLocation Loc)
Check that the type of a non-type template parameter is well-formed.
QualType CheckTemplateIdType(TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body)
Definition: SemaDecl.cpp:16046
void keepInLifetimeExtendingContext()
keepInLifetimeExtendingContext - Pull down InLifetimeExtendingContext flag from previous context.
Definition: Sema.h:6463
void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc, ArrayRef< CXXCtorInitializer * > MemInits, bool AnyErrors)
ActOnMemInitializers - Handle the member initializers for a constructor.
TemplateParameterList * SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs, bool EvaluateConstraints=true)
void AddSYCLIntelBankBitsAttr(Decl *D, const AttributeCommonInfo &CI, Expr **Exprs, unsigned Size)
void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor)
Build an exception spec for destructors that don't have one.
bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain=true)
Instantiate the definition of a class from a given pattern.
void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor)
In the MS ABI, we need to instantiate default arguments of dllexported default constructors along wit...
RedeclarationKind forRedeclarationInCurContext() const
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, ConceptDecl *NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
bool SubstTemplateArgument(const TemplateArgumentLoc &Input, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentLoc &Output, SourceLocation Loc={}, const DeclarationName &Entity={})
void AddSYCLAddIRAttributesGlobalVariableAttr(Decl *D, const AttributeCommonInfo &CI, MutableArrayRef< Expr * > Args)
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, bool HasTypenameKeyword, const CXXScopeSpec &SS, SourceLocation NameLoc, const LookupResult &Previous)
Checks that the given using declaration is not an invalid redeclaration.
bool SubstDefaultArgument(SourceLocation Loc, ParmVarDecl *Param, const MultiLevelTemplateArgumentList &TemplateArgs, bool ForCallExpr=false)
Substitute the given template arguments into the default argument.
void InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
ASTContext & getASTContext() const
Definition: Sema.h:526
EnumConstantDecl * CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val)
Definition: SemaDecl.cpp:19756
ASTConsumer & Consumer
Definition: Sema.h:858
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D)
Definition: SemaDecl.cpp:2107
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition: Sema.cpp:1670
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition: Sema.h:10633
void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max)
addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size attribute to a particular declar...
bool CheckInheritingConstructorUsingDecl(UsingDecl *UD)
Additional checks for a using declaration referring to a constructor name.
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
void addAMDGPUMaxNumWorkGroupsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *XExpr, Expr *YExpr, Expr *ZExpr)
addAMDGPUMaxNumWorkGroupsAttr - Adds an amdgpu_max_num_work_groups attribute to a particular declarat...
void CheckStaticLocalForDllExport(VarDecl *VD)
Check if VD needs to be dllexport/dllimport due to being in a dllexport/import function.
Definition: SemaDecl.cpp:14794
NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs)
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:8923
LateTemplateParserCB * LateTemplateParser
Definition: Sema.h:902
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo, SourceLocation OpLoc, SourceRange R)
Definition: SemaExpr.cpp:4814
NamedDecl * BuildUsingPackDecl(NamedDecl *InstantiatedFrom, ArrayRef< NamedDecl * > Expansions)
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc, StringLiteral *Message=nullptr)
FPOptions CurFPFeatures
Definition: Sema.h:853
NamespaceDecl * getStdNamespace() const
void AddSYCLIntelESimdVectorizeAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
Definition: SemaDecl.cpp:7380
@ TPC_ClassTemplate
Definition: Sema.h:9097
@ TPC_FriendFunctionTemplate
Definition: Sema.h:9102
@ TPC_FriendFunctionTemplateDefinition
Definition: Sema.h:9103
void DiagnoseUnusedDecl(const NamedDecl *ND)
Definition: SemaDecl.cpp:2125
void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, bool IsPackExpansion)
AddAlignedAttr - Adds an aligned attribute to a particular declaration.
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
Definition: SemaDecl.cpp:1609
SemaOpenMP & OpenMP()
Definition: Sema.h:1022
void ActOnUninitializedDecl(Decl *dcl)
Definition: SemaDecl.cpp:14109
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:13539
void AddSYCLAddIRAttributesFunctionAttr(Decl *D, const AttributeCommonInfo &CI, MutableArrayRef< Expr * > Args)
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:553
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
Definition: SemaExpr.cpp:18001
void BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs, LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner, LocalInstantiationScope *StartingScope, bool InstantiatingVarTemplate=false, VarTemplateSpecializationDecl *PrevVTSD=nullptr)
BuildVariableInstantiation - Used after a new variable has been created.
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
void AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Annot, MutableArrayRef< Expr * > Args)
AddAnnotationAttr - Adds an annotation Annot with Args arguments to D.
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:21065
void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI)
void AddSYCLIntelNumSimdWorkItemsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
AddAlignValueAttr - Adds an align_value attribute to a particular declaration.
void AddSYCLIntelMinWorkGroupsPerComputeUnitAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
std::pair< ValueDecl *, SourceLocation > PendingImplicitInstantiation
An entity for which implicit template instantiation is required.
Definition: Sema.h:10629
void AddSYCLIntelLoopFuseAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
DeclContext * FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, const MultiLevelTemplateArgumentList &TemplateArgs)
Finds the instantiation of the given declaration context within the current instantiation.
bool isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New)
Definition: SemaDecl.cpp:2509
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:523
void addSYCLIntelPipeIOAttr(Decl *D, const AttributeCommonInfo &CI, Expr *ID)
addSYCLIntelPipeIOAttr - Adds a pipe I/O attribute to a particular declaration.
void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI, Expr *ParamExpr)
AddAllocAlignAttr - Adds an alloc_align attribute to a particular declaration.
void PerformDependentDiagnostics(const DeclContext *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, bool IsFixed, const EnumDecl *Prev)
Check whether this is a valid redeclaration of a previous enumeration.
Definition: SemaDecl.cpp:17072
SemaCUDA & CUDA()
Definition: Sema.h:1002
void AddSYCLIntelInitiationIntervalAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr, bool SkipImmediateInvocations=true)
Instantiate or parse a C++ default argument expression as necessary.
Definition: SemaExpr.cpp:5449
ASTMutationListener * getASTMutationListener() const
Definition: Sema.cpp:583
void AddSYCLIntelMaxWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI, Expr *XDim, Expr *YDim, Expr *ZDim)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:6848
TypeSourceInfo * SubstFunctionDeclType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext, Qualifiers ThisTypeQuals, bool EvaluateConstraints=true)
A form of SubstType intended specifically for instantiating the type of a FunctionDecl.
Encodes a location in the source.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
Represents a C++11 static_assert declaration.
Definition: DeclCXX.h:4058
bool isFailed() const
Definition: DeclCXX.h:4087
SourceLocation getRParenLoc() const
Definition: DeclCXX.h:4089
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3587
bool isThisDeclarationADefinition() const
Return true if this declaration is a completion definition of the type.
Definition: Decl.h:3685
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3690
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier (with source-location information) that qualifies the name of this...
Definition: Decl.h:3832
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition: Decl.cpp:4732
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:4787
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3811
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:3815
TagKind getTagKind() const
Definition: Decl.h:3782
bool isBeingDefined() const
Determines whether this type is in the process of being defined.
Definition: Type.cpp:4036
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1327
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:650
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:651
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:667
A template argument list.
Definition: DeclTemplate.h:244
static TemplateArgumentList * CreateCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument list that copies the given set of template arguments.
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:274
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
SourceLocation getTemplateNameLoc() const
Definition: TemplateBase.h:616
NestedNameSpecifierLoc getTemplateQualifierLoc() const
Definition: TemplateBase.h:609
const TemplateArgument & getArgument() const
Definition: TemplateBase.h:574
Represents a template argument.
Definition: TemplateBase.h:61
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:343
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
void setEvaluateConstraints(bool B)
Definition: Template.h:592
Decl * VisitVarDecl(VarDecl *D, bool InstantiatingVarTemplate, ArrayRef< BindingDecl * > *Bindings=nullptr)
bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl)
Initializes common fields of an instantiated method declaration (New) from the corresponding fields o...
bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl)
Initializes the common fields of an instantiation function declaration (New) from the corresponding f...
VarTemplatePartialSpecializationDecl * InstantiateVarTemplatePartialSpecialization(VarTemplateDecl *VarTemplate, VarTemplatePartialSpecializationDecl *PartialSpec)
Instantiate the declaration of a variable template partial specialization.
void adjustForRewrite(RewriteKind RK, FunctionDecl *Orig, QualType &T, TypeSourceInfo *&TInfo, DeclarationNameInfo &NameInfo)
TypeSourceInfo * SubstFunctionType(FunctionDecl *D, SmallVectorImpl< ParmVarDecl * > &Params)
Decl * VisitVarTemplateSpecializationDecl(VarTemplateDecl *VarTemplate, VarDecl *FromVar, const TemplateArgumentListInfo &TemplateArgsInfo, ArrayRef< TemplateArgument > Converted, VarTemplateSpecializationDecl *PrevDecl=nullptr)
void InstantiateEnumDefinition(EnumDecl *Enum, EnumDecl *Pattern)
Decl * VisitFunctionDecl(FunctionDecl *D, TemplateParameterList *TemplateParams, RewriteKind RK=RewriteKind::None)
Normal class members are of more specific types and therefore don't make it here.
Decl * VisitCXXMethodDecl(CXXMethodDecl *D, TemplateParameterList *TemplateParams, RewriteKind RK=RewriteKind::None)
Decl * VisitBaseUsingDecls(BaseUsingDecl *D, BaseUsingDecl *Inst, LookupResult *Lookup)
bool SubstQualifier(const DeclaratorDecl *OldDecl, DeclaratorDecl *NewDecl)
TemplateParameterList * SubstTemplateParams(TemplateParameterList *List)
Instantiates a nested template parameter list in the current instantiation context.
Decl * InstantiateTypedefNameDecl(TypedefNameDecl *D, bool IsTypeAlias)
ClassTemplatePartialSpecializationDecl * InstantiateClassTemplatePartialSpecialization(ClassTemplateDecl *ClassTemplate, ClassTemplatePartialSpecializationDecl *PartialSpec)
Instantiate the declaration of a class template partial specialization.
bool SubstDefaultedFunction(FunctionDecl *New, FunctionDecl *Tmpl)
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Represents a C++ template name within the type system.
Definition: TemplateName.h:202
bool isNull() const
Determine whether this template name is NULL.
A template parameter object.
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:203
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
ArrayRef< NamedDecl * > asArray()
Definition: DeclTemplate.h:139
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:201
SourceLocation getLAngleLoc() const
Definition: DeclTemplate.h:200
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
Definition: DeclTemplate.h:180
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:199
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
bool wasDeclaredWithTypename() const
Whether this template template parameter was declared with the 'typename' keyword.
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
unsigned getNumExpansionTemplateParameters() const
Retrieves the number of expansion template parameters in an expanded parameter pack.
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
bool defaultArgumentWasInherited() const
Determines whether the default argument was inherited from a previous declaration of this template.
void setDefaultArgument(const ASTContext &C, const TemplateArgumentLoc &DefArg)
Set the default argument for this template parameter, and whether that default argument was inherited...
unsigned getDepth() const
Get the nesting depth of the template parameter.
bool isExpandedParameterPack() const
Whether this parameter is a template template parameter pack that has a known list of different templ...
TemplateParameterList * getExpansionTemplateParameters(unsigned I) const
Retrieve a particular expansion type within an expanded parameter pack.
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, bool Typename, TemplateParameterList *Params)
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
Declaration of a template type parameter.
bool wasDeclaredWithTypename() const
Whether this template type parameter was declared with the 'typename' keyword.
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
unsigned getIndex() const
Retrieve the index of the template parameter.
bool hasTypeConstraint() const
Determine whether this template parameter has a type-constraint.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, std::optional< unsigned > NumExpanded=std::nullopt)
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
bool defaultArgumentWasInherited() const
Determines whether the default argument was inherited from a previous declaration of this template.
bool isExpandedParameterPack() const
Whether this parameter is a template type parameter pack that has a known list of different type-cons...
bool isParameterPack() const
Returns whether this is a parameter pack.
unsigned getDepth() const
Retrieve the depth of the template parameter.
void setDefaultArgument(const ASTContext &C, const TemplateArgumentLoc &DefArg)
Set the default argument for this template parameter.
const TypeConstraint * getTypeConstraint() const
Returns the type constraint associated with this template parameter (if any).
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
The top declaration context.
Definition: Decl.h:84
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition: Decl.h:3558
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5558
void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT)
Definition: Decl.h:3577
Declaration of an alias template.
TypeAliasDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
static TypeAliasTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition: ASTConcept.h:231
void setTypeForDecl(const Type *TD)
Definition: Decl.h:3418
const Type * getTypeForDecl() const
Definition: Decl.h:3417
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:3420
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:59
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:89
TypeLoc IgnoreParens() const
Definition: TypeLoc.h:1225
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition: TypeLoc.h:78
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:153
AutoTypeLoc getContainedAutoTypeLoc() const
Get the typeloc of an AutoType whose type will be deduced for a variable with an initializer of this ...
Definition: TypeLoc.cpp:745
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2684
A container of type source information.
Definition: Type.h:7342
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7353
SourceLocation getNameLoc() const
Definition: TypeLoc.h:535
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:539
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1881
bool isRValueReferenceType() const
Definition: Type.h:7644
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2766
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8227
bool isReferenceType() const
Definition: Type.h:7636
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2669
bool isLValueReferenceType() const
Definition: Type.h:7640
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2661
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2320
bool isTemplateTypeParmType() const
Definition: Type.h:7904
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2679
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8073
bool isFunctionType() const
Definition: Type.h:7620
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8160
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition: Decl.h:3537
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5507
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3435
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:3485
QualType getUnderlyingType() const
Definition: Decl.h:3490
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition: DeclCXX.h:4346
This node is generated when a using-declaration that was annotated with attribute((using_if_exists)) ...
Definition: DeclCXX.h:4040
static UnresolvedUsingIfExistsDecl * Create(ASTContext &Ctx, DeclContext *DC, SourceLocation Loc, DeclarationName Name)
Definition: DeclCXX.cpp:3288
Represents a dependent using declaration which was marked with typename.
Definition: DeclCXX.h:3959
SourceLocation getTypenameLoc() const
Returns the source location of the 'typename' keyword.
Definition: DeclCXX.h:3989
Represents a dependent using declaration which was not marked with typename.
Definition: DeclCXX.h:3862
Represents a C++ using-declaration.
Definition: DeclCXX.h:3512
bool hasTypename() const
Return true if the using declaration has 'typename'.
Definition: DeclCXX.h:3561
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier that qualifies the name, with source-location information.
Definition: DeclCXX.h:3546
DeclarationNameInfo getNameInfo() const
Definition: DeclCXX.h:3553
static UsingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
Definition: DeclCXX.cpp:3173
SourceLocation getUsingLoc() const
Return the source location of the 'using' keyword.
Definition: DeclCXX.h:3539
Represents C++ using-directive.
Definition: DeclCXX.h:3015
static UsingDirectiveDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation NamespaceLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Nominated, DeclContext *CommonAncestor)
Definition: DeclCXX.cpp:2937
NamespaceDecl * getNominatedNamespace()
Returns the namespace nominated by this using-directive.
Definition: DeclCXX.cpp:2958
SourceLocation getNamespaceKeyLocation() const
Returns the location of the namespace keyword.
Definition: DeclCXX.h:3090
DeclContext * getCommonAncestor()
Returns the common ancestor context of this using-directive and its nominated namespace.
Definition: DeclCXX.h:3082
SourceLocation getIdentLocation() const
Returns the location of this using declaration's identifier.
Definition: DeclCXX.h:3093
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier that qualifies the name of the namespace, with source-location inf...
Definition: DeclCXX.h:3060
Represents a C++ using-enum-declaration.
Definition: DeclCXX.h:3713
SourceLocation getEnumLoc() const
The source location of the 'enum' keyword.
Definition: DeclCXX.h:3737
EnumDecl * getEnumDecl() const
Definition: DeclCXX.h:3757
TypeSourceInfo * getEnumType() const
Definition: DeclCXX.h:3751
static UsingEnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, SourceLocation EnumL, SourceLocation NameL, TypeSourceInfo *EnumType)
Definition: DeclCXX.cpp:3194
SourceLocation getUsingLoc() const
The source location of the 'using' keyword.
Definition: DeclCXX.h:3733
Represents a pack of using declarations that a single using-declarator pack-expanded into.
Definition: DeclCXX.h:3794
ArrayRef< NamedDecl * > expansions() const
Get the set of using declarations that this pack expanded into.
Definition: DeclCXX.h:3828
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3320
void setType(QualType newType)
Definition: Decl.h:719
QualType getType() const
Definition: Decl.h:718
Represents a variable declaration or definition.
Definition: Decl.h:919
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2791
void setObjCForDecl(bool FRD)
Definition: Decl.h:1517
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2152
void setCXXForRangeDecl(bool FRD)
Definition: Decl.h:1506
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1550
void setInstantiationOfStaticDataMember(VarDecl *VD, TemplateSpecializationKind TSK)
Specify that this variable is an instantiation of the static data member VD.
Definition: Decl.cpp:2908
TLSKind getTLSKind() const
Definition: Decl.cpp:2169
bool hasInit() const
Definition: Decl.cpp:2399
void setInitStyle(InitializationStyle Style)
Definition: Decl.h:1433
InitializationStyle getInitStyle() const
The style of initialization for this declaration.
Definition: Decl.h:1447
void setInitCapture(bool IC)
Definition: Decl.h:1562
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition: Decl.cpp:2261
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a static data member.
Definition: Decl.cpp:2442
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2258
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1559
@ CallInit
Call-style initialization (C++98)
Definition: Decl.h:927
bool isObjCForDecl() const
Determine whether this variable is a for-loop declaration for a for-in statement in Objective-C.
Definition: Decl.h:1513
void setPreviousDeclInSameBlockScope(bool Same)
Definition: Decl.h:1578
bool isInlineSpecified() const
Definition: Decl.h:1535
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1271
VarDecl * getTemplateInstantiationPattern() const
Retrieve the variable declaration from which this variable could be instantiated, if it is an instant...
Definition: Decl.cpp:2695
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1214
bool isCXXForRangeDecl() const
Determine whether this variable is the for-range-declaration in a C++0x for-range statement.
Definition: Decl.h:1503
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2367
bool mightBeUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value might be usable in a constant expression, according to the re...
Definition: Decl.cpp:2467
bool isNRVOVariable() const
Determine whether this local variable can be used with the named return value optimization (NRVO).
Definition: Decl.h:1493
void setInlineSpecified()
Definition: Decl.h:1539
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1196
const Expr * getInit() const
Definition: Decl.h:1356
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For a static data member that was instantiated from a static data member of a class template,...
Definition: Decl.cpp:2880
void setTSCSpec(ThreadStorageClassSpecifier TSC)
Definition: Decl.h:1161
void setNRVOVariable(bool NRVO)
Definition: Decl.h:1496
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1532
ThreadStorageClassSpecifier getTSCSpec() const
Definition: Decl.h:1165
void setConstexpr(bool IC)
Definition: Decl.h:1553
void setDescribedVarTemplate(VarTemplateDecl *Template)
Definition: Decl.cpp:2796
bool isDirectInit() const
Whether the initializer is a direct-initializer (list or call).
Definition: Decl.h:1452
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1156
void setImplicitlyInline()
Definition: Decl.h:1544
bool isPreviousDeclInSameBlockScope() const
Whether this local extern variable declaration's previous declaration was declared in the same block ...
Definition: Decl.h:1573
SourceLocation getPointOfInstantiation() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2781
TemplateSpecializationKind getTemplateSpecializationKindForInstantiation() const
Get the template specialization kind of this variable for the purposes of template instantiation.
Definition: Decl.cpp:2771
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2760
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition: Decl.cpp:2667
Declaration of a variable template.
VarDecl * getTemplatedDecl() const
Get the underlying variable declarations of the template.
void AddPartialSpecialization(VarTemplatePartialSpecializationDecl *D, void *InsertPos)
Insert the specified partial specialization knowing that it is not already in.
VarTemplatePartialSpecializationDecl * findPartialSpecialization(ArrayRef< TemplateArgument > Args, TemplateParameterList *TPL, void *&InsertPos)
Return the partial specialization with the provided arguments if it exists, otherwise return the inse...
void AddSpecialization(VarTemplateSpecializationDecl *D, void *InsertPos)
Insert the specified specialization knowing that it is not already in.
static VarTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, VarDecl *Decl)
Create a variable template node.
llvm::FoldingSetVector< VarTemplatePartialSpecializationDecl > & getPartialSpecializations() const
Retrieve the set of partial specializations of this class template.
VarTemplateSpecializationDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
VarTemplatePartialSpecializationDecl * findPartialSpecInstantiatedFromMember(VarTemplatePartialSpecializationDecl *D)
Find a variable template partial specialization which was instantiated from the given member partial ...
static VarTemplatePartialSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
void setInstantiatedFromMember(VarTemplatePartialSpecializationDecl *PartialSpec)
Represents a variable template specialization, which refers to a variable template with a given set o...
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Retrieve the template argument list as written in the sources, if any.
static VarTemplateSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
VarTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
const TemplateArgumentList & getTemplateInstantiationArgs() const
Retrieve the set of template arguments that should be used to instantiate the initializer of the vari...
const TemplateArgumentList & getTemplateArgs() const
Retrieve the template arguments of the variable template specialization.
llvm::PointerUnion< VarTemplateDecl *, VarTemplatePartialSpecializationDecl * > getSpecializedTemplateOrPartial() const
Retrieve the variable template or variable template partial specialization which was specialized by t...
RetTy Visit(PTR(Decl) D)
Definition: DeclVisitor.h:37
QualType FunctionType
BlockType - The function type of the block, if one was given.
Definition: ScopeInfo.h:794
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition: ScopeInfo.h:731
Provides information about an attempted template argument deduction, whose success or failure was des...
Defines the clang::TargetInfo interface.
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
llvm::APInt APInt
Definition: Integral.h:29
bool NE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:869
bool Init(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1472
Attr * instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs)
Attr * instantiateTemplateAttributeForDecl(const Attr *At, ASTContext &C, Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs)
The JSON file list parser is used to communicate input to InstallAPI.
void atTemplateEnd(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema, const Sema::CodeSynthesisContext &Inst)
@ OpenCL
Definition: LangStandard.h:65
@ CPlusPlus11
Definition: LangStandard.h:56
void atTemplateBegin(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema, const Sema::CodeSynthesisContext &Inst)
@ Rewrite
We are substituting template parameters for (typically) other template parameters in order to rewrite...
StorageClass
Storage classes.
Definition: Specifiers.h:245
@ SC_Static
Definition: Specifiers.h:249
@ SC_None
Definition: Specifiers.h:247
ExprResult ExprEmpty()
Definition: Ownership.h:271
@ Property
The type of a property.
@ TU_Prefix
The translation unit is a prefix to a translation unit, and is not complete.
Definition: LangOptions.h:1080
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
const FunctionProtoType * T
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1275
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:185
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:203
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:199
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:195
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:191
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:188
@ Other
Other implicit parameter.
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_DynamicNone
throw()
@ EST_Uninstantiated
not instantiated yet
@ EST_None
no exception specification
@ EST_BasicNoexcept
noexcept
@ EST_Unevaluated
not evaluated yet, for special member function
@ AS_public
Definition: Specifiers.h:121
@ AS_protected
Definition: Specifiers.h:122
@ AS_none
Definition: Specifiers.h:124
@ AS_private
Definition: Specifiers.h:123
#define bool
Definition: stdbool.h:24
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
Definition: TemplateBase.h:676
SourceLocation RAngleLoc
The source location of the right angle bracket ('>').
Definition: TemplateBase.h:691
SourceLocation LAngleLoc
The source location of the left angle bracket ('<').
Definition: TemplateBase.h:688
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:705
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
const DeclarationNameLoc & getInfo() const
Holds information about the various types of exception specification.
Definition: Type.h:4719
FunctionDecl * SourceDecl
The function whose exception specification this is, for EST_Unevaluated and EST_Uninstantiated.
Definition: Type.h:4731
FunctionDecl * SourceTemplate
The function template whose exception specification this is instantiated from, for EST_Uninstantiated...
Definition: Type.h:4735
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:4721
Extra information about a function prototype.
Definition: Type.h:4747
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:4754
FunctionType::ExtInfo ExtInfo
Definition: Type.h:4748
This structure contains most locations needed for by an OMPVarListClause.
Definition: OpenMPClause.h:259
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:9920
SynthesisKind
The kind of template instantiation we are performing.
Definition: Sema.h:9922
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition: Sema.h:10027
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition: Sema.h:9948
A stack object to be created when performing template instantiation.
Definition: Sema.h:10105
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:10259
bool isAlreadyInstantiating() const
Determine whether we are already instantiating this specialization in some surrounding active instant...
Definition: Sema.h:10263