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