blob: 881b4fd992e1705676931ff6e016cf2306e4b0e2 [file] [log] [blame]
Douglas Gregord7e7a512009-03-17 21:15:40 +00001//===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Douglas Gregord7e7a512009-03-17 21:15:40 +00006//===----------------------------------------------------------------------===/
7//
8// This file implements C++ template instantiation for declarations.
9//
10//===----------------------------------------------------------------------===/
John McCall83024632010-08-25 22:03:47 +000011#include "clang/Sema/SemaInternal.h"
Douglas Gregor28ad4b52009-05-26 20:50:29 +000012#include "clang/AST/ASTConsumer.h"
Douglas Gregord7e7a512009-03-17 21:15:40 +000013#include "clang/AST/ASTContext.h"
Richard Smithd28ac5b2014-03-22 23:33:22 +000014#include "clang/AST/ASTMutationListener.h"
Douglas Gregord7e7a512009-03-17 21:15:40 +000015#include "clang/AST/DeclTemplate.h"
16#include "clang/AST/DeclVisitor.h"
John McCallc62bb642010-03-24 05:22:00 +000017#include "clang/AST/DependentDiagnostic.h"
Douglas Gregord7e7a512009-03-17 21:15:40 +000018#include "clang/AST/Expr.h"
Douglas Gregor6131b442009-12-12 18:16:41 +000019#include "clang/AST/ExprCXX.h"
Jordan Rose1e879d82018-03-23 00:07:18 +000020#include "clang/AST/PrettyDeclStackTrace.h"
John McCall58f10c32010-03-11 09:03:00 +000021#include "clang/AST/TypeLoc.h"
Richard Smith3997b1b2016-08-12 01:55:21 +000022#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/Sema/Lookup.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Sema/Template.h"
Gabor Horvath207e7b12018-02-10 14:04:45 +000025#include "clang/Sema/TemplateInstCallback.h"
Anton Afanasyevd880de22019-03-30 08:42:48 +000026#include "llvm/Support/TimeProfiler.h"
Douglas Gregord7e7a512009-03-17 21:15:40 +000027
28using namespace clang;
29
David Majnemer192d1792013-11-27 08:20:38 +000030static bool isDeclWithinFunction(const Decl *D) {
31 const DeclContext *DC = D->getDeclContext();
32 if (DC->isFunctionOrMethod())
33 return true;
34
35 if (DC->isRecord())
36 return cast<CXXRecordDecl>(DC)->isLocalClass();
37
38 return false;
39}
40
Richard Smithcc928662014-10-17 20:37:29 +000041template<typename DeclT>
42static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
43 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor14454802011-02-25 02:25:35 +000044 if (!OldDecl->getQualifierLoc())
45 return false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000046
Richard Smithcc928662014-10-17 20:37:29 +000047 assert((NewDecl->getFriendObjectKind() ||
48 !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
49 "non-friend with qualified name defined in dependent context");
50 Sema::ContextRAII SavedContext(
51 SemaRef,
52 const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
53 ? NewDecl->getLexicalDeclContext()
54 : OldDecl->getLexicalDeclContext()));
55
Douglas Gregor14454802011-02-25 02:25:35 +000056 NestedNameSpecifierLoc NewQualifierLoc
Richard Smithcc928662014-10-17 20:37:29 +000057 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
58 TemplateArgs);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000059
Douglas Gregor14454802011-02-25 02:25:35 +000060 if (!NewQualifierLoc)
John McCall3e11ebe2010-03-15 10:12:16 +000061 return true;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000062
Douglas Gregor14454802011-02-25 02:25:35 +000063 NewDecl->setQualifierInfo(NewQualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +000064 return false;
65}
66
Richard Smithcc928662014-10-17 20:37:29 +000067bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
68 DeclaratorDecl *NewDecl) {
69 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
70}
71
John McCall3e11ebe2010-03-15 10:12:16 +000072bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
73 TagDecl *NewDecl) {
Richard Smithcc928662014-10-17 20:37:29 +000074 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
John McCall3e11ebe2010-03-15 10:12:16 +000075}
76
DeLesley Hutchinsceec3062012-01-20 22:37:06 +000077// Include attribute instantiation code.
78#include "clang/Sema/AttrTemplateInstantiate.inc"
79
Richard Smith44c247f2013-02-22 08:32:16 +000080static void instantiateDependentAlignedAttr(
81 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
82 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
83 if (Aligned->isAlignmentExpr()) {
84 // The alignment expression is a constant expression.
Faisal Valid143a0c2017-04-01 21:30:49 +000085 EnterExpressionEvaluationContext Unevaluated(
86 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Richard Smith44c247f2013-02-22 08:32:16 +000087 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
88 if (!Result.isInvalid())
Erich Keane6a24e802019-09-13 17:39:31 +000089 S.AddAlignedAttr(New, *Aligned, Result.getAs<Expr>(), IsPackExpansion);
Richard Smith44c247f2013-02-22 08:32:16 +000090 } else {
91 TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
92 TemplateArgs, Aligned->getLocation(),
93 DeclarationName());
94 if (Result)
Erich Keane6a24e802019-09-13 17:39:31 +000095 S.AddAlignedAttr(New, *Aligned, Result, IsPackExpansion);
Richard Smith44c247f2013-02-22 08:32:16 +000096 }
97}
98
99static void instantiateDependentAlignedAttr(
100 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
101 const AlignedAttr *Aligned, Decl *New) {
102 if (!Aligned->isPackExpansion()) {
103 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
104 return;
105 }
106
107 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
108 if (Aligned->isAlignmentExpr())
109 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
110 Unexpanded);
111 else
112 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
113 Unexpanded);
114 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
115
116 // Determine whether we can expand this attribute pack yet.
117 bool Expand = true, RetainExpansion = false;
118 Optional<unsigned> NumExpansions;
119 // FIXME: Use the actual location of the ellipsis.
120 SourceLocation EllipsisLoc = Aligned->getLocation();
121 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
122 Unexpanded, TemplateArgs, Expand,
123 RetainExpansion, NumExpansions))
124 return;
125
126 if (!Expand) {
127 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
128 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
129 } else {
130 for (unsigned I = 0; I != *NumExpansions; ++I) {
131 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
132 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
133 }
134 }
135}
136
Hal Finkelee90a222014-09-26 05:04:30 +0000137static void instantiateDependentAssumeAlignedAttr(
138 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
139 const AssumeAlignedAttr *Aligned, Decl *New) {
140 // The alignment expression is a constant expression.
Faisal Valid143a0c2017-04-01 21:30:49 +0000141 EnterExpressionEvaluationContext Unevaluated(
142 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Hal Finkelee90a222014-09-26 05:04:30 +0000143
144 Expr *E, *OE = nullptr;
145 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
146 if (Result.isInvalid())
147 return;
148 E = Result.getAs<Expr>();
149
150 if (Aligned->getOffset()) {
151 Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
152 if (Result.isInvalid())
153 return;
154 OE = Result.getAs<Expr>();
155 }
156
Erich Keane6a24e802019-09-13 17:39:31 +0000157 S.AddAssumeAlignedAttr(New, *Aligned, E, OE);
Hal Finkelee90a222014-09-26 05:04:30 +0000158}
159
Hal Finkel1b0d24e2014-10-02 21:21:25 +0000160static void instantiateDependentAlignValueAttr(
161 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
162 const AlignValueAttr *Aligned, Decl *New) {
163 // The alignment expression is a constant expression.
Faisal Valid143a0c2017-04-01 21:30:49 +0000164 EnterExpressionEvaluationContext Unevaluated(
165 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Hal Finkel1b0d24e2014-10-02 21:21:25 +0000166 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
167 if (!Result.isInvalid())
Erich Keane6a24e802019-09-13 17:39:31 +0000168 S.AddAlignValueAttr(New, *Aligned, Result.getAs<Expr>());
Hal Finkel1b0d24e2014-10-02 21:21:25 +0000169}
170
Erich Keane623efd82017-03-30 21:48:55 +0000171static void instantiateDependentAllocAlignAttr(
172 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
173 const AllocAlignAttr *Align, Decl *New) {
174 Expr *Param = IntegerLiteral::Create(
Joel E. Denny81508102018-03-13 14:51:22 +0000175 S.getASTContext(),
176 llvm::APInt(64, Align->getParamIndex().getSourceIndex()),
Erich Keane623efd82017-03-30 21:48:55 +0000177 S.getASTContext().UnsignedLongLongTy, Align->getLocation());
Erich Keane6a24e802019-09-13 17:39:31 +0000178 S.AddAllocAlignAttr(New, *Align, Param);
Erich Keane623efd82017-03-30 21:48:55 +0000179}
180
George Burgess IV177399e2017-01-09 04:12:14 +0000181static Expr *instantiateDependentFunctionAttrCondition(
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000182 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
George Burgess IV177399e2017-01-09 04:12:14 +0000183 const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000184 Expr *Cond = nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000185 {
George Burgess IV177399e2017-01-09 04:12:14 +0000186 Sema::ContextRAII SwitchContext(S, New);
Faisal Valid143a0c2017-04-01 21:30:49 +0000187 EnterExpressionEvaluationContext Unevaluated(
188 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
George Burgess IV177399e2017-01-09 04:12:14 +0000189 ExprResult Result = S.SubstExpr(OldCond, TemplateArgs);
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000190 if (Result.isInvalid())
George Burgess IV177399e2017-01-09 04:12:14 +0000191 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000192 Cond = Result.getAs<Expr>();
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000193 }
George Burgess IV00431952016-11-17 01:33:54 +0000194 if (!Cond->isTypeDependent()) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000195 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
196 if (Converted.isInvalid())
George Burgess IV177399e2017-01-09 04:12:14 +0000197 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000198 Cond = Converted.get();
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000199 }
200
201 SmallVector<PartialDiagnosticAt, 8> Diags;
George Burgess IV177399e2017-01-09 04:12:14 +0000202 if (OldCond->isValueDependent() && !Cond->isValueDependent() &&
203 !Expr::isPotentialConstantExprUnevaluated(Cond, New, Diags)) {
204 S.Diag(A->getLocation(), diag::err_attr_cond_never_constant_expr) << A;
205 for (const auto &P : Diags)
206 S.Diag(P.first, P.second);
207 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000208 }
George Burgess IV177399e2017-01-09 04:12:14 +0000209 return Cond;
210}
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000211
George Burgess IV177399e2017-01-09 04:12:14 +0000212static void instantiateDependentEnableIfAttr(
213 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
214 const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) {
215 Expr *Cond = instantiateDependentFunctionAttrCondition(
216 S, TemplateArgs, EIA, EIA->getCond(), Tmpl, New);
217
218 if (Cond)
Erich Keane6a24e802019-09-13 17:39:31 +0000219 New->addAttr(new (S.getASTContext()) EnableIfAttr(S.getASTContext(), *EIA,
220 Cond, EIA->getMessage()));
George Burgess IV177399e2017-01-09 04:12:14 +0000221}
222
223static void instantiateDependentDiagnoseIfAttr(
224 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
225 const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) {
226 Expr *Cond = instantiateDependentFunctionAttrCondition(
227 S, TemplateArgs, DIA, DIA->getCond(), Tmpl, New);
228
229 if (Cond)
230 New->addAttr(new (S.getASTContext()) DiagnoseIfAttr(
Erich Keane6a24e802019-09-13 17:39:31 +0000231 S.getASTContext(), *DIA, Cond, DIA->getMessage(),
232 DIA->getDiagnosticType(), DIA->getArgDependent(), New));
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000233}
234
Artem Belevich7093e402015-04-21 22:55:54 +0000235// Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
236// template A as the base and arguments from TemplateArgs.
237static void instantiateDependentCUDALaunchBoundsAttr(
238 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
239 const CUDALaunchBoundsAttr &Attr, Decl *New) {
240 // The alignment expression is a constant expression.
Faisal Valid143a0c2017-04-01 21:30:49 +0000241 EnterExpressionEvaluationContext Unevaluated(
242 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Artem Belevich7093e402015-04-21 22:55:54 +0000243
244 ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
245 if (Result.isInvalid())
246 return;
247 Expr *MaxThreads = Result.getAs<Expr>();
248
249 Expr *MinBlocks = nullptr;
250 if (Attr.getMinBlocks()) {
251 Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
252 if (Result.isInvalid())
253 return;
254 MinBlocks = Result.getAs<Expr>();
255 }
256
Erich Keane6a24e802019-09-13 17:39:31 +0000257 S.AddLaunchBoundsAttr(New, Attr, MaxThreads, MinBlocks);
Artem Belevich7093e402015-04-21 22:55:54 +0000258}
259
Denis Zobnind9e2dcd2016-02-02 13:50:39 +0000260static void
261instantiateDependentModeAttr(Sema &S,
262 const MultiLevelTemplateArgumentList &TemplateArgs,
263 const ModeAttr &Attr, Decl *New) {
Erich Keane6a24e802019-09-13 17:39:31 +0000264 S.AddModeAttr(New, Attr, Attr.getMode(),
265 /*InInstantiation=*/true);
Denis Zobnind9e2dcd2016-02-02 13:50:39 +0000266}
267
Alexey Bataev2af33e32016-04-07 12:45:37 +0000268/// Instantiation of 'declare simd' attribute and its arguments.
269static void instantiateOMPDeclareSimdDeclAttr(
270 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
271 const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +0000272 // Allow 'this' in clauses with varlists.
273 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
274 New = FTD->getTemplatedDecl();
275 auto *FD = cast<FunctionDecl>(New);
276 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
Alexey Bataevecba70f2016-04-12 11:02:11 +0000277 SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
278 SmallVector<unsigned, 4> LinModifiers;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +0000279
Richard Smith715f7a12019-06-11 17:50:32 +0000280 auto SubstExpr = [&](Expr *E) -> ExprResult {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +0000281 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
282 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
283 Sema::ContextRAII SavedContext(S, FD);
284 LocalInstantiationScope Local(S);
285 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
286 Local.InstantiatedLocal(
287 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
288 return S.SubstExpr(E, TemplateArgs);
289 }
Mikael Nilsson9d2872d2018-12-13 10:15:27 +0000290 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
Alexey Bataeve48a5fc2016-04-12 05:28:34 +0000291 FD->isCXXInstanceMember());
292 return S.SubstExpr(E, TemplateArgs);
293 };
294
Richard Smith715f7a12019-06-11 17:50:32 +0000295 // Substitute a single OpenMP clause, which is a potentially-evaluated
296 // full-expression.
297 auto Subst = [&](Expr *E) -> ExprResult {
298 EnterExpressionEvaluationContext Evaluated(
299 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
300 ExprResult Res = SubstExpr(E);
301 if (Res.isInvalid())
302 return Res;
303 return S.ActOnFinishFullExpr(Res.get(), false);
304 };
305
Alexey Bataevecba70f2016-04-12 11:02:11 +0000306 ExprResult Simdlen;
307 if (auto *E = Attr.getSimdlen())
308 Simdlen = Subst(E);
309
Alexey Bataeve48a5fc2016-04-12 05:28:34 +0000310 if (Attr.uniforms_size() > 0) {
311 for(auto *E : Attr.uniforms()) {
312 ExprResult Inst = Subst(E);
313 if (Inst.isInvalid())
314 continue;
315 Uniforms.push_back(Inst.get());
316 }
Alexey Bataev2af33e32016-04-07 12:45:37 +0000317 }
318
Alexey Bataevd93d3762016-04-12 09:35:56 +0000319 auto AI = Attr.alignments_begin();
320 for (auto *E : Attr.aligneds()) {
321 ExprResult Inst = Subst(E);
322 if (Inst.isInvalid())
323 continue;
324 Aligneds.push_back(Inst.get());
325 Inst = ExprEmpty();
326 if (*AI)
327 Inst = S.SubstExpr(*AI, TemplateArgs);
328 Alignments.push_back(Inst.get());
329 ++AI;
330 }
Alexey Bataevecba70f2016-04-12 11:02:11 +0000331
332 auto SI = Attr.steps_begin();
333 for (auto *E : Attr.linears()) {
334 ExprResult Inst = Subst(E);
335 if (Inst.isInvalid())
336 continue;
337 Linears.push_back(Inst.get());
338 Inst = ExprEmpty();
339 if (*SI)
340 Inst = S.SubstExpr(*SI, TemplateArgs);
341 Steps.push_back(Inst.get());
342 ++SI;
343 }
344 LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
Alexey Bataevd93d3762016-04-12 09:35:56 +0000345 (void)S.ActOnOpenMPDeclareSimdDirective(
346 S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
Alexey Bataevecba70f2016-04-12 11:02:11 +0000347 Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
348 Attr.getRange());
Alexey Bataev2af33e32016-04-07 12:45:37 +0000349}
350
Alexey Bataevbf5d4292019-09-17 17:36:49 +0000351/// Instantiation of 'declare variant' attribute and its arguments.
352static void instantiateOMPDeclareVariantAttr(
353 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
354 const OMPDeclareVariantAttr &Attr, Decl *New) {
355 // Allow 'this' in clauses with varlists.
356 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
357 New = FTD->getTemplatedDecl();
358 auto *FD = cast<FunctionDecl>(New);
359 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
360
361 auto &&SubstExpr = [FD, ThisContext, &S, &TemplateArgs](Expr *E) {
362 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
363 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
364 Sema::ContextRAII SavedContext(S, FD);
365 LocalInstantiationScope Local(S);
366 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
367 Local.InstantiatedLocal(
368 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
369 return S.SubstExpr(E, TemplateArgs);
370 }
371 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
372 FD->isCXXInstanceMember());
373 return S.SubstExpr(E, TemplateArgs);
374 };
375
376 // Substitute a single OpenMP clause, which is a potentially-evaluated
377 // full-expression.
378 auto &&Subst = [&SubstExpr, &S](Expr *E) {
379 EnterExpressionEvaluationContext Evaluated(
380 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
381 ExprResult Res = SubstExpr(E);
382 if (Res.isInvalid())
383 return Res;
384 return S.ActOnFinishFullExpr(Res.get(), false);
385 };
386
387 ExprResult VariantFuncRef;
388 if (Expr *E = Attr.getVariantFuncRef())
389 VariantFuncRef = Subst(E);
390
Alexey Bataeva15a1412019-10-02 18:19:02 +0000391 ExprResult Score;
392 if (Expr *E = Attr.getScore())
393 Score = Subst(E);
394
Alexey Bataev0736f7f2019-09-18 16:24:31 +0000395 // Check function/variant ref.
396 Optional<std::pair<FunctionDecl *, Expr *>> DeclVarData =
397 S.checkOpenMPDeclareVariantFunction(
398 S.ConvertDeclToDeclGroup(New), VariantFuncRef.get(), Attr.getRange());
399 if (!DeclVarData)
400 return;
401 // Instantiate the attribute.
Alexey Bataeva15a1412019-10-02 18:19:02 +0000402 Sema::OpenMPDeclareVariantCtsSelectorData Data(Attr.getCtxSelectorSet(),
403 Attr.getCtxSelector(),
404 Attr.getImplVendor(), Score);
Alexey Bataev0736f7f2019-09-18 16:24:31 +0000405 S.ActOnOpenMPDeclareVariantDirective(DeclVarData.getValue().first,
406 DeclVarData.getValue().second,
Alexey Bataev9ff34742019-09-25 19:43:37 +0000407 Attr.getRange(), Data);
Alexey Bataevbf5d4292019-09-17 17:36:49 +0000408}
409
Michael Liao7557afa2019-02-26 18:49:36 +0000410static void instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
411 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
412 const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) {
413 // Both min and max expression are constant expressions.
414 EnterExpressionEvaluationContext Unevaluated(
415 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
416
417 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
418 if (Result.isInvalid())
419 return;
420 Expr *MinExpr = Result.getAs<Expr>();
421
422 Result = S.SubstExpr(Attr.getMax(), TemplateArgs);
423 if (Result.isInvalid())
424 return;
425 Expr *MaxExpr = Result.getAs<Expr>();
426
Erich Keane6a24e802019-09-13 17:39:31 +0000427 S.addAMDGPUFlatWorkGroupSizeAttr(New, Attr, MinExpr, MaxExpr);
Michael Liao7557afa2019-02-26 18:49:36 +0000428}
429
Richard Smith76b90272019-05-09 03:59:21 +0000430static ExplicitSpecifier
431instantiateExplicitSpecifier(Sema &S,
432 const MultiLevelTemplateArgumentList &TemplateArgs,
433 ExplicitSpecifier ES, FunctionDecl *New) {
434 if (!ES.getExpr())
435 return ES;
436 Expr *OldCond = ES.getExpr();
437 Expr *Cond = nullptr;
438 {
439 EnterExpressionEvaluationContext Unevaluated(
440 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
441 ExprResult SubstResult = S.SubstExpr(OldCond, TemplateArgs);
442 if (SubstResult.isInvalid()) {
443 return ExplicitSpecifier::Invalid();
444 }
445 Cond = SubstResult.get();
446 }
447 ExplicitSpecifier Result(Cond, ES.getKind());
448 if (!Cond->isTypeDependent())
449 S.tryResolveExplicitSpecifier(Result);
450 return Result;
451}
452
Michael Liao7557afa2019-02-26 18:49:36 +0000453static void instantiateDependentAMDGPUWavesPerEUAttr(
454 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
455 const AMDGPUWavesPerEUAttr &Attr, Decl *New) {
456 // Both min and max expression are constant expressions.
457 EnterExpressionEvaluationContext Unevaluated(
458 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
459
460 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
461 if (Result.isInvalid())
462 return;
463 Expr *MinExpr = Result.getAs<Expr>();
464
465 Expr *MaxExpr = nullptr;
466 if (auto Max = Attr.getMax()) {
467 Result = S.SubstExpr(Max, TemplateArgs);
468 if (Result.isInvalid())
469 return;
470 MaxExpr = Result.getAs<Expr>();
471 }
472
Erich Keane6a24e802019-09-13 17:39:31 +0000473 S.addAMDGPUWavesPerEUAttr(New, Attr, MinExpr, MaxExpr);
Michael Liao7557afa2019-02-26 18:49:36 +0000474}
475
Erich Keanea32910d2017-03-23 18:51:54 +0000476void Sema::InstantiateAttrsForDecl(
477 const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl,
478 Decl *New, LateInstantiatedAttrVec *LateAttrs,
479 LocalInstantiationScope *OuterMostScope) {
480 if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) {
481 for (const auto *TmplAttr : Tmpl->attrs()) {
482 // FIXME: If any of the special case versions from InstantiateAttrs become
483 // applicable to template declaration, we'll need to add them here.
484 CXXThisScopeRAII ThisScope(
485 *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()),
Mikael Nilsson9d2872d2018-12-13 10:15:27 +0000486 Qualifiers(), ND->isCXXInstanceMember());
Erich Keanea32910d2017-03-23 18:51:54 +0000487
488 Attr *NewAttr = sema::instantiateTemplateAttributeForDecl(
489 TmplAttr, Context, *this, TemplateArgs);
Richard Smith33bddbd2018-01-04 23:42:29 +0000490 if (NewAttr)
Erich Keanea32910d2017-03-23 18:51:54 +0000491 New->addAttr(NewAttr);
492 }
493 }
494}
495
George Karpenkov1657f362018-11-30 02:18:37 +0000496static Sema::RetainOwnershipKind
497attrToRetainOwnershipKind(const Attr *A) {
498 switch (A->getKind()) {
499 case clang::attr::CFConsumed:
500 return Sema::RetainOwnershipKind::CF;
501 case clang::attr::OSConsumed:
502 return Sema::RetainOwnershipKind::OS;
503 case clang::attr::NSConsumed:
504 return Sema::RetainOwnershipKind::NS;
505 default:
506 llvm_unreachable("Wrong argument supplied");
507 }
508}
509
John McCall6602bb12010-08-01 02:01:53 +0000510void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000511 const Decl *Tmpl, Decl *New,
512 LateInstantiatedAttrVec *LateAttrs,
513 LocalInstantiationScope *OuterMostScope) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000514 for (const auto *TmplAttr : Tmpl->attrs()) {
Chandler Carruthf40c42f2010-06-25 03:22:07 +0000515 // FIXME: This should be generalized to more than just the AlignedAttr.
Richard Smith44c247f2013-02-22 08:32:16 +0000516 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
517 if (Aligned && Aligned->isAlignmentDependent()) {
518 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
519 continue;
Chandler Carruthf40c42f2010-06-25 03:22:07 +0000520 }
521
Erich Keane23384a12019-08-23 15:58:35 +0000522 if (const auto *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr)) {
Hal Finkelee90a222014-09-26 05:04:30 +0000523 instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
524 continue;
525 }
526
Erich Keane23384a12019-08-23 15:58:35 +0000527 if (const auto *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr)) {
Hal Finkel1b0d24e2014-10-02 21:21:25 +0000528 instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
529 continue;
530 }
531
Erich Keane623efd82017-03-30 21:48:55 +0000532 if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) {
533 instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New);
534 continue;
535 }
536
537
George Burgess IV00431952016-11-17 01:33:54 +0000538 if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000539 instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
George Burgess IV177399e2017-01-09 04:12:14 +0000540 cast<FunctionDecl>(New));
541 continue;
542 }
543
544 if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) {
545 instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl,
546 cast<FunctionDecl>(New));
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000547 continue;
548 }
549
Erich Keane23384a12019-08-23 15:58:35 +0000550 if (const auto *CUDALaunchBounds =
Artem Belevich7093e402015-04-21 22:55:54 +0000551 dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
552 instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs,
553 *CUDALaunchBounds, New);
554 continue;
555 }
556
Erich Keane23384a12019-08-23 15:58:35 +0000557 if (const auto *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +0000558 instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
559 continue;
560 }
561
Alexey Bataev2af33e32016-04-07 12:45:37 +0000562 if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
563 instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
564 continue;
565 }
566
Alexey Bataevbf5d4292019-09-17 17:36:49 +0000567 if (const auto *OMPAttr = dyn_cast<OMPDeclareVariantAttr>(TmplAttr)) {
568 instantiateOMPDeclareVariantAttr(*this, TemplateArgs, *OMPAttr, New);
569 continue;
570 }
571
Erich Keane23384a12019-08-23 15:58:35 +0000572 if (const auto *AMDGPUFlatWorkGroupSize =
Michael Liao7557afa2019-02-26 18:49:36 +0000573 dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(TmplAttr)) {
574 instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
575 *this, TemplateArgs, *AMDGPUFlatWorkGroupSize, New);
576 }
577
Erich Keane23384a12019-08-23 15:58:35 +0000578 if (const auto *AMDGPUFlatWorkGroupSize =
Michael Liao7557afa2019-02-26 18:49:36 +0000579 dyn_cast<AMDGPUWavesPerEUAttr>(TmplAttr)) {
580 instantiateDependentAMDGPUWavesPerEUAttr(*this, TemplateArgs,
581 *AMDGPUFlatWorkGroupSize, New);
582 }
583
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +0000584 // Existing DLL attribute on the instantiation takes precedence.
585 if (TmplAttr->getKind() == attr::DLLExport ||
586 TmplAttr->getKind() == attr::DLLImport) {
587 if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
588 continue;
589 }
590 }
591
Erich Keane23384a12019-08-23 15:58:35 +0000592 if (const auto *ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
Erich Keane6a24e802019-09-13 17:39:31 +0000593 AddParameterABIAttr(New, *ABIAttr, ABIAttr->getABI());
John McCall477f2bb2016-03-03 06:39:32 +0000594 continue;
595 }
596
George Karpenkov1657f362018-11-30 02:18:37 +0000597 if (isa<NSConsumedAttr>(TmplAttr) || isa<OSConsumedAttr>(TmplAttr) ||
598 isa<CFConsumedAttr>(TmplAttr)) {
Erich Keane6a24e802019-09-13 17:39:31 +0000599 AddXConsumedAttr(New, *TmplAttr, attrToRetainOwnershipKind(TmplAttr),
George Karpenkov1657f362018-11-30 02:18:37 +0000600 /*template instantiation=*/true);
John McCall3b5a8f52016-03-03 00:10:03 +0000601 continue;
602 }
603
Matthias Gehref64f4882019-09-06 08:56:30 +0000604 if (auto *A = dyn_cast<PointerAttr>(TmplAttr)) {
605 if (!New->hasAttr<PointerAttr>())
606 New->addAttr(A->clone(Context));
607 continue;
608 }
609
610 if (auto *A = dyn_cast<OwnerAttr>(TmplAttr)) {
611 if (!New->hasAttr<OwnerAttr>())
612 New->addAttr(A->clone(Context));
613 continue;
614 }
615
Richard Smith44c247f2013-02-22 08:32:16 +0000616 assert(!TmplAttr->isPackExpansion());
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000617 if (TmplAttr->isLateParsed() && LateAttrs) {
618 // Late parsed attributes must be instantiated and attached after the
619 // enclosing class has been instantiated. See Sema::InstantiateClass.
Craig Topperc3ec1492014-05-26 06:22:03 +0000620 LocalInstantiationScope *Saved = nullptr;
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000621 if (CurrentInstantiationScope)
622 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
623 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
624 } else {
Richard Smithc3d2ebb2013-06-07 02:33:37 +0000625 // Allow 'this' within late-parsed attributes.
626 NamedDecl *ND = dyn_cast<NamedDecl>(New);
627 CXXRecordDecl *ThisContext =
628 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
Mikael Nilsson9d2872d2018-12-13 10:15:27 +0000629 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
Richard Smithc3d2ebb2013-06-07 02:33:37 +0000630 ND && ND->isCXXInstanceMember());
631
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +0000632 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
633 *this, TemplateArgs);
Richard Smith33bddbd2018-01-04 23:42:29 +0000634 if (NewAttr)
Rafael Espindola7f90b7d2012-05-15 14:09:55 +0000635 New->addAttr(NewAttr);
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000636 }
Anders Carlsson3d709752009-11-07 06:07:58 +0000637 }
638}
639
Richard Smith41c79d92014-10-11 00:37:16 +0000640/// Get the previous declaration of a declaration for the purposes of template
641/// instantiation. If this finds a previous declaration, then the previous
642/// declaration of the instantiation of D should be an instantiation of the
643/// result of this function.
644template<typename DeclT>
645static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
646 DeclT *Result = D->getPreviousDecl();
647
648 // If the declaration is within a class, and the previous declaration was
649 // merged from a different definition of that class, then we don't have a
650 // previous declaration for the purpose of template instantiation.
651 if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
652 D->getLexicalDeclContext() != Result->getLexicalDeclContext())
653 return nullptr;
654
655 return Result;
656}
657
Douglas Gregor8a655532009-03-25 15:45:12 +0000658Decl *
659TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000660 llvm_unreachable("Translation units cannot be instantiated");
Douglas Gregor8a655532009-03-25 15:45:12 +0000661}
662
663Decl *
Nico Weber66220292016-03-02 17:28:48 +0000664TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
665 llvm_unreachable("pragma comment cannot be instantiated");
666}
667
Nico Webercbbaeb12016-03-02 19:28:54 +0000668Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
669 PragmaDetectMismatchDecl *D) {
670 llvm_unreachable("pragma comment cannot be instantiated");
671}
672
Nico Weber66220292016-03-02 17:28:48 +0000673Decl *
Richard Smithf19e1272015-03-07 00:04:49 +0000674TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
675 llvm_unreachable("extern \"C\" context cannot be instantiated");
676}
677
678Decl *
Chris Lattnercab02a62011-02-17 20:34:02 +0000679TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
680 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
681 D->getIdentifier());
682 Owner->addDecl(Inst);
683 return Inst;
684}
685
686Decl *
Douglas Gregor8a655532009-03-25 15:45:12 +0000687TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000688 llvm_unreachable("Namespaces cannot be instantiated");
Douglas Gregor8a655532009-03-25 15:45:12 +0000689}
690
John McCalld8d0d432010-02-16 06:53:13 +0000691Decl *
692TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
693 NamespaceAliasDecl *Inst
694 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
695 D->getNamespaceLoc(),
696 D->getAliasLoc(),
Douglas Gregorc05ba2e2011-02-25 17:08:07 +0000697 D->getIdentifier(),
698 D->getQualifierLoc(),
John McCalld8d0d432010-02-16 06:53:13 +0000699 D->getTargetNameLoc(),
700 D->getNamespace());
701 Owner->addDecl(Inst);
702 return Inst;
703}
704
Richard Smith3f1b5d02011-05-05 21:57:07 +0000705Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
706 bool IsTypeAlias) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000707 bool Invalid = false;
John McCallbcd03502009-12-07 02:54:59 +0000708 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor678d76c2011-07-01 01:22:09 +0000709 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor5a5073e2010-05-24 17:22:01 +0000710 DI->getType()->isVariablyModifiedType()) {
John McCall703a3f82009-10-24 08:00:42 +0000711 DI = SemaRef.SubstType(DI, TemplateArgs,
712 D->getLocation(), D->getDeclName());
713 if (!DI) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000714 Invalid = true;
John McCallbcd03502009-12-07 02:54:59 +0000715 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000716 }
Douglas Gregor5597ab42010-05-07 23:12:07 +0000717 } else {
718 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000719 }
Mike Stump11289f42009-09-09 15:08:12 +0000720
Richard Smith2ddcbab2012-10-23 00:32:41 +0000721 // HACK: g++ has a bug where it gets the value kind of ?: wrong.
722 // libstdc++ relies upon this bug in its implementation of common_type.
723 // If we happen to be processing that implementation, fake up the g++ ?:
724 // semantics. See LWG issue 2141 for more information on the bug.
725 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
726 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
727 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
728 DT->isReferenceType() &&
729 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
730 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
731 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000732 SemaRef.getSourceManager().isInSystemHeader(D->getBeginLoc()))
Richard Smith2ddcbab2012-10-23 00:32:41 +0000733 // Fold it to the (non-reference) type which g++ would have produced.
734 DI = SemaRef.Context.getTrivialTypeSourceInfo(
735 DI->getType().getNonReferenceType());
736
Douglas Gregord7e7a512009-03-17 21:15:40 +0000737 // Create the new typedef
Richard Smithdda56e42011-04-15 14:24:37 +0000738 TypedefNameDecl *Typedef;
739 if (IsTypeAlias)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000740 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
Richard Smithdda56e42011-04-15 14:24:37 +0000741 D->getLocation(), D->getIdentifier(), DI);
742 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000743 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
Richard Smithdda56e42011-04-15 14:24:37 +0000744 D->getLocation(), D->getIdentifier(), DI);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000745 if (Invalid)
746 Typedef->setInvalidDecl();
747
John McCall04fcd0d2011-02-01 08:20:08 +0000748 // If the old typedef was the name for linkage purposes of an anonymous
749 // tag decl, re-establish that relationship for the new typedef.
750 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
751 TagDecl *oldTag = oldTagType->getDecl();
Douglas Gregord831d952013-03-08 22:15:15 +0000752 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
John McCall04fcd0d2011-02-01 08:20:08 +0000753 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
John McCall5ea95772013-03-09 00:54:27 +0000754 assert(!newTag->hasNameForLinkage());
Richard Smithdda56e42011-04-15 14:24:37 +0000755 newTag->setTypedefNameForAnonDecl(Typedef);
John McCall04fcd0d2011-02-01 08:20:08 +0000756 }
Douglas Gregor83eb5032010-04-23 16:25:07 +0000757 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000758
Richard Smith41c79d92014-10-11 00:37:16 +0000759 if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000760 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
761 TemplateArgs);
Douglas Gregor55e6b312011-03-04 19:46:35 +0000762 if (!InstPrev)
Craig Topperc3ec1492014-05-26 06:22:03 +0000763 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000764
Rafael Espindolacde2c8f2011-12-26 22:42:47 +0000765 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
766
767 // If the typedef types are not identical, reject them.
768 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
769
Rafael Espindola8db352d2013-10-17 15:37:26 +0000770 Typedef->setPreviousDecl(InstPrevTypedef);
John McCall91f1a022009-12-30 00:31:22 +0000771 }
772
John McCall6602bb12010-08-01 02:01:53 +0000773 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
Douglas Gregor83eb5032010-04-23 16:25:07 +0000774
Matthias Gehref64f4882019-09-06 08:56:30 +0000775 if (D->getUnderlyingType()->getAs<DependentNameType>())
776 SemaRef.inferGslPointerAttribute(Typedef);
777
John McCall401982f2010-01-20 21:53:11 +0000778 Typedef->setAccess(D->getAccess());
Mike Stump11289f42009-09-09 15:08:12 +0000779
Douglas Gregord7e7a512009-03-17 21:15:40 +0000780 return Typedef;
781}
782
Richard Smithdda56e42011-04-15 14:24:37 +0000783Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000784 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
Richard Smith41c79d92014-10-11 00:37:16 +0000785 if (Typedef)
786 Owner->addDecl(Typedef);
Richard Smith3f1b5d02011-05-05 21:57:07 +0000787 return Typedef;
Richard Smithdda56e42011-04-15 14:24:37 +0000788}
789
790Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000791 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
Richard Smith41c79d92014-10-11 00:37:16 +0000792 if (Typedef)
793 Owner->addDecl(Typedef);
Richard Smith3f1b5d02011-05-05 21:57:07 +0000794 return Typedef;
795}
796
797Decl *
798TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
799 // Create a local instantiation scope for this type alias template, which
800 // will contain the instantiations of the template parameters.
801 LocalInstantiationScope Scope(SemaRef);
802
803 TemplateParameterList *TempParams = D->getTemplateParameters();
804 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
805 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +0000806 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000807
808 TypeAliasDecl *Pattern = D->getTemplatedDecl();
809
Craig Topperc3ec1492014-05-26 06:22:03 +0000810 TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
Richard Smith41c79d92014-10-11 00:37:16 +0000811 if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000812 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +0000813 if (!Found.empty()) {
814 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
Richard Smith3f1b5d02011-05-05 21:57:07 +0000815 }
816 }
817
818 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
819 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
820 if (!AliasInst)
Craig Topperc3ec1492014-05-26 06:22:03 +0000821 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000822
823 TypeAliasTemplateDecl *Inst
824 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
825 D->getDeclName(), InstParams, AliasInst);
Richard Smith43ccec8e2014-08-26 03:52:16 +0000826 AliasInst->setDescribedAliasTemplate(Inst);
Richard Smith3f1b5d02011-05-05 21:57:07 +0000827 if (PrevAliasTemplate)
Rafael Espindola8db352d2013-10-17 15:37:26 +0000828 Inst->setPreviousDecl(PrevAliasTemplate);
Richard Smith3f1b5d02011-05-05 21:57:07 +0000829
830 Inst->setAccess(D->getAccess());
831
832 if (!PrevAliasTemplate)
833 Inst->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000834
Richard Smith3f1b5d02011-05-05 21:57:07 +0000835 Owner->addDecl(Inst);
836
837 return Inst;
Richard Smithdda56e42011-04-15 14:24:37 +0000838}
839
Richard Smithbdb84f32016-07-22 23:36:59 +0000840Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) {
Richard Smith3997b1b2016-08-12 01:55:21 +0000841 auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(),
842 D->getIdentifier());
Richard Smith81df9eb2017-10-02 22:43:36 +0000843 NewBD->setReferenced(D->isReferenced());
Richard Smith3997b1b2016-08-12 01:55:21 +0000844 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewBD);
845 return NewBD;
Richard Smithbdb84f32016-07-22 23:36:59 +0000846}
847
848Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
Richard Smith3997b1b2016-08-12 01:55:21 +0000849 // Transform the bindings first.
850 SmallVector<BindingDecl*, 16> NewBindings;
851 for (auto *OldBD : D->bindings())
852 NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD)));
853 ArrayRef<BindingDecl*> NewBindingArray = NewBindings;
854
855 auto *NewDD = cast_or_null<DecompositionDecl>(
856 VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray));
857
858 if (!NewDD || NewDD->isInvalidDecl())
859 for (auto *NewBD : NewBindings)
860 NewBD->setInvalidDecl();
861
862 return NewDD;
Richard Smithbdb84f32016-07-22 23:36:59 +0000863}
864
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000865Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000866 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000867}
868
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000869Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
Richard Smith3997b1b2016-08-12 01:55:21 +0000870 bool InstantiatingVarTemplate,
871 ArrayRef<BindingDecl*> *Bindings) {
Larisse Voufo39a1e502013-08-06 01:03:05 +0000872
John McCall76d824f2009-08-25 22:02:44 +0000873 // Do substitution on the type of the declaration
Richard Smithee579842017-01-30 20:39:26 +0000874 TypeSourceInfo *DI = SemaRef.SubstType(
875 D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(),
876 D->getDeclName(), /*AllowDeducedTST*/true);
John McCallf1abcdc2009-10-21 02:39:02 +0000877 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +0000878 return nullptr;
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000879
Douglas Gregor61623342010-09-12 07:37:24 +0000880 if (DI->getType()->isFunctionType()) {
881 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
882 << D->isStaticDataMember() << DI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +0000883 return nullptr;
Douglas Gregor61623342010-09-12 07:37:24 +0000884 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000885
Richard Smith541b38b2013-09-20 01:15:31 +0000886 DeclContext *DC = Owner;
887 if (D->isLocalExternDecl())
888 SemaRef.adjustContextForLocalExternDecl(DC);
889
Larisse Voufo39a1e502013-08-06 01:03:05 +0000890 // Build the instantiated declaration.
Richard Smith3997b1b2016-08-12 01:55:21 +0000891 VarDecl *Var;
892 if (Bindings)
893 Var = DecompositionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
894 D->getLocation(), DI->getType(), DI,
895 D->getStorageClass(), *Bindings);
896 else
897 Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
898 D->getLocation(), D->getIdentifier(), DI->getType(),
899 DI, D->getStorageClass());
Mike Stump11289f42009-09-09 15:08:12 +0000900
Douglas Gregor8ca0c642011-12-10 01:22:52 +0000901 // In ARC, infer 'retaining' for variables of retainable type.
Fangrui Song6907ce22018-07-30 19:24:48 +0000902 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
Douglas Gregor8ca0c642011-12-10 01:22:52 +0000903 SemaRef.inferObjCARCLifetime(Var))
904 Var->setInvalidDecl();
905
Larisse Voufo39a1e502013-08-06 01:03:05 +0000906 // Substitute the nested name specifier, if any.
907 if (SubstQualifier(D, Var))
Craig Topperc3ec1492014-05-26 06:22:03 +0000908 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000909
Richard Smith541b38b2013-09-20 01:15:31 +0000910 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000911 StartingScope, InstantiatingVarTemplate);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +0000912
913 if (D->isNRVOVariable()) {
914 QualType ReturnType = cast<FunctionDecl>(DC)->getReturnType();
Richard Trieu09c163b2018-03-15 03:00:55 +0000915 if (SemaRef.isCopyElisionCandidate(ReturnType, Var, Sema::CES_Strict))
Taiju Tsuiki3be68e12018-06-19 05:35:30 +0000916 Var->setNRVOVariable(true);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +0000917 }
Taiju Tsuiki3be68e12018-06-19 05:35:30 +0000918
Alexander Kornienko83a4e182014-05-27 21:29:22 +0000919 Var->setImplicit(D->isImplicit());
920
Hans Wennborg262baa42018-10-31 10:34:46 +0000921 if (Var->isStaticLocal())
922 SemaRef.CheckStaticLocalForDllExport(Var);
923
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000924 return Var;
925}
926
Abramo Bagnarad7340582010-06-05 05:09:32 +0000927Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
928 AccessSpecDecl* AD
929 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
930 D->getAccessSpecifierLoc(), D->getColonLoc());
931 Owner->addHiddenDecl(AD);
932 return AD;
933}
934
Douglas Gregord7e7a512009-03-17 21:15:40 +0000935Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
936 bool Invalid = false;
John McCallbcd03502009-12-07 02:54:59 +0000937 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor678d76c2011-07-01 01:22:09 +0000938 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor5a5073e2010-05-24 17:22:01 +0000939 DI->getType()->isVariablyModifiedType()) {
John McCall90459c52009-10-22 23:33:21 +0000940 DI = SemaRef.SubstType(DI, TemplateArgs,
941 D->getLocation(), D->getDeclName());
942 if (!DI) {
John McCallbcd03502009-12-07 02:54:59 +0000943 DI = D->getTypeSourceInfo();
John McCall90459c52009-10-22 23:33:21 +0000944 Invalid = true;
945 } else if (DI->getType()->isFunctionType()) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000946 // C++ [temp.arg.type]p3:
947 // If a declaration acquires a function type through a type
948 // dependent on a template-parameter and this causes a
949 // declaration that does not use the syntactic form of a
950 // function declarator to have function type, the program is
951 // ill-formed.
952 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall90459c52009-10-22 23:33:21 +0000953 << DI->getType();
Douglas Gregord7e7a512009-03-17 21:15:40 +0000954 Invalid = true;
955 }
Douglas Gregor5597ab42010-05-07 23:12:07 +0000956 } else {
957 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000958 }
959
960 Expr *BitWidth = D->getBitWidth();
961 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +0000962 BitWidth = nullptr;
Douglas Gregord7e7a512009-03-17 21:15:40 +0000963 else if (BitWidth) {
Richard Smith764d2fe2011-12-20 02:08:33 +0000964 // The bit-width expression is a constant expression.
Faisal Valid143a0c2017-04-01 21:30:49 +0000965 EnterExpressionEvaluationContext Unevaluated(
966 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000967
John McCalldadc5752010-08-24 06:29:42 +0000968 ExprResult InstantiatedBitWidth
John McCall76d824f2009-08-25 22:02:44 +0000969 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000970 if (InstantiatedBitWidth.isInvalid()) {
971 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +0000972 BitWidth = nullptr;
Douglas Gregord7e7a512009-03-17 21:15:40 +0000973 } else
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000974 BitWidth = InstantiatedBitWidth.getAs<Expr>();
Douglas Gregord7e7a512009-03-17 21:15:40 +0000975 }
976
John McCall90459c52009-10-22 23:33:21 +0000977 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
978 DI->getType(), DI,
Mike Stump11289f42009-09-09 15:08:12 +0000979 cast<RecordDecl>(Owner),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000980 D->getLocation(),
981 D->isMutable(),
982 BitWidth,
Richard Smith2b013182012-06-10 03:12:00 +0000983 D->getInClassInitStyle(),
Richard Smith47ad0172012-05-23 04:22:22 +0000984 D->getInnerLocStart(),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000985 D->getAccess(),
Craig Topperc3ec1492014-05-26 06:22:03 +0000986 nullptr);
Douglas Gregor3c74d412009-10-14 20:14:33 +0000987 if (!Field) {
988 cast<Decl>(Owner)->setInvalidDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +0000989 return nullptr;
Douglas Gregor3c74d412009-10-14 20:14:33 +0000990 }
Mike Stump11289f42009-09-09 15:08:12 +0000991
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000992 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000993
Richard Smith848e1f12013-02-01 08:12:08 +0000994 if (Field->hasAttrs())
995 SemaRef.CheckAlignasUnderalignment(Field);
996
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000997 if (Invalid)
998 Field->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000999
Anders Carlsson2e56cc62009-09-02 19:17:55 +00001000 if (!Field->getDeclName()) {
1001 // Keep track of where this decl came from.
1002 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001003 }
Douglas Gregor04163182010-05-21 00:31:19 +00001004 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
1005 if (Parent->isAnonymousStructOrUnion() &&
Sebastian Redl50c68252010-08-31 00:36:30 +00001006 Parent->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor04163182010-05-21 00:31:19 +00001007 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregord7e7a512009-03-17 21:15:40 +00001008 }
Mike Stump11289f42009-09-09 15:08:12 +00001009
Anders Carlsson2e56cc62009-09-02 19:17:55 +00001010 Field->setImplicit(D->isImplicit());
John McCall401982f2010-01-20 21:53:11 +00001011 Field->setAccess(D->getAccess());
Anders Carlsson2e56cc62009-09-02 19:17:55 +00001012 Owner->addDecl(Field);
Douglas Gregord7e7a512009-03-17 21:15:40 +00001013
1014 return Field;
1015}
1016
John McCall5e77d762013-04-16 07:28:30 +00001017Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
1018 bool Invalid = false;
1019 TypeSourceInfo *DI = D->getTypeSourceInfo();
1020
1021 if (DI->getType()->isVariablyModifiedType()) {
1022 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
Aaron Ballman1bda4592014-01-03 01:09:27 +00001023 << D;
John McCall5e77d762013-04-16 07:28:30 +00001024 Invalid = true;
1025 } else if (DI->getType()->isInstantiationDependentType()) {
1026 DI = SemaRef.SubstType(DI, TemplateArgs,
1027 D->getLocation(), D->getDeclName());
1028 if (!DI) {
1029 DI = D->getTypeSourceInfo();
1030 Invalid = true;
1031 } else if (DI->getType()->isFunctionType()) {
1032 // C++ [temp.arg.type]p3:
1033 // If a declaration acquires a function type through a type
1034 // dependent on a template-parameter and this causes a
1035 // declaration that does not use the syntactic form of a
1036 // function declarator to have function type, the program is
1037 // ill-formed.
1038 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1039 << DI->getType();
1040 Invalid = true;
1041 }
1042 } else {
1043 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
1044 }
1045
Richard Smithf7981722013-11-22 09:01:48 +00001046 MSPropertyDecl *Property = MSPropertyDecl::Create(
1047 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001048 DI, D->getBeginLoc(), D->getGetterId(), D->getSetterId());
John McCall5e77d762013-04-16 07:28:30 +00001049
1050 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
1051 StartingScope);
1052
1053 if (Invalid)
1054 Property->setInvalidDecl();
1055
1056 Property->setAccess(D->getAccess());
1057 Owner->addDecl(Property);
1058
1059 return Property;
1060}
1061
Francois Pichet783dd6e2010-11-21 06:08:52 +00001062Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
1063 NamedDecl **NamedChain =
1064 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
1065
1066 int i = 0;
Aaron Ballman29c94602014-03-07 18:36:15 +00001067 for (auto *PI : D->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00001068 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
Douglas Gregor55e6b312011-03-04 19:46:35 +00001069 TemplateArgs);
1070 if (!Next)
Craig Topperc3ec1492014-05-26 06:22:03 +00001071 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001072
Douglas Gregor55e6b312011-03-04 19:46:35 +00001073 NamedChain[i++] = Next;
1074 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00001075
Francois Pichetdbafc192010-12-09 10:07:54 +00001076 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
Aaron Ballman260995b2014-10-15 16:58:18 +00001077 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
1078 SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
David Majnemer59f77922016-06-24 04:05:48 +00001079 {NamedChain, D->getChainingSize()});
Francois Pichet783dd6e2010-11-21 06:08:52 +00001080
NAKAMURA Takumi729be142014-10-27 12:37:26 +00001081 for (const auto *Attr : D->attrs())
1082 IndirectField->addAttr(Attr->clone(SemaRef.Context));
Francois Pichet783dd6e2010-11-21 06:08:52 +00001083
1084 IndirectField->setImplicit(D->isImplicit());
1085 IndirectField->setAccess(D->getAccess());
1086 Owner->addDecl(IndirectField);
1087 return IndirectField;
1088}
1089
John McCallaa74a0c2009-08-28 07:59:38 +00001090Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCallaa74a0c2009-08-28 07:59:38 +00001091 // Handle friend type expressions by simply substituting template
Douglas Gregor3b4abb62010-04-07 17:57:12 +00001092 // parameters into the pattern type and checking the result.
John McCall15ad0962010-03-25 18:04:51 +00001093 if (TypeSourceInfo *Ty = D->getFriendType()) {
Chandler Carruth08836322011-05-01 00:51:33 +00001094 TypeSourceInfo *InstTy;
1095 // If this is an unsupported friend, don't bother substituting template
1096 // arguments into it. The actual type referred to won't be used by any
1097 // parts of Clang, and may not be valid for instantiating. Just use the
1098 // same info for the instantiated friend.
1099 if (D->isUnsupportedFriend()) {
1100 InstTy = Ty;
1101 } else {
1102 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
1103 D->getLocation(), DeclarationName());
1104 }
1105 if (!InstTy)
Craig Topperc3ec1492014-05-26 06:22:03 +00001106 return nullptr;
John McCallaa74a0c2009-08-28 07:59:38 +00001107
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001108 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getBeginLoc(),
Abramo Bagnara254b6302011-10-29 20:52:52 +00001109 D->getFriendLoc(), InstTy);
Douglas Gregor3b4abb62010-04-07 17:57:12 +00001110 if (!FD)
Craig Topperc3ec1492014-05-26 06:22:03 +00001111 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001112
Douglas Gregor3b4abb62010-04-07 17:57:12 +00001113 FD->setAccess(AS_public);
John McCallace48cd2010-10-19 01:40:49 +00001114 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor3b4abb62010-04-07 17:57:12 +00001115 Owner->addDecl(FD);
1116 return FD;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001117 }
1118
Douglas Gregor3b4abb62010-04-07 17:57:12 +00001119 NamedDecl *ND = D->getFriendDecl();
1120 assert(ND && "friend decl must be a decl or a type!");
1121
John McCallb9c78482010-04-08 09:05:18 +00001122 // All of the Visit implementations for the various potential friend
1123 // declarations have to be carefully written to work for friend
1124 // objects, with the most important detail being that the target
1125 // decl should almost certainly not be placed in Owner.
1126 Decl *NewND = Visit(ND);
Craig Topperc3ec1492014-05-26 06:22:03 +00001127 if (!NewND) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001128
John McCallaa74a0c2009-08-28 07:59:38 +00001129 FriendDecl *FD =
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001130 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor3b4abb62010-04-07 17:57:12 +00001131 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall75c03bb2009-08-29 03:50:18 +00001132 FD->setAccess(AS_public);
John McCallace48cd2010-10-19 01:40:49 +00001133 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCallaa74a0c2009-08-28 07:59:38 +00001134 Owner->addDecl(FD);
1135 return FD;
John McCall58de3582009-08-14 02:03:10 +00001136}
1137
Douglas Gregord7e7a512009-03-17 21:15:40 +00001138Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
1139 Expr *AssertExpr = D->getAssertExpr();
Mike Stump11289f42009-09-09 15:08:12 +00001140
Richard Smith764d2fe2011-12-20 02:08:33 +00001141 // The expression in a static assertion is a constant expression.
Faisal Valid143a0c2017-04-01 21:30:49 +00001142 EnterExpressionEvaluationContext Unevaluated(
1143 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +00001144
John McCalldadc5752010-08-24 06:29:42 +00001145 ExprResult InstantiatedAssertExpr
John McCall76d824f2009-08-25 22:02:44 +00001146 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregord7e7a512009-03-17 21:15:40 +00001147 if (InstantiatedAssertExpr.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00001148 return nullptr;
Douglas Gregord7e7a512009-03-17 21:15:40 +00001149
Richard Smithded9c2e2012-07-11 22:37:56 +00001150 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
John McCallb268a282010-08-23 23:25:46 +00001151 InstantiatedAssertExpr.get(),
Richard Smithded9c2e2012-07-11 22:37:56 +00001152 D->getMessage(),
1153 D->getRParenLoc(),
1154 D->isFailed());
Douglas Gregord7e7a512009-03-17 21:15:40 +00001155}
1156
1157Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001158 EnumDecl *PrevDecl = nullptr;
Richard Smith41c79d92014-10-11 00:37:16 +00001159 if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
Richard Smith2e6610a2012-03-26 04:58:10 +00001160 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
Richard Smith41c79d92014-10-11 00:37:16 +00001161 PatternPrev,
Richard Smith2e6610a2012-03-26 04:58:10 +00001162 TemplateArgs);
Craig Topperc3ec1492014-05-26 06:22:03 +00001163 if (!Prev) return nullptr;
Richard Smith2e6610a2012-03-26 04:58:10 +00001164 PrevDecl = cast<EnumDecl>(Prev);
1165 }
1166
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001167 EnumDecl *Enum =
1168 EnumDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1169 D->getLocation(), D->getIdentifier(), PrevDecl,
1170 D->isScoped(), D->isScopedUsingClassTag(), D->isFixed());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001171 if (D->isFixed()) {
Richard Smith4b38ded2012-03-14 23:13:10 +00001172 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00001173 // If we have type source information for the underlying type, it means it
1174 // has been explicitly set by the user. Perform substitution on it before
1175 // moving on.
1176 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
Richard Smith4b38ded2012-03-14 23:13:10 +00001177 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
1178 DeclarationName());
1179 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
Douglas Gregor0bf31402010-10-08 23:50:27 +00001180 Enum->setIntegerType(SemaRef.Context.IntTy);
Richard Smith4b38ded2012-03-14 23:13:10 +00001181 else
1182 Enum->setIntegerTypeSourceInfo(NewTI);
1183 } else {
Douglas Gregor0bf31402010-10-08 23:50:27 +00001184 assert(!D->getIntegerType()->isDependentType()
1185 && "Dependent type without type source info");
1186 Enum->setIntegerType(D->getIntegerType());
1187 }
1188 }
1189
John McCall811a0f52010-10-22 23:36:17 +00001190 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
1191
Richard Smith4b38ded2012-03-14 23:13:10 +00001192 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
Douglas Gregor6c2adff2009-03-25 22:00:53 +00001193 Enum->setAccess(D->getAccess());
David Majnemerdbc0c8f2013-12-04 09:01:55 +00001194 // Forward the mangling number from the template to the instantiated decl.
1195 SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
David Majnemer00350522015-08-31 18:48:39 +00001196 // See if the old tag was defined along with a declarator.
1197 // If it did, mark the new tag as being associated with that declarator.
1198 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1199 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD);
1200 // See if the old tag was defined along with a typedef.
1201 // If it did, mark the new tag as being associated with that typedef.
1202 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1203 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND);
Craig Topperc3ec1492014-05-26 06:22:03 +00001204 if (SubstQualifier(D, Enum)) return nullptr;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001205 Owner->addDecl(Enum);
Richard Smith4b38ded2012-03-14 23:13:10 +00001206
Richard Smith258a7442012-03-26 04:08:46 +00001207 EnumDecl *Def = D->getDefinition();
1208 if (Def && Def != D) {
1209 // If this is an out-of-line definition of an enum member template, check
1210 // that the underlying types match in the instantiation of both
1211 // declarations.
1212 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
1213 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1214 QualType DefnUnderlying =
1215 SemaRef.SubstType(TI->getType(), TemplateArgs,
1216 UnderlyingLoc, DeclarationName());
1217 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
Reid Klecknerb0a17ed2018-02-12 17:37:06 +00001218 DefnUnderlying, /*IsFixed=*/true, Enum);
Richard Smith258a7442012-03-26 04:08:46 +00001219 }
1220 }
Douglas Gregord7e7a512009-03-17 21:15:40 +00001221
Richard Smith4b38ded2012-03-14 23:13:10 +00001222 // C++11 [temp.inst]p1: The implicit instantiation of a class template
1223 // specialization causes the implicit instantiation of the declarations, but
1224 // not the definitions of scoped member enumerations.
David Majnemer192d1792013-11-27 08:20:38 +00001225 //
1226 // DR1484 clarifies that enumeration definitions inside of a template
1227 // declaration aren't considered entities that can be separately instantiated
1228 // from the rest of the entity they are declared inside of.
1229 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
1230 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
Richard Smith258a7442012-03-26 04:08:46 +00001231 InstantiateEnumDefinition(Enum, Def);
David Majnemer192d1792013-11-27 08:20:38 +00001232 }
Richard Smith4b38ded2012-03-14 23:13:10 +00001233
1234 return Enum;
1235}
1236
1237void TemplateDeclInstantiator::InstantiateEnumDefinition(
1238 EnumDecl *Enum, EnumDecl *Pattern) {
1239 Enum->startDefinition();
1240
Richard Smith7d137e32012-03-23 03:33:32 +00001241 // Update the location to refer to the definition.
1242 Enum->setLocation(Pattern->getLocation());
1243
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001244 SmallVector<Decl*, 4> Enumerators;
Douglas Gregord7e7a512009-03-17 21:15:40 +00001245
Craig Topperc3ec1492014-05-26 06:22:03 +00001246 EnumConstantDecl *LastEnumConst = nullptr;
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001247 for (auto *EC : Pattern->enumerators()) {
Douglas Gregord7e7a512009-03-17 21:15:40 +00001248 // The specified value for the enumerator.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001249 ExprResult Value((Expr *)nullptr);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00001250 if (Expr *UninstValue = EC->getInitExpr()) {
Richard Smith764d2fe2011-12-20 02:08:33 +00001251 // The enumerator's value expression is a constant expression.
Faisal Valid143a0c2017-04-01 21:30:49 +00001252 EnterExpressionEvaluationContext Unevaluated(
1253 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +00001254
John McCall76d824f2009-08-25 22:02:44 +00001255 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00001256 }
Douglas Gregord7e7a512009-03-17 21:15:40 +00001257
1258 // Drop the initial value and continue.
1259 bool isInvalid = false;
1260 if (Value.isInvalid()) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001261 Value = nullptr;
Douglas Gregord7e7a512009-03-17 21:15:40 +00001262 isInvalid = true;
1263 }
1264
Mike Stump11289f42009-09-09 15:08:12 +00001265 EnumConstantDecl *EnumConst
Douglas Gregord7e7a512009-03-17 21:15:40 +00001266 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
1267 EC->getLocation(), EC->getIdentifier(),
John McCallb268a282010-08-23 23:25:46 +00001268 Value.get());
Douglas Gregord7e7a512009-03-17 21:15:40 +00001269
1270 if (isInvalid) {
1271 if (EnumConst)
1272 EnumConst->setInvalidDecl();
1273 Enum->setInvalidDecl();
1274 }
1275
1276 if (EnumConst) {
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001277 SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
John McCall811a0f52010-10-22 23:36:17 +00001278
John McCallf9b528c2010-01-23 22:37:59 +00001279 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001280 Enum->addDecl(EnumConst);
John McCall48871652010-08-21 09:40:31 +00001281 Enumerators.push_back(EnumConst);
Douglas Gregord7e7a512009-03-17 21:15:40 +00001282 LastEnumConst = EnumConst;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001283
Richard Smith4b38ded2012-03-14 23:13:10 +00001284 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
1285 !Enum->isScoped()) {
Douglas Gregoraff9c1a2010-03-01 19:00:07 +00001286 // If the enumeration is within a function or method, record the enum
1287 // constant as a local.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001288 SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
Douglas Gregoraff9c1a2010-03-01 19:00:07 +00001289 }
Douglas Gregord7e7a512009-03-17 21:15:40 +00001290 }
1291 }
Mike Stump11289f42009-09-09 15:08:12 +00001292
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00001293 SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
Erich Keanec480f302018-07-12 21:09:05 +00001294 Enumerators, nullptr, ParsedAttributesView());
Douglas Gregord7e7a512009-03-17 21:15:40 +00001295}
1296
Douglas Gregor9106b822009-03-25 15:04:13 +00001297Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +00001298 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
Douglas Gregor9106b822009-03-25 15:04:13 +00001299}
1300
David Majnemerd9b1a4f2015-11-04 03:40:30 +00001301Decl *
1302TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
1303 llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
1304}
1305
John McCall87a44eb2009-08-20 01:44:21 +00001306Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall598b4402010-03-25 06:39:04 +00001307 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1308
Douglas Gregor954de172009-10-31 17:21:17 +00001309 // Create a local instantiation scope for this class template, which
1310 // will contain the instantiations of the template parameters.
John McCall19c1bfd2010-08-25 05:32:35 +00001311 LocalInstantiationScope Scope(SemaRef);
John McCall87a44eb2009-08-20 01:44:21 +00001312 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCall76d824f2009-08-25 22:02:44 +00001313 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump11289f42009-09-09 15:08:12 +00001314 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00001315 return nullptr;
John McCall87a44eb2009-08-20 01:44:21 +00001316
1317 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall598b4402010-03-25 06:39:04 +00001318
1319 // Instantiate the qualifier. We have to do this first in case
1320 // we're a friend declaration, because if we are then we need to put
1321 // the new declaration in the appropriate context.
Douglas Gregor14454802011-02-25 02:25:35 +00001322 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
1323 if (QualifierLoc) {
1324 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1325 TemplateArgs);
1326 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00001327 return nullptr;
John McCall598b4402010-03-25 06:39:04 +00001328 }
1329
Craig Topperc3ec1492014-05-26 06:22:03 +00001330 CXXRecordDecl *PrevDecl = nullptr;
1331 ClassTemplateDecl *PrevClassTemplate = nullptr;
John McCall598b4402010-03-25 06:39:04 +00001332
Richard Smith41c79d92014-10-11 00:37:16 +00001333 if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
Nick Lewycky61478912010-11-08 23:29:42 +00001334 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +00001335 if (!Found.empty()) {
1336 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
Nick Lewycky61478912010-11-08 23:29:42 +00001337 if (PrevClassTemplate)
1338 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1339 }
1340 }
1341
John McCall598b4402010-03-25 06:39:04 +00001342 // If this isn't a friend, then it's a member template, in which
1343 // case we just want to build the instantiation in the
1344 // specialization. If it is a friend, we want to build it in
1345 // the appropriate context.
1346 DeclContext *DC = Owner;
1347 if (isFriend) {
Douglas Gregor14454802011-02-25 02:25:35 +00001348 if (QualifierLoc) {
John McCall598b4402010-03-25 06:39:04 +00001349 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +00001350 SS.Adopt(QualifierLoc);
John McCall598b4402010-03-25 06:39:04 +00001351 DC = SemaRef.computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +00001352 if (!DC) return nullptr;
John McCall598b4402010-03-25 06:39:04 +00001353 } else {
1354 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
1355 Pattern->getDeclContext(),
1356 TemplateArgs);
1357 }
1358
1359 // Look for a previous declaration of the template in the owning
1360 // context.
1361 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
Richard Smithbecb92d2017-10-10 22:33:17 +00001362 Sema::LookupOrdinaryName,
1363 SemaRef.forRedeclarationInCurContext());
John McCall598b4402010-03-25 06:39:04 +00001364 SemaRef.LookupQualifiedName(R, DC);
1365
1366 if (R.isSingleResult()) {
1367 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
1368 if (PrevClassTemplate)
1369 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1370 }
1371
Douglas Gregor14454802011-02-25 02:25:35 +00001372 if (!PrevClassTemplate && QualifierLoc) {
John McCall598b4402010-03-25 06:39:04 +00001373 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregorf5af3582010-03-31 23:17:41 +00001374 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
Douglas Gregor14454802011-02-25 02:25:35 +00001375 << QualifierLoc.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00001376 return nullptr;
John McCall598b4402010-03-25 06:39:04 +00001377 }
1378
Douglas Gregor01e09d92010-04-08 18:16:15 +00001379 bool AdoptedPreviousTemplateParams = false;
John McCall598b4402010-03-25 06:39:04 +00001380 if (PrevClassTemplate) {
Douglas Gregor01e09d92010-04-08 18:16:15 +00001381 bool Complain = true;
1382
1383 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
1384 // template for struct std::tr1::__detail::_Map_base, where the
1385 // template parameters of the friend declaration don't match the
1386 // template parameters of the original declaration. In this one
1387 // case, we don't complain about the ill-formed friend
1388 // declaration.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001389 if (isFriend && Pattern->getIdentifier() &&
Douglas Gregor01e09d92010-04-08 18:16:15 +00001390 Pattern->getIdentifier()->isStr("_Map_base") &&
1391 DC->isNamespace() &&
1392 cast<NamespaceDecl>(DC)->getIdentifier() &&
1393 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
1394 DeclContext *DCParent = DC->getParent();
1395 if (DCParent->isNamespace() &&
1396 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
1397 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
Richard Trieuc771d5d2014-05-28 02:16:01 +00001398 if (cast<Decl>(DCParent)->isInStdNamespace())
Douglas Gregor01e09d92010-04-08 18:16:15 +00001399 Complain = false;
1400 }
1401 }
1402
John McCall598b4402010-03-25 06:39:04 +00001403 TemplateParameterList *PrevParams
Richard Smithc4577662018-09-12 02:13:47 +00001404 = PrevClassTemplate->getMostRecentDecl()->getTemplateParameters();
John McCall598b4402010-03-25 06:39:04 +00001405
1406 // Make sure the parameter lists match.
1407 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001408 Complain,
Douglas Gregor01e09d92010-04-08 18:16:15 +00001409 Sema::TPL_TemplateMatch)) {
1410 if (Complain)
Craig Topperc3ec1492014-05-26 06:22:03 +00001411 return nullptr;
Douglas Gregor01e09d92010-04-08 18:16:15 +00001412
1413 AdoptedPreviousTemplateParams = true;
1414 InstParams = PrevParams;
1415 }
John McCall598b4402010-03-25 06:39:04 +00001416
1417 // Do some additional validation, then merge default arguments
1418 // from the existing declarations.
Douglas Gregor01e09d92010-04-08 18:16:15 +00001419 if (!AdoptedPreviousTemplateParams &&
1420 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall598b4402010-03-25 06:39:04 +00001421 Sema::TPC_ClassTemplate))
Craig Topperc3ec1492014-05-26 06:22:03 +00001422 return nullptr;
John McCall598b4402010-03-25 06:39:04 +00001423 }
1424 }
1425
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001426 CXXRecordDecl *RecordInst = CXXRecordDecl::Create(
1427 SemaRef.Context, Pattern->getTagKind(), DC, Pattern->getBeginLoc(),
1428 Pattern->getLocation(), Pattern->getIdentifier(), PrevDecl,
1429 /*DelayTypeCreation=*/true);
John McCall87a44eb2009-08-20 01:44:21 +00001430
Douglas Gregor14454802011-02-25 02:25:35 +00001431 if (QualifierLoc)
1432 RecordInst->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +00001433
Louis Dionne3c011e12018-09-14 14:07:16 +00001434 SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs,
1435 StartingScope);
1436
John McCall87a44eb2009-08-20 01:44:21 +00001437 ClassTemplateDecl *Inst
John McCall598b4402010-03-25 06:39:04 +00001438 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
Vassil Vassilev352e4412017-01-12 09:16:26 +00001439 D->getIdentifier(), InstParams, RecordInst);
1440 assert(!(isFriend && Owner->isDependentContext()));
1441 Inst->setPreviousDecl(PrevClassTemplate);
1442
John McCall87a44eb2009-08-20 01:44:21 +00001443 RecordInst->setDescribedClassTemplate(Inst);
John McCall17762b82010-04-08 20:25:50 +00001444
John McCall598b4402010-03-25 06:39:04 +00001445 if (isFriend) {
John McCall17762b82010-04-08 20:25:50 +00001446 if (PrevClassTemplate)
1447 Inst->setAccess(PrevClassTemplate->getAccess());
1448 else
1449 Inst->setAccess(D->getAccess());
1450
Richard Smith64017682013-07-17 23:53:16 +00001451 Inst->setObjectOfFriendDecl();
John McCall598b4402010-03-25 06:39:04 +00001452 // TODO: do we want to track the instantiation progeny of this
1453 // friend target decl?
1454 } else {
Douglas Gregor412e8bc2009-10-30 21:07:27 +00001455 Inst->setAccess(D->getAccess());
Nick Lewycky61478912010-11-08 23:29:42 +00001456 if (!PrevClassTemplate)
1457 Inst->setInstantiatedFromMemberTemplate(D);
John McCall598b4402010-03-25 06:39:04 +00001458 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001459
Douglas Gregoref06ccf2009-10-12 23:11:44 +00001460 // Trigger creation of the type for the instantiation.
John McCalle78aac42010-03-10 03:28:59 +00001461 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor9961ce92010-07-08 18:37:38 +00001462 Inst->getInjectedClassNameSpecialization());
John McCall17762b82010-04-08 20:25:50 +00001463
Douglas Gregorbb3b46e2009-10-30 22:42:42 +00001464 // Finish handling of friends.
John McCall598b4402010-03-25 06:39:04 +00001465 if (isFriend) {
Richard Smith05afe5e2012-03-13 03:12:56 +00001466 DC->makeDeclVisibleInContext(Inst);
Abramo Bagnaraedf99ff2011-11-26 13:33:46 +00001467 Inst->setLexicalDeclContext(Owner);
1468 RecordInst->setLexicalDeclContext(Owner);
Douglas Gregor412e8bc2009-10-30 21:07:27 +00001469 return Inst;
Douglas Gregorbb3b46e2009-10-30 22:42:42 +00001470 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001471
Abramo Bagnaraedf99ff2011-11-26 13:33:46 +00001472 if (D->isOutOfLine()) {
1473 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1474 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
1475 }
1476
John McCall87a44eb2009-08-20 01:44:21 +00001477 Owner->addDecl(Inst);
Douglas Gregor869853e2010-11-10 19:44:59 +00001478
1479 if (!PrevClassTemplate) {
1480 // Queue up any out-of-line partial specializations of this member
1481 // class template; the client will force their instantiation once
1482 // the enclosing class has been instantiated.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001483 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregor869853e2010-11-10 19:44:59 +00001484 D->getPartialSpecializations(PartialSpecs);
1485 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
Rafael Espindola8db352d2013-10-17 15:37:26 +00001486 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
Douglas Gregor869853e2010-11-10 19:44:59 +00001487 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
1488 }
1489
John McCall87a44eb2009-08-20 01:44:21 +00001490 return Inst;
1491}
1492
Douglas Gregore704c9d2009-08-27 16:57:43 +00001493Decl *
Douglas Gregore4b05162009-10-07 17:21:34 +00001494TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1495 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregor21610382009-10-29 00:04:11 +00001496 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001497
Douglas Gregor21610382009-10-29 00:04:11 +00001498 // Lookup the already-instantiated declaration in the instantiation
1499 // of the class template and return that.
1500 DeclContext::lookup_result Found
1501 = Owner->lookup(ClassTemplate->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +00001502 if (Found.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +00001503 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001504
Douglas Gregor21610382009-10-29 00:04:11 +00001505 ClassTemplateDecl *InstClassTemplate
David Blaikieff7d47a2012-12-19 00:45:41 +00001506 = dyn_cast<ClassTemplateDecl>(Found.front());
Douglas Gregor21610382009-10-29 00:04:11 +00001507 if (!InstClassTemplate)
Craig Topperc3ec1492014-05-26 06:22:03 +00001508 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001509
Douglas Gregor869853e2010-11-10 19:44:59 +00001510 if (ClassTemplatePartialSpecializationDecl *Result
1511 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1512 return Result;
1513
1514 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregore4b05162009-10-07 17:21:34 +00001515}
1516
Larisse Voufo39a1e502013-08-06 01:03:05 +00001517Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1518 assert(D->getTemplatedDecl()->isStaticDataMember() &&
1519 "Only static data member templates are allowed.");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001520
1521 // Create a local instantiation scope for this variable template, which
1522 // will contain the instantiations of the template parameters.
1523 LocalInstantiationScope Scope(SemaRef);
1524 TemplateParameterList *TempParams = D->getTemplateParameters();
1525 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1526 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00001527 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00001528
1529 VarDecl *Pattern = D->getTemplatedDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00001530 VarTemplateDecl *PrevVarTemplate = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00001531
Richard Smith41c79d92014-10-11 00:37:16 +00001532 if (getPreviousDeclForInstantiation(Pattern)) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00001533 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1534 if (!Found.empty())
1535 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1536 }
1537
Richard Smith1c34fb72013-08-13 18:18:50 +00001538 VarDecl *VarInst =
Larisse Voufo72caf2b2013-08-22 00:59:14 +00001539 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1540 /*InstantiatingVarTemplate=*/true));
Nick Lewycky6ca07ca2015-08-10 21:54:08 +00001541 if (!VarInst) return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00001542
1543 DeclContext *DC = Owner;
1544
Larisse Voufo39a1e502013-08-06 01:03:05 +00001545 VarTemplateDecl *Inst = VarTemplateDecl::Create(
1546 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
Richard Smithbeef3452014-01-16 23:39:20 +00001547 VarInst);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001548 VarInst->setDescribedVarTemplate(Inst);
Richard Smithbeef3452014-01-16 23:39:20 +00001549 Inst->setPreviousDecl(PrevVarTemplate);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001550
1551 Inst->setAccess(D->getAccess());
1552 if (!PrevVarTemplate)
1553 Inst->setInstantiatedFromMemberTemplate(D);
1554
1555 if (D->isOutOfLine()) {
1556 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1557 VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1558 }
1559
1560 Owner->addDecl(Inst);
1561
1562 if (!PrevVarTemplate) {
1563 // Queue up any out-of-line partial specializations of this member
1564 // variable template; the client will force their instantiation once
1565 // the enclosing class has been instantiated.
1566 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1567 D->getPartialSpecializations(PartialSpecs);
1568 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
Rafael Espindola8db352d2013-10-17 15:37:26 +00001569 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
Larisse Voufo39a1e502013-08-06 01:03:05 +00001570 OutOfLineVarPartialSpecs.push_back(
1571 std::make_pair(Inst, PartialSpecs[I]));
1572 }
1573
1574 return Inst;
1575}
1576
1577Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1578 VarTemplatePartialSpecializationDecl *D) {
1579 assert(D->isStaticDataMember() &&
1580 "Only static data member templates are allowed.");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001581
1582 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1583
1584 // Lookup the already-instantiated declaration and return that.
1585 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1586 assert(!Found.empty() && "Instantiation found nothing?");
1587
1588 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1589 assert(InstVarTemplate && "Instantiation did not find a variable template?");
1590
1591 if (VarTemplatePartialSpecializationDecl *Result =
1592 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1593 return Result;
1594
1595 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1596}
1597
Douglas Gregore4b05162009-10-07 17:21:34 +00001598Decl *
Douglas Gregore704c9d2009-08-27 16:57:43 +00001599TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor954de172009-10-31 17:21:17 +00001600 // Create a local instantiation scope for this function template, which
1601 // will contain the instantiations of the template parameters and then get
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001602 // merged with the local instantiation scope for the function template
Douglas Gregor954de172009-10-31 17:21:17 +00001603 // itself.
John McCall19c1bfd2010-08-25 05:32:35 +00001604 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor14cf7522010-04-30 18:55:50 +00001605
Douglas Gregore704c9d2009-08-27 16:57:43 +00001606 TemplateParameterList *TempParams = D->getTemplateParameters();
1607 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump11289f42009-09-09 15:08:12 +00001608 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00001609 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001610
Craig Topperc3ec1492014-05-26 06:22:03 +00001611 FunctionDecl *Instantiated = nullptr;
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001612 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001613 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001614 InstParams));
1615 else
1616 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001617 D->getTemplatedDecl(),
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001618 InstParams));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001619
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001620 if (!Instantiated)
Craig Topperc3ec1492014-05-26 06:22:03 +00001621 return nullptr;
Douglas Gregore704c9d2009-08-27 16:57:43 +00001622
Mike Stump11289f42009-09-09 15:08:12 +00001623 // Link the instantiated function template declaration to the function
Douglas Gregore704c9d2009-08-27 16:57:43 +00001624 // template from which it was instantiated.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001625 FunctionTemplateDecl *InstTemplate
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001626 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregorca027af2009-10-12 22:27:17 +00001627 InstTemplate->setAccess(D->getAccess());
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001628 assert(InstTemplate &&
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001629 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCall2079d0b2009-12-14 23:19:40 +00001630
John McCall30837102010-03-26 23:10:15 +00001631 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1632
John McCall2079d0b2009-12-14 23:19:40 +00001633 // Link the instantiation back to the pattern *unless* this is a
1634 // non-definition friend declaration.
1635 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCall30837102010-03-26 23:10:15 +00001636 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001637 InstTemplate->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001638
John McCall30837102010-03-26 23:10:15 +00001639 // Make declarations visible in the appropriate context.
John McCalla0a96892012-08-10 03:15:35 +00001640 if (!isFriend) {
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001641 Owner->addDecl(InstTemplate);
John McCalla0a96892012-08-10 03:15:35 +00001642 } else if (InstTemplate->getDeclContext()->isRecord() &&
Richard Smith41c79d92014-10-11 00:37:16 +00001643 !getPreviousDeclForInstantiation(D)) {
John McCalla0a96892012-08-10 03:15:35 +00001644 SemaRef.CheckFriendAccess(InstTemplate);
1645 }
John McCall30837102010-03-26 23:10:15 +00001646
Douglas Gregore704c9d2009-08-27 16:57:43 +00001647 return InstTemplate;
1648}
1649
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001650Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001651 CXXRecordDecl *PrevDecl = nullptr;
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001652 if (D->isInjectedClassName())
1653 PrevDecl = cast<CXXRecordDecl>(Owner);
Richard Smith41c79d92014-10-11 00:37:16 +00001654 else if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001655 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
Richard Smith41c79d92014-10-11 00:37:16 +00001656 PatternPrev,
John McCalle9f92a02009-12-15 22:29:06 +00001657 TemplateArgs);
Craig Topperc3ec1492014-05-26 06:22:03 +00001658 if (!Prev) return nullptr;
John McCalle9f92a02009-12-15 22:29:06 +00001659 PrevDecl = cast<CXXRecordDecl>(Prev);
1660 }
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001661
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001662 CXXRecordDecl *Record = CXXRecordDecl::Create(
1663 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
1664 D->getLocation(), D->getIdentifier(), PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00001665
1666 // Substitute the nested name specifier, if any.
1667 if (SubstQualifier(D, Record))
Craig Topperc3ec1492014-05-26 06:22:03 +00001668 return nullptr;
John McCall3e11ebe2010-03-15 10:12:16 +00001669
Louis Dionne3c011e12018-09-14 14:07:16 +00001670 SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs,
1671 StartingScope);
1672
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001673 Record->setImplicit(D->isImplicit());
Eli Friedmanbda4ef12009-08-27 19:11:42 +00001674 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1675 // the tag decls introduced by friend class declarations don't have an access
1676 // specifier. Remove once this area of the code gets sorted out.
1677 if (D->getAccess() != AS_none)
1678 Record->setAccess(D->getAccess());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001679 if (!D->isInjectedClassName())
Douglas Gregorbbe8f462009-10-08 15:14:33 +00001680 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001681
John McCallaa74a0c2009-08-28 07:59:38 +00001682 // If the original function was part of a friend declaration,
1683 // inherit its namespace state.
Richard Smith64017682013-07-17 23:53:16 +00001684 if (D->getFriendObjectKind())
1685 Record->setObjectOfFriendDecl();
John McCallaa74a0c2009-08-28 07:59:38 +00001686
Douglas Gregor04163182010-05-21 00:31:19 +00001687 // Make sure that anonymous structs and unions are recorded.
David Majnemer192d1792013-11-27 08:20:38 +00001688 if (D->isAnonymousStructOrUnion())
Douglas Gregor04163182010-05-21 00:31:19 +00001689 Record->setAnonymousStructOrUnion(true);
David Majnemer192d1792013-11-27 08:20:38 +00001690
1691 if (D->isLocalClass())
1692 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
Anders Carlsson5da84842009-09-01 04:26:58 +00001693
David Majnemerdbc0c8f2013-12-04 09:01:55 +00001694 // Forward the mangling number from the template to the instantiated decl.
1695 SemaRef.Context.setManglingNumber(Record,
1696 SemaRef.Context.getManglingNumber(D));
1697
David Majnemer00350522015-08-31 18:48:39 +00001698 // See if the old tag was defined along with a declarator.
1699 // If it did, mark the new tag as being associated with that declarator.
1700 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1701 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD);
1702
1703 // See if the old tag was defined along with a typedef.
1704 // If it did, mark the new tag as being associated with that typedef.
1705 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1706 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND);
1707
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001708 Owner->addDecl(Record);
David Majnemer192d1792013-11-27 08:20:38 +00001709
1710 // DR1484 clarifies that the members of a local class are instantiated as part
1711 // of the instantiation of their enclosing entity.
1712 if (D->isCompleteDefinition() && D->isLocalClass()) {
Richard Smith4f3e3812017-05-20 01:36:41 +00001713 Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef);
Richard Smithb0b68012015-05-11 23:09:06 +00001714
David Majnemera64cb5a2014-02-22 00:17:46 +00001715 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1716 TSK_ImplicitInstantiation,
1717 /*Complain=*/true);
Richard Smithb0b68012015-05-11 23:09:06 +00001718
Richard Smithece47582017-01-04 23:45:01 +00001719 // For nested local classes, we will instantiate the members when we
1720 // reach the end of the outermost (non-nested) local class.
1721 if (!D->isCXXClassMember())
1722 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1723 TSK_ImplicitInstantiation);
Richard Smithb0b68012015-05-11 23:09:06 +00001724
1725 // This class may have local implicit instantiations that need to be
1726 // performed within this scope.
Richard Smith4f3e3812017-05-20 01:36:41 +00001727 LocalInstantiations.perform();
David Majnemer192d1792013-11-27 08:20:38 +00001728 }
Nico Weber72889432014-09-06 01:25:55 +00001729
1730 SemaRef.DiagnoseUnusedNestedTypedefs(Record);
1731
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001732 return Record;
1733}
1734
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001735/// Adjust the given function type for an instantiation of the
Douglas Gregor89f593a2012-09-13 21:56:43 +00001736/// given declaration, to cope with modifications to the function's type that
1737/// aren't reflected in the type-source information.
1738///
1739/// \param D The declaration we're instantiating.
1740/// \param TInfo The already-instantiated type.
1741static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1742 FunctionDecl *D,
1743 TypeSourceInfo *TInfo) {
Douglas Gregor1af8ad42012-09-13 22:01:49 +00001744 const FunctionProtoType *OrigFunc
1745 = D->getType()->castAs<FunctionProtoType>();
1746 const FunctionProtoType *NewFunc
1747 = TInfo->getType()->castAs<FunctionProtoType>();
1748 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1749 return TInfo->getType();
1750
1751 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1752 NewEPI.ExtInfo = OrigFunc->getExtInfo();
Alp Toker314cc812014-01-25 16:55:45 +00001753 return Context.getFunctionType(NewFunc->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00001754 NewFunc->getParamTypes(), NewEPI);
Douglas Gregor89f593a2012-09-13 21:56:43 +00001755}
1756
John McCallaa74a0c2009-08-28 07:59:38 +00001757/// Normal class members are of more specific types and therefore
Richard Smith4fa145152017-12-21 19:43:39 +00001758/// don't make it here. This function serves three purposes:
John McCallaa74a0c2009-08-28 07:59:38 +00001759/// 1) instantiating function templates
1760/// 2) substituting friend declarations
Richard Smith4fa145152017-12-21 19:43:39 +00001761/// 3) substituting deduction guide declarations for nested class templates
Douglas Gregor33636e62009-12-24 20:56:24 +00001762Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001763 TemplateParameterList *TemplateParams) {
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001764 // Check whether there is already a function template specialization for
1765 // this declaration.
1766 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
John McCall2f88d7d2010-03-27 05:57:59 +00001767 if (FunctionTemplate && !TemplateParams) {
Richard Smith47752e42013-05-03 23:46:09 +00001768 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump11289f42009-09-09 15:08:12 +00001769
Craig Topperc3ec1492014-05-26 06:22:03 +00001770 void *InsertPos = nullptr;
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001771 FunctionDecl *SpecFunc
Craig Topper7e0daca2014-06-26 04:58:53 +00001772 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001773
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001774 // If we already have a function template specialization, return it.
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001775 if (SpecFunc)
1776 return SpecFunc;
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001777 }
Mike Stump11289f42009-09-09 15:08:12 +00001778
John McCall2f88d7d2010-03-27 05:57:59 +00001779 bool isFriend;
1780 if (FunctionTemplate)
1781 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1782 else
1783 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1784
Craig Topperc3ec1492014-05-26 06:22:03 +00001785 bool MergeWithParentScope = (TemplateParams != nullptr) ||
Douglas Gregor9f44d142010-05-21 21:25:08 +00001786 Owner->isFunctionOrMethod() ||
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001787 !(isa<Decl>(Owner) &&
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001788 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall19c1bfd2010-08-25 05:32:35 +00001789 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump11289f42009-09-09 15:08:12 +00001790
Richard Smith76b90272019-05-09 03:59:21 +00001791 ExplicitSpecifier InstantiatedExplicitSpecifier;
1792 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
1793 InstantiatedExplicitSpecifier = instantiateExplicitSpecifier(
1794 SemaRef, TemplateArgs, DGuide->getExplicitSpecifier(), DGuide);
1795 if (InstantiatedExplicitSpecifier.isInvalid())
1796 return nullptr;
1797 }
1798
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001799 SmallVector<ParmVarDecl *, 4> Params;
David Blaikie4d142962011-11-10 05:42:04 +00001800 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall58f10c32010-03-11 09:03:00 +00001801 if (!TInfo)
Craig Topperc3ec1492014-05-26 06:22:03 +00001802 return nullptr;
Douglas Gregor89f593a2012-09-13 21:56:43 +00001803 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
John McCall58de3582009-08-14 02:03:10 +00001804
Douglas Gregor14454802011-02-25 02:25:35 +00001805 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1806 if (QualifierLoc) {
1807 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1808 TemplateArgs);
1809 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00001810 return nullptr;
John McCalle0b2ddb2010-03-26 04:53:08 +00001811 }
1812
John McCallce410662010-02-06 01:50:47 +00001813 // If we're instantiating a local function declaration, put the result
Richard Smith541b38b2013-09-20 01:15:31 +00001814 // in the enclosing namespace; otherwise we need to find the instantiated
1815 // context.
John McCallce410662010-02-06 01:50:47 +00001816 DeclContext *DC;
Richard Smith541b38b2013-09-20 01:15:31 +00001817 if (D->isLocalExternDecl()) {
John McCallce410662010-02-06 01:50:47 +00001818 DC = Owner;
Richard Smith541b38b2013-09-20 01:15:31 +00001819 SemaRef.adjustContextForLocalExternDecl(DC);
1820 } else if (isFriend && QualifierLoc) {
John McCalle0b2ddb2010-03-26 04:53:08 +00001821 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +00001822 SS.Adopt(QualifierLoc);
John McCalle0b2ddb2010-03-26 04:53:08 +00001823 DC = SemaRef.computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +00001824 if (!DC) return nullptr;
John McCalle0b2ddb2010-03-26 04:53:08 +00001825 } else {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001826 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001827 TemplateArgs);
John McCalle0b2ddb2010-03-26 04:53:08 +00001828 }
John McCallce410662010-02-06 01:50:47 +00001829
Richard Smith4fa145152017-12-21 19:43:39 +00001830 DeclarationNameInfo NameInfo
1831 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1832
Richard Smithbc491202017-02-17 20:05:37 +00001833 FunctionDecl *Function;
Faisal Vali81b756e2017-10-22 14:45:08 +00001834 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
Richard Smithbc491202017-02-17 20:05:37 +00001835 Function = CXXDeductionGuideDecl::Create(
Richard Smith76b90272019-05-09 03:59:21 +00001836 SemaRef.Context, DC, D->getInnerLocStart(),
1837 InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
1838 D->getSourceRange().getEnd());
Faisal Vali81b756e2017-10-22 14:45:08 +00001839 if (DGuide->isCopyDeductionCandidate())
1840 cast<CXXDeductionGuideDecl>(Function)->setIsCopyDeductionCandidate();
Richard Smithc660c8f2018-03-16 13:36:56 +00001841 Function->setAccess(D->getAccess());
Faisal Vali81b756e2017-10-22 14:45:08 +00001842 } else {
Richard Smithbc491202017-02-17 20:05:37 +00001843 Function = FunctionDecl::Create(
Richard Smith4fa145152017-12-21 19:43:39 +00001844 SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo,
Richard Smithbc491202017-02-17 20:05:37 +00001845 D->getCanonicalDecl()->getStorageClass(), D->isInlineSpecified(),
Gauthier Harnisch796ed032019-06-14 08:56:20 +00001846 D->hasWrittenPrototype(), D->getConstexprKind());
Richard Smithbc491202017-02-17 20:05:37 +00001847 Function->setRangeEnd(D->getSourceRange().getEnd());
1848 }
John McCall3e11ebe2010-03-15 10:12:16 +00001849
Richard Smithf3814ad2013-01-25 00:08:28 +00001850 if (D->isInlined())
1851 Function->setImplicitlyInline();
1852
Douglas Gregor14454802011-02-25 02:25:35 +00001853 if (QualifierLoc)
1854 Function->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +00001855
Richard Smith541b38b2013-09-20 01:15:31 +00001856 if (D->isLocalExternDecl())
1857 Function->setLocalExternDecl();
1858
John McCall30837102010-03-26 23:10:15 +00001859 DeclContext *LexicalDC = Owner;
Richard Smith541b38b2013-09-20 01:15:31 +00001860 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
John McCall30837102010-03-26 23:10:15 +00001861 assert(D->getDeclContext()->isFileContext());
1862 LexicalDC = D->getDeclContext();
1863 }
1864
1865 Function->setLexicalDeclContext(LexicalDC);
Mike Stump11289f42009-09-09 15:08:12 +00001866
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001867 // Attach the parameters
Reid Klecknera09e44c2013-07-31 21:00:18 +00001868 for (unsigned P = 0; P < Params.size(); ++P)
1869 if (Params[P])
1870 Params[P]->setOwningFunction(Function);
David Blaikie9c70e042011-09-21 18:16:56 +00001871 Function->setParams(Params);
John McCallaa74a0c2009-08-28 07:59:38 +00001872
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001873 if (TemplateParams) {
1874 // Our resulting instantiation is actually a function template, since we
1875 // are substituting only the outer template parameters. For example, given
1876 //
1877 // template<typename T>
1878 // struct X {
1879 // template<typename U> friend void f(T, U);
1880 // };
1881 //
1882 // X<int> x;
1883 //
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001884 // We are instantiating the friend function template "f" within X<int>,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001885 // which means substituting int for T, but leaving "f" as a friend function
1886 // template.
1887 // Build the function template itself.
John McCalle0b2ddb2010-03-26 04:53:08 +00001888 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001889 Function->getLocation(),
1890 Function->getDeclName(),
1891 TemplateParams, Function);
1892 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCall30837102010-03-26 23:10:15 +00001893
1894 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalle0b2ddb2010-03-26 04:53:08 +00001895
1896 if (isFriend && D->isThisDeclarationADefinition()) {
John McCalle0b2ddb2010-03-26 04:53:08 +00001897 FunctionTemplate->setInstantiatedFromMemberTemplate(
1898 D->getDescribedFunctionTemplate());
1899 }
Douglas Gregorffe14e32009-11-14 01:20:54 +00001900 } else if (FunctionTemplate) {
1901 // Record this function template specialization.
Richard Smith47752e42013-05-03 23:46:09 +00001902 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregord5058122010-02-11 01:19:42 +00001903 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001904 TemplateArgumentList::CreateCopy(SemaRef.Context,
David Majnemer8b622692016-07-03 21:17:51 +00001905 Innermost),
Craig Topperc3ec1492014-05-26 06:22:03 +00001906 /*InsertPos=*/nullptr);
Richard Smith152bcd22017-01-28 02:56:07 +00001907 } else if (isFriend && D->isThisDeclarationADefinition()) {
1908 // Do not connect the friend to the template unless it's actually a
1909 // definition. We don't want non-template functions to be marked as being
1910 // template instantiations.
John McCalle0b2ddb2010-03-26 04:53:08 +00001911 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCallaa74a0c2009-08-28 07:59:38 +00001912 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001913
Richard Smith64095fc2019-01-11 01:59:33 +00001914 if (isFriend)
1915 Function->setObjectOfFriendDecl();
1916
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001917 if (InitFunctionInstantiation(Function, D))
1918 Function->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001919
Richard Smith64095fc2019-01-11 01:59:33 +00001920 bool IsExplicitSpecialization = false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001921
Richard Smith541b38b2013-09-20 01:15:31 +00001922 LookupResult Previous(
1923 SemaRef, Function->getDeclName(), SourceLocation(),
1924 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
1925 : Sema::LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00001926 D->isLocalExternDecl() ? Sema::ForExternalRedeclaration
1927 : SemaRef.forRedeclarationInCurContext());
John McCall1f82f242009-11-18 22:49:29 +00001928
John McCallb9c78482010-04-08 09:05:18 +00001929 if (DependentFunctionTemplateSpecializationInfo *Info
1930 = D->getDependentSpecializationInfo()) {
1931 assert(isFriend && "non-friend has dependent specialization info?");
1932
John McCallb9c78482010-04-08 09:05:18 +00001933 // Instantiate the explicit template arguments.
1934 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1935 Info->getRAngleLoc());
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001936 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1937 ExplicitArgs, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00001938 return nullptr;
John McCallb9c78482010-04-08 09:05:18 +00001939
1940 // Map the candidate templates to their instantiations.
1941 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1942 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1943 Info->getTemplate(I),
1944 TemplateArgs);
Craig Topperc3ec1492014-05-26 06:22:03 +00001945 if (!Temp) return nullptr;
John McCallb9c78482010-04-08 09:05:18 +00001946
1947 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1948 }
1949
1950 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1951 &ExplicitArgs,
1952 Previous))
1953 Function->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001954
Richard Smith64095fc2019-01-11 01:59:33 +00001955 IsExplicitSpecialization = true;
1956 } else if (const ASTTemplateArgumentListInfo *Info =
1957 D->getTemplateSpecializationArgsAsWritten()) {
1958 // The name of this function was written as a template-id.
1959 SemaRef.LookupQualifiedName(Previous, DC);
John McCallb9c78482010-04-08 09:05:18 +00001960
Richard Smith64095fc2019-01-11 01:59:33 +00001961 // Instantiate the explicit template arguments.
1962 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1963 Info->getRAngleLoc());
1964 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1965 ExplicitArgs, TemplateArgs))
1966 return nullptr;
1967
1968 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1969 &ExplicitArgs,
1970 Previous))
1971 Function->setInvalidDecl();
1972
1973 IsExplicitSpecialization = true;
John McCallb9c78482010-04-08 09:05:18 +00001974 } else if (TemplateParams || !FunctionTemplate) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001975 // Look only into the namespace where the friend would be declared to
1976 // find a previous declaration. This is the innermost enclosing namespace,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001977 // as described in ActOnFriendFunctionDecl.
John McCall1f82f242009-11-18 22:49:29 +00001978 SemaRef.LookupQualifiedName(Previous, DC);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001979
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001980 // In C++, the previous declaration we find might be a tag type
1981 // (class or enum). In this case, the new declaration will hide the
1982 // tag type. Note that this does does not apply if we're declaring a
1983 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00001984 if (Previous.isSingleTagDecl())
1985 Previous.clear();
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001986 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001987
Craig Topperc3ec1492014-05-26 06:22:03 +00001988 SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
Richard Smith64095fc2019-01-11 01:59:33 +00001989 IsExplicitSpecialization);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001990
John McCallb9467b62010-04-24 01:30:58 +00001991 NamedDecl *PrincipalDecl = (TemplateParams
1992 ? cast<NamedDecl>(FunctionTemplate)
1993 : Function);
1994
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001995 // If the original function was part of a friend declaration,
1996 // inherit its namespace state and add it to the owner.
John McCalle0b2ddb2010-03-26 04:53:08 +00001997 if (isFriend) {
Serge Pavlovacfcd782018-12-06 09:35:04 +00001998 Function->setObjectOfFriendDecl();
1999 if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate())
2000 FT->setObjectOfFriendDecl();
Richard Smith05afe5e2012-03-13 03:12:56 +00002001 DC->makeDeclVisibleInContext(PrincipalDecl);
Gabor Greif718d5152010-08-30 21:10:05 +00002002
Richard Smith91dfaac2014-02-03 02:37:59 +00002003 bool QueuedInstantiation = false;
Gabor Greif718d5152010-08-30 21:10:05 +00002004
Richard Smith91dfaac2014-02-03 02:37:59 +00002005 // C++11 [temp.friend]p4 (DR329):
2006 // When a function is defined in a friend function declaration in a class
2007 // template, the function is instantiated when the function is odr-used.
2008 // The same restrictions on multiple declarations and definitions that
2009 // apply to non-template function declarations and definitions also apply
2010 // to these implicit definitions.
2011 if (D->isThisDeclarationADefinition()) {
Serge Pavlove6e534c2018-03-01 07:04:11 +00002012 SemaRef.CheckForFunctionRedefinition(Function);
2013 if (!Function->isInvalidDecl()) {
2014 for (auto R : Function->redecls()) {
2015 if (R == Function)
2016 continue;
Richard Smith91dfaac2014-02-03 02:37:59 +00002017
Serge Pavlove6e534c2018-03-01 07:04:11 +00002018 // If some prior declaration of this function has been used, we need
2019 // to instantiate its definition.
2020 if (!QueuedInstantiation && R->isUsed(false)) {
2021 if (MemberSpecializationInfo *MSInfo =
2022 Function->getMemberSpecializationInfo()) {
2023 if (MSInfo->getPointOfInstantiation().isInvalid()) {
2024 SourceLocation Loc = R->getLocation(); // FIXME
2025 MSInfo->setPointOfInstantiation(Loc);
2026 SemaRef.PendingLocalImplicitInstantiations.push_back(
2027 std::make_pair(Function, Loc));
2028 QueuedInstantiation = true;
2029 }
Douglas Gregorb92ea592010-05-18 05:45:02 +00002030 }
Richard Smith91dfaac2014-02-03 02:37:59 +00002031 }
Douglas Gregorb92ea592010-05-18 05:45:02 +00002032 }
2033 }
2034 }
Richard Smithf3597652017-05-10 00:01:13 +00002035
2036 // Check the template parameter list against the previous declaration. The
2037 // goal here is to pick up default arguments added since the friend was
2038 // declared; we know the template parameter lists match, since otherwise
2039 // we would not have picked this template as the previous declaration.
2040 if (TemplateParams && FunctionTemplate->getPreviousDecl()) {
2041 SemaRef.CheckTemplateParameterList(
2042 TemplateParams,
2043 FunctionTemplate->getPreviousDecl()->getTemplateParameters(),
2044 Function->isThisDeclarationADefinition()
2045 ? Sema::TPC_FriendFunctionTemplateDefinition
2046 : Sema::TPC_FriendFunctionTemplate);
2047 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00002048 }
2049
Richard Smith541b38b2013-09-20 01:15:31 +00002050 if (Function->isLocalExternDecl() && !Function->getPreviousDecl())
2051 DC->makeDeclVisibleInContext(PrincipalDecl);
2052
John McCallb9467b62010-04-24 01:30:58 +00002053 if (Function->isOverloadedOperator() && !DC->isRecord() &&
2054 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
2055 PrincipalDecl->setNonMemberOperator();
2056
Alexis Hunt1fb4e762011-05-23 21:07:59 +00002057 assert(!D->isDefaulted() && "only methods should be defaulted");
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002058 return Function;
2059}
2060
Richard Smithf19a8b02019-05-02 00:49:14 +00002061Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(
2062 CXXMethodDecl *D, TemplateParameterList *TemplateParams,
2063 Optional<const ASTTemplateArgumentListInfo *>
2064 ClassScopeSpecializationArgs) {
Douglas Gregor97628d62009-08-21 00:16:32 +00002065 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
Douglas Gregore704c9d2009-08-27 16:57:43 +00002066 if (FunctionTemplate && !TemplateParams) {
Mike Stump11289f42009-09-09 15:08:12 +00002067 // We are creating a function template specialization from a function
2068 // template. Check whether there is already a function template
Douglas Gregore704c9d2009-08-27 16:57:43 +00002069 // specialization for this particular set of template arguments.
Richard Smith47752e42013-05-03 23:46:09 +00002070 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump11289f42009-09-09 15:08:12 +00002071
Craig Topperc3ec1492014-05-26 06:22:03 +00002072 void *InsertPos = nullptr;
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00002073 FunctionDecl *SpecFunc
Craig Topper7e0daca2014-06-26 04:58:53 +00002074 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002075
Douglas Gregor97628d62009-08-21 00:16:32 +00002076 // If we already have a function template specialization, return it.
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00002077 if (SpecFunc)
2078 return SpecFunc;
Douglas Gregor97628d62009-08-21 00:16:32 +00002079 }
2080
John McCall2f88d7d2010-03-27 05:57:59 +00002081 bool isFriend;
2082 if (FunctionTemplate)
2083 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2084 else
2085 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2086
Craig Topperc3ec1492014-05-26 06:22:03 +00002087 bool MergeWithParentScope = (TemplateParams != nullptr) ||
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002088 !(isa<Decl>(Owner) &&
Douglas Gregorf5974fa2010-01-16 20:21:20 +00002089 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall19c1bfd2010-08-25 05:32:35 +00002090 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor37256522009-05-14 21:44:34 +00002091
John McCalld0e23ec2010-10-19 02:26:41 +00002092 // Instantiate enclosing template arguments for friends.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002093 SmallVector<TemplateParameterList *, 4> TempParamLists;
John McCalld0e23ec2010-10-19 02:26:41 +00002094 unsigned NumTempParamLists = 0;
2095 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
Benjamin Kramer9dc549b2015-08-04 14:46:06 +00002096 TempParamLists.resize(NumTempParamLists);
John McCalld0e23ec2010-10-19 02:26:41 +00002097 for (unsigned I = 0; I != NumTempParamLists; ++I) {
2098 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
2099 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2100 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00002101 return nullptr;
John McCalld0e23ec2010-10-19 02:26:41 +00002102 TempParamLists[I] = InstParams;
2103 }
2104 }
2105
Richard Smith76b90272019-05-09 03:59:21 +00002106 ExplicitSpecifier InstantiatedExplicitSpecifier =
2107 instantiateExplicitSpecifier(SemaRef, TemplateArgs,
2108 ExplicitSpecifier::getFromDecl(D), D);
2109 if (InstantiatedExplicitSpecifier.isInvalid())
2110 return nullptr;
2111
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002112 SmallVector<ParmVarDecl *, 4> Params;
Benjamin Kramer1dd48bc2012-01-20 14:42:32 +00002113 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall58f10c32010-03-11 09:03:00 +00002114 if (!TInfo)
Craig Topperc3ec1492014-05-26 06:22:03 +00002115 return nullptr;
Douglas Gregor89f593a2012-09-13 21:56:43 +00002116 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00002117
Douglas Gregor14454802011-02-25 02:25:35 +00002118 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2119 if (QualifierLoc) {
2120 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
John McCall2f88d7d2010-03-27 05:57:59 +00002121 TemplateArgs);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002122 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00002123 return nullptr;
John McCall2f88d7d2010-03-27 05:57:59 +00002124 }
2125
2126 DeclContext *DC = Owner;
2127 if (isFriend) {
Douglas Gregor14454802011-02-25 02:25:35 +00002128 if (QualifierLoc) {
John McCall2f88d7d2010-03-27 05:57:59 +00002129 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +00002130 SS.Adopt(QualifierLoc);
John McCall2f88d7d2010-03-27 05:57:59 +00002131 DC = SemaRef.computeDeclContext(SS);
John McCall1a1b53e2010-10-19 05:01:53 +00002132
2133 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
Craig Topperc3ec1492014-05-26 06:22:03 +00002134 return nullptr;
John McCall2f88d7d2010-03-27 05:57:59 +00002135 } else {
2136 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
2137 D->getDeclContext(),
2138 TemplateArgs);
2139 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002140 if (!DC) return nullptr;
John McCall2f88d7d2010-03-27 05:57:59 +00002141 }
2142
Douglas Gregorf4f296d2009-03-23 23:06:20 +00002143 // Build the instantiated method declaration.
John McCall2f88d7d2010-03-27 05:57:59 +00002144 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Craig Topperc3ec1492014-05-26 06:22:03 +00002145 CXXMethodDecl *Method = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002146
Abramo Bagnaradff19302011-03-08 08:55:46 +00002147 SourceLocation StartLoc = D->getInnerLocStart();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002148 DeclarationNameInfo NameInfo
2149 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregore8394862009-08-21 22:43:28 +00002150 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Richard Smith76b90272019-05-09 03:59:21 +00002151 Method = CXXConstructorDecl::Create(
2152 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2153 InstantiatedExplicitSpecifier, Constructor->isInlineSpecified(), false,
Gauthier Harnisch796ed032019-06-14 08:56:20 +00002154 Constructor->getConstexprKind());
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002155 Method->setRangeEnd(Constructor->getEndLoc());
Douglas Gregore8394862009-08-21 22:43:28 +00002156 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Richard Smith457226e2019-09-23 03:48:44 +00002157 Method = CXXDestructorDecl::Create(
2158 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2159 Destructor->isInlineSpecified(), false, Destructor->getConstexprKind());
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002160 Method->setRangeEnd(Destructor->getEndLoc());
Douglas Gregor05155d82009-08-21 23:19:43 +00002161 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002162 Method = CXXConversionDecl::Create(
2163 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
Richard Smith76b90272019-05-09 03:59:21 +00002164 Conversion->isInlineSpecified(), InstantiatedExplicitSpecifier,
Gauthier Harnisch796ed032019-06-14 08:56:20 +00002165 Conversion->getConstexprKind(), Conversion->getEndLoc());
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002166 } else {
Rafael Espindola29cda592013-04-15 12:38:20 +00002167 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002168 Method = CXXMethodDecl::Create(SemaRef.Context, Record, StartLoc, NameInfo,
2169 T, TInfo, SC, D->isInlineSpecified(),
Gauthier Harnisch796ed032019-06-14 08:56:20 +00002170 D->getConstexprKind(), D->getEndLoc());
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002171 }
Douglas Gregor97628d62009-08-21 00:16:32 +00002172
Richard Smithf3814ad2013-01-25 00:08:28 +00002173 if (D->isInlined())
2174 Method->setImplicitlyInline();
2175
Douglas Gregor14454802011-02-25 02:25:35 +00002176 if (QualifierLoc)
2177 Method->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +00002178
Douglas Gregore704c9d2009-08-27 16:57:43 +00002179 if (TemplateParams) {
2180 // Our resulting instantiation is actually a function template, since we
2181 // are substituting only the outer template parameters. For example, given
Mike Stump11289f42009-09-09 15:08:12 +00002182 //
Douglas Gregore704c9d2009-08-27 16:57:43 +00002183 // template<typename T>
2184 // struct X {
2185 // template<typename U> void f(T, U);
2186 // };
2187 //
2188 // X<int> x;
2189 //
2190 // We are instantiating the member template "f" within X<int>, which means
2191 // substituting int for T, but leaving "f" as a member function template.
2192 // Build the function template itself.
2193 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
2194 Method->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002195 Method->getDeclName(),
Douglas Gregore704c9d2009-08-27 16:57:43 +00002196 TemplateParams, Method);
John McCall2f88d7d2010-03-27 05:57:59 +00002197 if (isFriend) {
2198 FunctionTemplate->setLexicalDeclContext(Owner);
Richard Smith64017682013-07-17 23:53:16 +00002199 FunctionTemplate->setObjectOfFriendDecl();
John McCall2f88d7d2010-03-27 05:57:59 +00002200 } else if (D->isOutOfLine())
Mike Stump11289f42009-09-09 15:08:12 +00002201 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregore704c9d2009-08-27 16:57:43 +00002202 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002203 } else if (FunctionTemplate) {
2204 // Record this function template specialization.
Richard Smith47752e42013-05-03 23:46:09 +00002205 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregord5058122010-02-11 01:19:42 +00002206 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002207 TemplateArgumentList::CreateCopy(SemaRef.Context,
David Majnemer8b622692016-07-03 21:17:51 +00002208 Innermost),
Craig Topperc3ec1492014-05-26 06:22:03 +00002209 /*InsertPos=*/nullptr);
John McCall2f88d7d2010-03-27 05:57:59 +00002210 } else if (!isFriend) {
Douglas Gregorffe14e32009-11-14 01:20:54 +00002211 // Record that this is an instantiation of a member function.
Douglas Gregord801b062009-10-07 23:56:10 +00002212 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002213 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002214
Mike Stump11289f42009-09-09 15:08:12 +00002215 // If we are instantiating a member function defined
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002216 // out-of-line, the instantiation will have the same lexical
2217 // context (which will be a namespace scope) as the template.
John McCall2f88d7d2010-03-27 05:57:59 +00002218 if (isFriend) {
John McCalld0e23ec2010-10-19 02:26:41 +00002219 if (NumTempParamLists)
Benjamin Kramer9cc210652015-08-05 09:40:49 +00002220 Method->setTemplateParameterListsInfo(
2221 SemaRef.Context,
2222 llvm::makeArrayRef(TempParamLists.data(), NumTempParamLists));
John McCalld0e23ec2010-10-19 02:26:41 +00002223
John McCall2f88d7d2010-03-27 05:57:59 +00002224 Method->setLexicalDeclContext(Owner);
Richard Smith64017682013-07-17 23:53:16 +00002225 Method->setObjectOfFriendDecl();
John McCall2f88d7d2010-03-27 05:57:59 +00002226 } else if (D->isOutOfLine())
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002227 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +00002228
Douglas Gregor21342092009-03-24 00:38:23 +00002229 // Attach the parameters
2230 for (unsigned P = 0; P < Params.size(); ++P)
2231 Params[P]->setOwningFunction(Method);
David Blaikie9c70e042011-09-21 18:16:56 +00002232 Method->setParams(Params);
Douglas Gregor21342092009-03-24 00:38:23 +00002233
2234 if (InitMethodInstantiation(Method, D))
2235 Method->setInvalidDecl();
Douglas Gregorf4f296d2009-03-23 23:06:20 +00002236
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002237 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00002238 Sema::ForExternalRedeclaration);
Mike Stump11289f42009-09-09 15:08:12 +00002239
Richard Smith64095fc2019-01-11 01:59:33 +00002240 bool IsExplicitSpecialization = false;
2241
2242 // If the name of this function was written as a template-id, instantiate
2243 // the explicit template arguments.
2244 if (DependentFunctionTemplateSpecializationInfo *Info
2245 = D->getDependentSpecializationInfo()) {
2246 assert(isFriend && "non-friend has dependent specialization info?");
2247
2248 // Instantiate the explicit template arguments.
2249 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2250 Info->getRAngleLoc());
2251 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
2252 ExplicitArgs, TemplateArgs))
2253 return nullptr;
2254
2255 // Map the candidate templates to their instantiations.
2256 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
2257 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
2258 Info->getTemplate(I),
2259 TemplateArgs);
2260 if (!Temp) return nullptr;
2261
2262 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
2263 }
2264
2265 if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2266 &ExplicitArgs,
2267 Previous))
2268 Method->setInvalidDecl();
2269
2270 IsExplicitSpecialization = true;
2271 } else if (const ASTTemplateArgumentListInfo *Info =
Richard Smithf19a8b02019-05-02 00:49:14 +00002272 ClassScopeSpecializationArgs.getValueOr(
2273 D->getTemplateSpecializationArgsAsWritten())) {
Richard Smith64095fc2019-01-11 01:59:33 +00002274 SemaRef.LookupQualifiedName(Previous, DC);
2275
2276 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2277 Info->getRAngleLoc());
2278 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
2279 ExplicitArgs, TemplateArgs))
2280 return nullptr;
2281
2282 if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2283 &ExplicitArgs,
2284 Previous))
2285 Method->setInvalidDecl();
2286
2287 IsExplicitSpecialization = true;
Richard Smithf19a8b02019-05-02 00:49:14 +00002288 } else if (ClassScopeSpecializationArgs) {
2289 // Class-scope explicit specialization written without explicit template
2290 // arguments.
2291 SemaRef.LookupQualifiedName(Previous, DC);
2292 if (SemaRef.CheckFunctionTemplateSpecialization(Method, nullptr, Previous))
2293 Method->setInvalidDecl();
2294
2295 IsExplicitSpecialization = true;
Richard Smith64095fc2019-01-11 01:59:33 +00002296 } else if (!FunctionTemplate || TemplateParams || isFriend) {
John McCall2f88d7d2010-03-27 05:57:59 +00002297 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump11289f42009-09-09 15:08:12 +00002298
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002299 // In C++, the previous declaration we find might be a tag type
2300 // (class or enum). In this case, the new declaration will hide the
2301 // tag type. Note that this does does not apply if we're declaring a
2302 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00002303 if (Previous.isSingleTagDecl())
2304 Previous.clear();
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002305 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00002306
Richard Smithf19a8b02019-05-02 00:49:14 +00002307 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous,
2308 IsExplicitSpecialization);
Douglas Gregor05155d82009-08-21 23:19:43 +00002309
Douglas Gregor21920e372009-12-01 17:24:26 +00002310 if (D->isPure())
2311 SemaRef.CheckPureMethod(Method, SourceRange());
2312
John McCalla0a96892012-08-10 03:15:35 +00002313 // Propagate access. For a non-friend declaration, the access is
2314 // whatever we're propagating from. For a friend, it should be the
2315 // previous declaration we just found.
2316 if (isFriend && Method->getPreviousDecl())
2317 Method->setAccess(Method->getPreviousDecl()->getAccess());
Fangrui Song6907ce22018-07-30 19:24:48 +00002318 else
John McCalla0a96892012-08-10 03:15:35 +00002319 Method->setAccess(D->getAccess());
2320 if (FunctionTemplate)
2321 FunctionTemplate->setAccess(Method->getAccess());
John McCall401982f2010-01-20 21:53:11 +00002322
Anders Carlsson7c812f52011-01-20 06:52:44 +00002323 SemaRef.CheckOverrideControl(Method);
2324
Eli Friedman41340732011-11-15 22:39:08 +00002325 // If a function is defined as defaulted or deleted, mark it as such now.
Richard Smith92f241f2012-12-08 02:53:02 +00002326 if (D->isExplicitlyDefaulted())
2327 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
Eli Friedman41340732011-11-15 22:39:08 +00002328 if (D->isDeletedAsWritten())
Richard Smith92f241f2012-12-08 02:53:02 +00002329 SemaRef.SetDeclDeleted(Method, Method->getLocation());
Eli Friedman41340732011-11-15 22:39:08 +00002330
Richard Smithf19a8b02019-05-02 00:49:14 +00002331 // If this is an explicit specialization, mark the implicitly-instantiated
2332 // template specialization as being an explicit specialization too.
2333 // FIXME: Is this necessary?
2334 if (IsExplicitSpecialization && !isFriend)
2335 SemaRef.CompleteMemberSpecialization(Method, Previous);
2336
John McCalla0a96892012-08-10 03:15:35 +00002337 // If there's a function template, let our caller handle it.
John McCall2f88d7d2010-03-27 05:57:59 +00002338 if (FunctionTemplate) {
John McCalla0a96892012-08-10 03:15:35 +00002339 // do nothing
2340
2341 // Don't hide a (potentially) valid declaration with an invalid one.
John McCall2f88d7d2010-03-27 05:57:59 +00002342 } else if (Method->isInvalidDecl() && !Previous.empty()) {
John McCalla0a96892012-08-10 03:15:35 +00002343 // do nothing
2344
2345 // Otherwise, check access to friends and make them visible.
2346 } else if (isFriend) {
2347 // We only need to re-check access for methods which we didn't
2348 // manage to match during parsing.
2349 if (!D->getPreviousDecl())
2350 SemaRef.CheckFriendAccess(Method);
2351
2352 Record->makeDeclVisibleInContext(Method);
2353
2354 // Otherwise, add the declaration. We don't need to do this for
2355 // class-scope specializations because we'll have matched them with
2356 // the appropriate template.
Richard Smithf19a8b02019-05-02 00:49:14 +00002357 } else {
John McCalla0a96892012-08-10 03:15:35 +00002358 Owner->addDecl(Method);
John McCall2f88d7d2010-03-27 05:57:59 +00002359 }
Alexis Hunt1fb4e762011-05-23 21:07:59 +00002360
Rafael Auler9dde31e2019-03-20 19:22:24 +00002361 // PR17480: Honor the used attribute to instantiate member function
2362 // definitions
2363 if (Method->hasAttr<UsedAttr>()) {
2364 if (const auto *A = dyn_cast<CXXRecordDecl>(Owner)) {
2365 SourceLocation Loc;
2366 if (const MemberSpecializationInfo *MSInfo =
2367 A->getMemberSpecializationInfo())
2368 Loc = MSInfo->getPointOfInstantiation();
2369 else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(A))
2370 Loc = Spec->getPointOfInstantiation();
2371 SemaRef.MarkFunctionReferenced(Loc, Method);
2372 }
2373 }
2374
Douglas Gregorf4f296d2009-03-23 23:06:20 +00002375 return Method;
2376}
2377
Douglas Gregor4044d992009-03-24 16:43:20 +00002378Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002379 return VisitCXXMethodDecl(D);
Douglas Gregor4044d992009-03-24 16:43:20 +00002380}
2381
Douglas Gregor654b07e2009-03-24 00:15:49 +00002382Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregore8394862009-08-21 22:43:28 +00002383 return VisitCXXMethodDecl(D);
Douglas Gregor654b07e2009-03-24 00:15:49 +00002384}
2385
Douglas Gregor1880ba52009-03-25 00:34:44 +00002386Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002387 return VisitCXXMethodDecl(D);
Douglas Gregor1880ba52009-03-25 00:34:44 +00002388}
2389
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002390Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
David Blaikie7a30dc52013-02-21 01:47:18 +00002391 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
2392 /*ExpectParameterPack=*/ false);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00002393}
2394
John McCall87a44eb2009-08-20 01:44:21 +00002395Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
2396 TemplateTypeParmDecl *D) {
2397 // TODO: don't always clone when decls are refcounted.
Chandler Carruth08836322011-05-01 00:51:33 +00002398 assert(D->getTypeForDecl()->isTemplateTypeParmType());
Mike Stump11289f42009-09-09 15:08:12 +00002399
Richard Smithb4f96252017-02-21 06:30:38 +00002400 TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002401 SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(),
Richard Smithb4f96252017-02-21 06:30:38 +00002402 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
2403 D->getIdentifier(), D->wasDeclaredWithTypename(), D->isParameterPack());
Douglas Gregorfd7c2252011-03-04 17:52:15 +00002404 Inst->setAccess(AS_public);
Richard Smith71c37a82019-09-04 22:14:50 +00002405 Inst->setImplicit(D->isImplicit());
John McCall87a44eb2009-08-20 01:44:21 +00002406
Richard Smith52933792015-06-16 21:57:05 +00002407 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
David Majnemer89189202013-08-28 23:48:32 +00002408 TypeSourceInfo *InstantiatedDefaultArg =
2409 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
2410 D->getDefaultArgumentLoc(), D->getDeclName());
2411 if (InstantiatedDefaultArg)
Richard Smith1469b912015-06-10 00:29:03 +00002412 Inst->setDefaultArgument(InstantiatedDefaultArg);
David Majnemer89189202013-08-28 23:48:32 +00002413 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002414
2415 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor954de172009-10-31 17:21:17 +00002416 // scope.
2417 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002418
John McCall87a44eb2009-08-20 01:44:21 +00002419 return Inst;
2420}
2421
Douglas Gregor6b815c82009-10-23 23:25:44 +00002422Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
2423 NonTypeTemplateParmDecl *D) {
2424 // Substitute into the type of the non-type template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002425 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002426 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
2427 SmallVector<QualType, 4> ExpandedParameterPackTypes;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002428 bool IsExpandedParameterPack = false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002429 TypeSourceInfo *DI;
Douglas Gregor6b815c82009-10-23 23:25:44 +00002430 QualType T;
Douglas Gregor6b815c82009-10-23 23:25:44 +00002431 bool Invalid = false;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002432
2433 if (D->isExpandedParameterPack()) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002434 // The non-type template parameter pack is an already-expanded pack
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002435 // expansion of types. Substitute into each of the expanded types.
2436 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
2437 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
2438 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
Richard Smith15361a22016-12-28 06:27:18 +00002439 TypeSourceInfo *NewDI =
2440 SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
2441 D->getLocation(), D->getDeclName());
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002442 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00002443 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002444
Richard Smith15361a22016-12-28 06:27:18 +00002445 QualType NewT =
2446 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002447 if (NewT.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00002448 return nullptr;
Richard Smith15361a22016-12-28 06:27:18 +00002449
2450 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002451 ExpandedParameterPackTypes.push_back(NewT);
2452 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002453
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002454 IsExpandedParameterPack = true;
2455 DI = D->getTypeSourceInfo();
2456 T = DI->getType();
Richard Smith1fde8ec2012-09-07 02:06:42 +00002457 } else if (D->isPackExpansion()) {
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002458 // The non-type template parameter pack's type is a pack expansion of types.
2459 // Determine whether we need to expand this parameter pack into separate
2460 // types.
David Blaikie6adc78e2013-02-18 22:06:02 +00002461 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002462 TypeLoc Pattern = Expansion.getPatternLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002463 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002464 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002465
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002466 // Determine whether the set of unexpanded parameter packs can and should
2467 // be expanded.
2468 bool Expand = true;
2469 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00002470 Optional<unsigned> OrigNumExpansions
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002471 = Expansion.getTypePtr()->getNumExpansions();
David Blaikie05785d12013-02-20 22:23:23 +00002472 Optional<unsigned> NumExpansions = OrigNumExpansions;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002473 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
2474 Pattern.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00002475 Unexpanded,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002476 TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002477 Expand, RetainExpansion,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002478 NumExpansions))
Craig Topperc3ec1492014-05-26 06:22:03 +00002479 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002480
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002481 if (Expand) {
2482 for (unsigned I = 0; I != *NumExpansions; ++I) {
2483 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2484 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002485 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002486 D->getDeclName());
2487 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00002488 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002489
Richard Smith15361a22016-12-28 06:27:18 +00002490 QualType NewT =
2491 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002492 if (NewT.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00002493 return nullptr;
Richard Smith15361a22016-12-28 06:27:18 +00002494
2495 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002496 ExpandedParameterPackTypes.push_back(NewT);
2497 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002498
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002499 // Note that we have an expanded parameter pack. The "type" of this
2500 // expanded parameter pack is the original expansion type, but callers
2501 // will end up using the expanded parameter pack types for type-checking.
2502 IsExpandedParameterPack = true;
2503 DI = D->getTypeSourceInfo();
2504 T = DI->getType();
2505 } else {
2506 // We cannot fully expand the pack expansion now, so substitute into the
2507 // pattern and create a new pack expansion type.
2508 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2509 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002510 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002511 D->getDeclName());
2512 if (!NewPattern)
Craig Topperc3ec1492014-05-26 06:22:03 +00002513 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002514
Richard Smith15361a22016-12-28 06:27:18 +00002515 SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002516 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
2517 NumExpansions);
2518 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00002519 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002520
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002521 T = DI->getType();
2522 }
2523 } else {
2524 // Simple case: substitution into a parameter that is not a parameter pack.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002525 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002526 D->getLocation(), D->getDeclName());
2527 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00002528 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002529
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002530 // Check that this type is acceptable for a non-type template parameter.
Richard Smith15361a22016-12-28 06:27:18 +00002531 T = SemaRef.CheckNonTypeTemplateParameterType(DI, D->getLocation());
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002532 if (T.isNull()) {
2533 T = SemaRef.Context.IntTy;
2534 Invalid = true;
2535 }
Douglas Gregor6b815c82009-10-23 23:25:44 +00002536 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002537
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002538 NonTypeTemplateParmDecl *Param;
2539 if (IsExpandedParameterPack)
David Majnemerdfecf1a2016-07-06 04:19:16 +00002540 Param = NonTypeTemplateParmDecl::Create(
2541 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
Richard Smithb4f96252017-02-21 06:30:38 +00002542 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2543 D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
David Majnemerdfecf1a2016-07-06 04:19:16 +00002544 ExpandedParameterPackTypesAsWritten);
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002545 else
Richard Smithb4f96252017-02-21 06:30:38 +00002546 Param = NonTypeTemplateParmDecl::Create(
2547 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2548 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2549 D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002550
Douglas Gregorfd7c2252011-03-04 17:52:15 +00002551 Param->setAccess(AS_public);
Richard Smith71c37a82019-09-04 22:14:50 +00002552 Param->setImplicit(D->isImplicit());
Douglas Gregor6b815c82009-10-23 23:25:44 +00002553 if (Invalid)
2554 Param->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002555
Richard Smith52933792015-06-16 21:57:05 +00002556 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
Faisal Valid143a0c2017-04-01 21:30:49 +00002557 EnterExpressionEvaluationContext ConstantEvaluated(
2558 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00002559 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
2560 if (!Value.isInvalid())
Richard Smith1469b912015-06-10 00:29:03 +00002561 Param->setDefaultArgument(Value.get());
David Majnemer89189202013-08-28 23:48:32 +00002562 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002563
2564 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor954de172009-10-31 17:21:17 +00002565 // scope.
2566 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor6b815c82009-10-23 23:25:44 +00002567 return Param;
2568}
2569
Richard Smith1fde8ec2012-09-07 02:06:42 +00002570static void collectUnexpandedParameterPacks(
2571 Sema &S,
2572 TemplateParameterList *Params,
2573 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
Davide Italiano18960b92015-07-02 19:20:11 +00002574 for (const auto &P : *Params) {
2575 if (P->isTemplateParameterPack())
Richard Smith1fde8ec2012-09-07 02:06:42 +00002576 continue;
Davide Italiano18960b92015-07-02 19:20:11 +00002577 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
Richard Smith1fde8ec2012-09-07 02:06:42 +00002578 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
2579 Unexpanded);
Davide Italiano18960b92015-07-02 19:20:11 +00002580 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
Richard Smith1fde8ec2012-09-07 02:06:42 +00002581 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
2582 Unexpanded);
2583 }
2584}
2585
Anders Carlsson4bd78752009-08-28 15:18:15 +00002586Decl *
Douglas Gregor38fee962009-11-11 16:58:32 +00002587TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
2588 TemplateTemplateParmDecl *D) {
2589 // Instantiate the template parameter list of the template template parameter.
2590 TemplateParameterList *TempParams = D->getTemplateParameters();
2591 TemplateParameterList *InstParams;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002592 SmallVector<TemplateParameterList*, 8> ExpandedParams;
2593
2594 bool IsExpandedParameterPack = false;
2595
2596 if (D->isExpandedParameterPack()) {
2597 // The template template parameter pack is an already-expanded pack
2598 // expansion of template parameters. Substitute into each of the expanded
2599 // parameters.
2600 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
2601 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2602 I != N; ++I) {
2603 LocalInstantiationScope Scope(SemaRef);
2604 TemplateParameterList *Expansion =
2605 SubstTemplateParams(D->getExpansionTemplateParameters(I));
2606 if (!Expansion)
Craig Topperc3ec1492014-05-26 06:22:03 +00002607 return nullptr;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002608 ExpandedParams.push_back(Expansion);
2609 }
2610
2611 IsExpandedParameterPack = true;
2612 InstParams = TempParams;
2613 } else if (D->isPackExpansion()) {
2614 // The template template parameter pack expands to a pack of template
2615 // template parameters. Determine whether we need to expand this parameter
2616 // pack into separate parameters.
2617 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2618 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
2619 Unexpanded);
2620
2621 // Determine whether the set of unexpanded parameter packs can and should
2622 // be expanded.
2623 bool Expand = true;
2624 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00002625 Optional<unsigned> NumExpansions;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002626 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
2627 TempParams->getSourceRange(),
2628 Unexpanded,
2629 TemplateArgs,
2630 Expand, RetainExpansion,
2631 NumExpansions))
Craig Topperc3ec1492014-05-26 06:22:03 +00002632 return nullptr;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002633
2634 if (Expand) {
2635 for (unsigned I = 0; I != *NumExpansions; ++I) {
2636 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2637 LocalInstantiationScope Scope(SemaRef);
2638 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
2639 if (!Expansion)
Craig Topperc3ec1492014-05-26 06:22:03 +00002640 return nullptr;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002641 ExpandedParams.push_back(Expansion);
2642 }
2643
2644 // Note that we have an expanded parameter pack. The "type" of this
2645 // expanded parameter pack is the original expansion type, but callers
2646 // will end up using the expanded parameter pack types for type-checking.
2647 IsExpandedParameterPack = true;
2648 InstParams = TempParams;
2649 } else {
2650 // We cannot fully expand the pack expansion now, so just substitute
2651 // into the pattern.
2652 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2653
2654 LocalInstantiationScope Scope(SemaRef);
2655 InstParams = SubstTemplateParams(TempParams);
2656 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00002657 return nullptr;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002658 }
2659 } else {
Douglas Gregor38fee962009-11-11 16:58:32 +00002660 // Perform the actual substitution of template parameters within a new,
2661 // local instantiation scope.
John McCall19c1bfd2010-08-25 05:32:35 +00002662 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor38fee962009-11-11 16:58:32 +00002663 InstParams = SubstTemplateParams(TempParams);
2664 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00002665 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002666 }
2667
Douglas Gregor38fee962009-11-11 16:58:32 +00002668 // Build the template template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002669 TemplateTemplateParmDecl *Param;
2670 if (IsExpandedParameterPack)
Richard Smithb4f96252017-02-21 06:30:38 +00002671 Param = TemplateTemplateParmDecl::Create(
2672 SemaRef.Context, Owner, D->getLocation(),
2673 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2674 D->getPosition(), D->getIdentifier(), InstParams, ExpandedParams);
Richard Smith1fde8ec2012-09-07 02:06:42 +00002675 else
Richard Smithb4f96252017-02-21 06:30:38 +00002676 Param = TemplateTemplateParmDecl::Create(
2677 SemaRef.Context, Owner, D->getLocation(),
2678 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2679 D->getPosition(), D->isParameterPack(), D->getIdentifier(), InstParams);
Richard Smith52933792015-06-16 21:57:05 +00002680 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
David Majnemer89189202013-08-28 23:48:32 +00002681 NestedNameSpecifierLoc QualifierLoc =
2682 D->getDefaultArgument().getTemplateQualifierLoc();
2683 QualifierLoc =
2684 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
2685 TemplateName TName = SemaRef.SubstTemplateName(
2686 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
2687 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
2688 if (!TName.isNull())
2689 Param->setDefaultArgument(
Richard Smith1469b912015-06-10 00:29:03 +00002690 SemaRef.Context,
David Majnemer89189202013-08-28 23:48:32 +00002691 TemplateArgumentLoc(TemplateArgument(TName),
2692 D->getDefaultArgument().getTemplateQualifierLoc(),
Richard Smith1469b912015-06-10 00:29:03 +00002693 D->getDefaultArgument().getTemplateNameLoc()));
David Majnemer89189202013-08-28 23:48:32 +00002694 }
Douglas Gregorfd7c2252011-03-04 17:52:15 +00002695 Param->setAccess(AS_public);
Richard Smith71c37a82019-09-04 22:14:50 +00002696 Param->setImplicit(D->isImplicit());
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002697
2698 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor38fee962009-11-11 16:58:32 +00002699 // scope.
2700 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002701
Douglas Gregor38fee962009-11-11 16:58:32 +00002702 return Param;
2703}
2704
Douglas Gregore0b28662009-11-17 06:07:40 +00002705Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregor12441b32011-02-25 16:33:46 +00002706 // Using directives are never dependent (and never contain any types or
2707 // expressions), so they require no explicit instantiation work.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002708
Douglas Gregore0b28662009-11-17 06:07:40 +00002709 UsingDirectiveDecl *Inst
2710 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002711 D->getNamespaceKeyLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00002712 D->getQualifierLoc(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002713 D->getIdentLocation(),
2714 D->getNominatedNamespace(),
Douglas Gregore0b28662009-11-17 06:07:40 +00002715 D->getCommonAncestor());
Abramo Bagnara8843f9f2012-09-05 09:55:10 +00002716
2717 // Add the using directive to its declaration context
2718 // only if this is not a function or method.
2719 if (!Owner->isFunctionOrMethod())
2720 Owner->addDecl(Inst);
2721
Douglas Gregore0b28662009-11-17 06:07:40 +00002722 return Inst;
2723}
2724
John McCallb96ec562009-12-04 22:46:56 +00002725Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorac2e4302010-09-29 17:58:28 +00002726
2727 // The nested name specifier may be dependent, for example
2728 // template <typename T> struct t {
2729 // struct s1 { T f1(); };
2730 // struct s2 : s1 { using s1::f1; };
2731 // };
2732 // template struct t<int>;
2733 // Here, in using s1::f1, s1 refers to t<T>::s1;
2734 // we need to substitute for t<int>::s1.
Douglas Gregor0499ab62011-02-25 15:54:31 +00002735 NestedNameSpecifierLoc QualifierLoc
2736 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2737 TemplateArgs);
2738 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00002739 return nullptr;
Douglas Gregorac2e4302010-09-29 17:58:28 +00002740
Richard Smith5179eb72016-06-28 19:03:57 +00002741 // For an inheriting constructor declaration, the name of the using
2742 // declaration is the name of a constructor in this class, not in the
2743 // base class.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002744 DeclarationNameInfo NameInfo = D->getNameInfo();
Richard Smith5179eb72016-06-28 19:03:57 +00002745 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
2746 if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
2747 NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName(
2748 SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
John McCallb96ec562009-12-04 22:46:56 +00002749
John McCall84d87672009-12-10 09:41:52 +00002750 // We only need to do redeclaration lookups if we're in a class
2751 // scope (in fact, it's not really even possible in non-class
2752 // scopes).
2753 bool CheckRedeclaration = Owner->isRecord();
2754
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002755 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
Richard Smithbecb92d2017-10-10 22:33:17 +00002756 Sema::ForVisibleRedeclaration);
John McCall84d87672009-12-10 09:41:52 +00002757
John McCallb96ec562009-12-04 22:46:56 +00002758 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002759 D->getUsingLoc(),
Douglas Gregor0499ab62011-02-25 15:54:31 +00002760 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002761 NameInfo,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002762 D->hasTypename());
John McCallb96ec562009-12-04 22:46:56 +00002763
Douglas Gregor0499ab62011-02-25 15:54:31 +00002764 CXXScopeSpec SS;
2765 SS.Adopt(QualifierLoc);
John McCall84d87672009-12-10 09:41:52 +00002766 if (CheckRedeclaration) {
2767 Prev.setHideTags(false);
2768 SemaRef.LookupQualifiedName(Prev, Owner);
2769
2770 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002771 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
2772 D->hasTypename(), SS,
John McCall84d87672009-12-10 09:41:52 +00002773 D->getLocation(), Prev))
2774 NewUD->setInvalidDecl();
2775
2776 }
2777
2778 if (!NewUD->isInvalidDecl() &&
Richard Smithd8a9e372016-12-18 21:39:37 +00002779 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(),
2780 SS, NameInfo, D->getLocation()))
John McCallb96ec562009-12-04 22:46:56 +00002781 NewUD->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00002782
John McCallb96ec562009-12-04 22:46:56 +00002783 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2784 NewUD->setAccess(D->getAccess());
2785 Owner->addDecl(NewUD);
2786
John McCall84d87672009-12-10 09:41:52 +00002787 // Don't process the shadow decls for an invalid decl.
2788 if (NewUD->isInvalidDecl())
2789 return NewUD;
2790
Richard Smith5179eb72016-06-28 19:03:57 +00002791 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
Richard Smith09d5b3a2014-05-01 00:35:04 +00002792 SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
Richard Smith23d55872012-04-02 01:30:27 +00002793
John McCalla1d85502009-12-22 22:26:37 +00002794 bool isFunctionScope = Owner->isFunctionOrMethod();
2795
John McCall84d87672009-12-10 09:41:52 +00002796 // Process the shadow decls.
Aaron Ballman91cdc282014-03-13 18:07:29 +00002797 for (auto *Shadow : D->shadows()) {
Richard Smith5179eb72016-06-28 19:03:57 +00002798 // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
2799 // reconstruct it in the case where it matters.
2800 NamedDecl *OldTarget = Shadow->getTargetDecl();
2801 if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
2802 if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
2803 OldTarget = BaseShadow;
2804
John McCall84d87672009-12-10 09:41:52 +00002805 NamedDecl *InstTarget =
Richard Smithfd8634a2013-10-23 02:17:46 +00002806 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
Richard Smith5179eb72016-06-28 19:03:57 +00002807 Shadow->getLocation(), OldTarget, TemplateArgs));
Douglas Gregor55e6b312011-03-04 19:46:35 +00002808 if (!InstTarget)
Craig Topperc3ec1492014-05-26 06:22:03 +00002809 return nullptr;
John McCall84d87672009-12-10 09:41:52 +00002810
Craig Topperc3ec1492014-05-26 06:22:03 +00002811 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00002812 if (CheckRedeclaration) {
2813 if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl))
2814 continue;
Richard Smith41c79d92014-10-11 00:37:16 +00002815 } else if (UsingShadowDecl *OldPrev =
2816 getPreviousDeclForInstantiation(Shadow)) {
Richard Smithfd8634a2013-10-23 02:17:46 +00002817 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
2818 Shadow->getLocation(), OldPrev, TemplateArgs));
2819 }
John McCall84d87672009-12-10 09:41:52 +00002820
Richard Smithfd8634a2013-10-23 02:17:46 +00002821 UsingShadowDecl *InstShadow =
Craig Topperc3ec1492014-05-26 06:22:03 +00002822 SemaRef.BuildUsingShadowDecl(/*Scope*/nullptr, NewUD, InstTarget,
2823 PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00002824 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCalla1d85502009-12-22 22:26:37 +00002825
2826 if (isFunctionScope)
2827 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall84d87672009-12-10 09:41:52 +00002828 }
John McCallb96ec562009-12-04 22:46:56 +00002829
2830 return NewUD;
2831}
2832
2833Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall84d87672009-12-10 09:41:52 +00002834 // Ignore these; we handle them in bulk when processing the UsingDecl.
Craig Topperc3ec1492014-05-26 06:22:03 +00002835 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00002836}
2837
Richard Smith5179eb72016-06-28 19:03:57 +00002838Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
2839 ConstructorUsingShadowDecl *D) {
2840 // Ignore these; we handle them in bulk when processing the UsingDecl.
2841 return nullptr;
2842}
2843
Richard Smith151c4562016-12-20 21:35:28 +00002844template <typename T>
2845Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
2846 T *D, bool InstantiatingPackElement) {
2847 // If this is a pack expansion, expand it now.
2848 if (D->isPackExpansion() && !InstantiatingPackElement) {
2849 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2850 SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
2851 SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
2852
2853 // Determine whether the set of unexpanded parameter packs can and should
2854 // be expanded.
2855 bool Expand = true;
2856 bool RetainExpansion = false;
2857 Optional<unsigned> NumExpansions;
2858 if (SemaRef.CheckParameterPacksForExpansion(
2859 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
2860 Expand, RetainExpansion, NumExpansions))
2861 return nullptr;
2862
2863 // This declaration cannot appear within a function template signature,
2864 // so we can't have a partial argument list for a parameter pack.
2865 assert(!RetainExpansion &&
2866 "should never need to retain an expansion for UsingPackDecl");
2867
2868 if (!Expand) {
2869 // We cannot fully expand the pack expansion now, so substitute into the
2870 // pattern and create a new pack expansion.
2871 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2872 return instantiateUnresolvedUsingDecl(D, true);
2873 }
2874
2875 // Within a function, we don't have any normal way to check for conflicts
2876 // between shadow declarations from different using declarations in the
2877 // same pack expansion, but this is always ill-formed because all expansions
2878 // must produce (conflicting) enumerators.
2879 //
2880 // Sadly we can't just reject this in the template definition because it
2881 // could be valid if the pack is empty or has exactly one expansion.
2882 if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) {
2883 SemaRef.Diag(D->getEllipsisLoc(),
2884 diag::err_using_decl_redeclaration_expansion);
2885 return nullptr;
2886 }
2887
2888 // Instantiate the slices of this pack and build a UsingPackDecl.
2889 SmallVector<NamedDecl*, 8> Expansions;
2890 for (unsigned I = 0; I != *NumExpansions; ++I) {
2891 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2892 Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
2893 if (!Slice)
2894 return nullptr;
2895 // Note that we can still get unresolved using declarations here, if we
2896 // had arguments for all packs but the pattern also contained other
2897 // template arguments (this only happens during partial substitution, eg
2898 // into the body of a generic lambda in a function template).
2899 Expansions.push_back(cast<NamedDecl>(Slice));
2900 }
2901
2902 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
2903 if (isDeclWithinFunction(D))
2904 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
2905 return NewD;
2906 }
2907
2908 UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
2909 SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation();
2910
Douglas Gregor0499ab62011-02-25 15:54:31 +00002911 NestedNameSpecifierLoc QualifierLoc
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002912 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
Douglas Gregor0499ab62011-02-25 15:54:31 +00002913 TemplateArgs);
2914 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00002915 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002916
Anders Carlsson4bd78752009-08-28 15:18:15 +00002917 CXXScopeSpec SS;
Douglas Gregor0499ab62011-02-25 15:54:31 +00002918 SS.Adopt(QualifierLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002919
Daniel Jasper9949ead2016-12-19 10:09:25 +00002920 DeclarationNameInfo NameInfo
2921 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2922
Richard Smith151c4562016-12-20 21:35:28 +00002923 // Produce a pack expansion only if we're not instantiating a particular
2924 // slice of a pack expansion.
2925 bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
2926 SemaRef.ArgumentPackSubstitutionIndex != -1;
2927 SourceLocation EllipsisLoc =
2928 InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc();
2929
2930 NamedDecl *UD = SemaRef.BuildUsingDeclaration(
2931 /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
Erich Keanec480f302018-07-12 21:09:05 +00002932 /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
2933 ParsedAttributesView(),
Richard Smith151c4562016-12-20 21:35:28 +00002934 /*IsInstantiation*/ true);
Daniel Jasper9949ead2016-12-19 10:09:25 +00002935 if (UD)
2936 SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
2937
2938 return UD;
Richard Smith22a250c2016-12-19 04:08:53 +00002939}
2940
Richard Smith151c4562016-12-20 21:35:28 +00002941Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
2942 UnresolvedUsingTypenameDecl *D) {
2943 return instantiateUnresolvedUsingDecl(D);
2944}
2945
2946Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
2947 UnresolvedUsingValueDecl *D) {
2948 return instantiateUnresolvedUsingDecl(D);
2949}
2950
2951Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
2952 SmallVector<NamedDecl*, 8> Expansions;
2953 for (auto *UD : D->expansions()) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00002954 if (NamedDecl *NewUD =
Richard Smith151c4562016-12-20 21:35:28 +00002955 SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
George Burgess IV00f70bd2018-03-01 05:43:23 +00002956 Expansions.push_back(NewUD);
Richard Smith151c4562016-12-20 21:35:28 +00002957 else
2958 return nullptr;
2959 }
2960
2961 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
2962 if (isDeclWithinFunction(D))
2963 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
2964 return NewD;
2965}
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002966
2967Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
Richard Smith6e671422018-12-04 22:26:32 +00002968 ClassScopeFunctionSpecializationDecl *Decl) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002969 CXXMethodDecl *OldFD = Decl->getSpecialization();
Richard Smithf19a8b02019-05-02 00:49:14 +00002970 return cast_or_null<CXXMethodDecl>(
2971 VisitCXXMethodDecl(OldFD, nullptr, Decl->getTemplateArgsAsWritten()));
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002972}
2973
Alexey Bataeva769e072013-03-22 06:34:35 +00002974Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2975 OMPThreadPrivateDecl *D) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002976 SmallVector<Expr *, 5> Vars;
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002977 for (auto *I : D->varlists()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002978 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
Alexey Bataeva769e072013-03-22 06:34:35 +00002979 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002980 Vars.push_back(Var);
Alexey Bataeva769e072013-03-22 06:34:35 +00002981 }
2982
2983 OMPThreadPrivateDecl *TD =
2984 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2985
Alexey Bataevd3db6ac2014-03-07 09:46:29 +00002986 TD->setAccess(AS_public);
2987 Owner->addDecl(TD);
2988
Alexey Bataeva769e072013-03-22 06:34:35 +00002989 return TD;
2990}
2991
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002992Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
2993 SmallVector<Expr *, 5> Vars;
2994 for (auto *I : D->varlists()) {
2995 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
2996 assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr");
2997 Vars.push_back(Var);
2998 }
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002999 SmallVector<OMPClause *, 4> Clauses;
3000 // Copy map clauses from the original mapper.
3001 for (OMPClause *C : D->clauselists()) {
3002 auto *AC = cast<OMPAllocatorClause>(C);
3003 ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs);
3004 if (!NewE.isUsable())
3005 continue;
3006 OMPClause *IC = SemaRef.ActOnOpenMPAllocatorClause(
3007 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
3008 Clauses.push_back(IC);
3009 }
Alexey Bataev25ed0c02019-03-07 17:54:44 +00003010
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00003011 Sema::DeclGroupPtrTy Res = SemaRef.ActOnOpenMPAllocateDirective(
3012 D->getLocation(), Vars, Clauses, Owner);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00003013 if (Res.get().isNull())
3014 return nullptr;
3015 return Res.get().getSingleDecl();
3016}
3017
Kelvin Li1408f912018-09-26 04:28:39 +00003018Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
3019 llvm_unreachable(
3020 "Requires directive cannot be instantiated within a dependent context");
3021}
3022
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003023Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
3024 OMPDeclareReductionDecl *D) {
3025 // Instantiate type and check if it is allowed.
Alexey Bataeve6aa4692018-09-13 16:54:05 +00003026 const bool RequiresInstantiation =
3027 D->getType()->isDependentType() ||
3028 D->getType()->isInstantiationDependentType() ||
3029 D->getType()->containsUnexpandedParameterPack();
3030 QualType SubstReductionType;
3031 if (RequiresInstantiation) {
3032 SubstReductionType = SemaRef.ActOnOpenMPDeclareReductionType(
3033 D->getLocation(),
3034 ParsedType::make(SemaRef.SubstType(
3035 D->getType(), TemplateArgs, D->getLocation(), DeclarationName())));
3036 } else {
3037 SubstReductionType = D->getType();
3038 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003039 if (SubstReductionType.isNull())
3040 return nullptr;
3041 bool IsCorrect = !SubstReductionType.isNull();
3042 // Create instantiated copy.
3043 std::pair<QualType, SourceLocation> ReductionTypes[] = {
3044 std::make_pair(SubstReductionType, D->getLocation())};
3045 auto *PrevDeclInScope = D->getPrevDeclInScope();
3046 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3047 PrevDeclInScope = cast<OMPDeclareReductionDecl>(
3048 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
3049 ->get<Decl *>());
3050 }
3051 auto DRD = SemaRef.ActOnOpenMPDeclareReductionDirectiveStart(
3052 /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
3053 PrevDeclInScope);
3054 auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
Alexey Bataeve6aa4692018-09-13 16:54:05 +00003055 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
3056 if (!RequiresInstantiation) {
3057 if (Expr *Combiner = D->getCombiner()) {
3058 NewDRD->setCombinerData(D->getCombinerIn(), D->getCombinerOut());
3059 NewDRD->setCombiner(Combiner);
3060 if (Expr *Init = D->getInitializer()) {
3061 NewDRD->setInitializerData(D->getInitOrig(), D->getInitPriv());
3062 NewDRD->setInitializer(Init, D->getInitializerKind());
3063 }
3064 }
3065 (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(
3066 /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl());
3067 return NewDRD;
3068 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003069 Expr *SubstCombiner = nullptr;
3070 Expr *SubstInitializer = nullptr;
3071 // Combiners instantiation sequence.
3072 if (D->getCombiner()) {
3073 SemaRef.ActOnOpenMPDeclareReductionCombinerStart(
3074 /*S=*/nullptr, NewDRD);
Alexey Bataeve6aa4692018-09-13 16:54:05 +00003075 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3076 cast<DeclRefExpr>(D->getCombinerIn())->getDecl(),
3077 cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl());
3078 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3079 cast<DeclRefExpr>(D->getCombinerOut())->getDecl(),
3080 cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl());
3081 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00003082 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
Alexey Bataeve6aa4692018-09-13 16:54:05 +00003083 ThisContext);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003084 SubstCombiner = SemaRef.SubstExpr(D->getCombiner(), TemplateArgs).get();
3085 SemaRef.ActOnOpenMPDeclareReductionCombinerEnd(NewDRD, SubstCombiner);
3086 // Initializers instantiation sequence.
3087 if (D->getInitializer()) {
Alexey Bataev070f43a2017-09-06 14:49:58 +00003088 VarDecl *OmpPrivParm =
3089 SemaRef.ActOnOpenMPDeclareReductionInitializerStart(
3090 /*S=*/nullptr, NewDRD);
Alexey Bataeve6aa4692018-09-13 16:54:05 +00003091 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3092 cast<DeclRefExpr>(D->getInitOrig())->getDecl(),
3093 cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl());
3094 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3095 cast<DeclRefExpr>(D->getInitPriv())->getDecl(),
3096 cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl());
Alexey Bataev070f43a2017-09-06 14:49:58 +00003097 if (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit) {
3098 SubstInitializer =
3099 SemaRef.SubstExpr(D->getInitializer(), TemplateArgs).get();
3100 } else {
3101 IsCorrect = IsCorrect && OmpPrivParm->hasInit();
3102 }
3103 SemaRef.ActOnOpenMPDeclareReductionInitializerEnd(
3104 NewDRD, SubstInitializer, OmpPrivParm);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003105 }
Alexey Bataev070f43a2017-09-06 14:49:58 +00003106 IsCorrect =
3107 IsCorrect && SubstCombiner &&
3108 (!D->getInitializer() ||
3109 (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit &&
3110 SubstInitializer) ||
3111 (D->getInitializerKind() != OMPDeclareReductionDecl::CallInit &&
3112 !SubstInitializer && !SubstInitializer));
Alexey Bataeve6aa4692018-09-13 16:54:05 +00003113 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003114 IsCorrect = false;
Alexey Bataeve6aa4692018-09-13 16:54:05 +00003115 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003116
3117 (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(/*S=*/nullptr, DRD,
3118 IsCorrect);
3119
3120 return NewDRD;
3121}
3122
Michael Kruse251e1482019-02-01 20:25:04 +00003123Decl *
3124TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
3125 // Instantiate type and check if it is allowed.
3126 const bool RequiresInstantiation =
3127 D->getType()->isDependentType() ||
3128 D->getType()->isInstantiationDependentType() ||
3129 D->getType()->containsUnexpandedParameterPack();
3130 QualType SubstMapperTy;
3131 DeclarationName VN = D->getVarName();
3132 if (RequiresInstantiation) {
3133 SubstMapperTy = SemaRef.ActOnOpenMPDeclareMapperType(
3134 D->getLocation(),
3135 ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
3136 D->getLocation(), VN)));
3137 } else {
3138 SubstMapperTy = D->getType();
3139 }
3140 if (SubstMapperTy.isNull())
3141 return nullptr;
3142 // Create an instantiated copy of mapper.
3143 auto *PrevDeclInScope = D->getPrevDeclInScope();
3144 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3145 PrevDeclInScope = cast<OMPDeclareMapperDecl>(
3146 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
3147 ->get<Decl *>());
3148 }
3149 OMPDeclareMapperDecl *NewDMD = SemaRef.ActOnOpenMPDeclareMapperDirectiveStart(
3150 /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(),
3151 VN, D->getAccess(), PrevDeclInScope);
3152 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD);
3153 SmallVector<OMPClause *, 6> Clauses;
3154 bool IsCorrect = true;
3155 if (!RequiresInstantiation) {
3156 // Copy the mapper variable.
3157 NewDMD->setMapperVarRef(D->getMapperVarRef());
3158 // Copy map clauses from the original mapper.
3159 for (OMPClause *C : D->clauselists())
3160 Clauses.push_back(C);
3161 } else {
3162 // Instantiate the mapper variable.
3163 DeclarationNameInfo DirName;
3164 SemaRef.StartOpenMPDSABlock(OMPD_declare_mapper, DirName, /*S=*/nullptr,
3165 (*D->clauselist_begin())->getBeginLoc());
3166 SemaRef.ActOnOpenMPDeclareMapperDirectiveVarDecl(
3167 NewDMD, /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN);
3168 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3169 cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(),
3170 cast<DeclRefExpr>(NewDMD->getMapperVarRef())->getDecl());
3171 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3172 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3173 ThisContext);
3174 // Instantiate map clauses.
3175 for (OMPClause *C : D->clauselists()) {
3176 auto *OldC = cast<OMPMapClause>(C);
3177 SmallVector<Expr *, 4> NewVars;
3178 for (Expr *OE : OldC->varlists()) {
3179 Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get();
3180 if (!NE) {
3181 IsCorrect = false;
3182 break;
3183 }
3184 NewVars.push_back(NE);
3185 }
3186 if (!IsCorrect)
3187 break;
Michael Kruse4304e9d2019-02-19 16:38:20 +00003188 NestedNameSpecifierLoc NewQualifierLoc =
3189 SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(),
3190 TemplateArgs);
3191 CXXScopeSpec SS;
3192 SS.Adopt(NewQualifierLoc);
3193 DeclarationNameInfo NewNameInfo = SemaRef.SubstDeclarationNameInfo(
3194 OldC->getMapperIdInfo(), TemplateArgs);
3195 OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(),
3196 OldC->getEndLoc());
Michael Kruse251e1482019-02-01 20:25:04 +00003197 OMPClause *NewC = SemaRef.ActOnOpenMPMapClause(
Michael Kruse4304e9d2019-02-19 16:38:20 +00003198 OldC->getMapTypeModifiers(), OldC->getMapTypeModifiersLoc(), SS,
3199 NewNameInfo, OldC->getMapType(), OldC->isImplicitMapType(),
3200 OldC->getMapLoc(), OldC->getColonLoc(), NewVars, Locs);
Michael Kruse251e1482019-02-01 20:25:04 +00003201 Clauses.push_back(NewC);
3202 }
3203 SemaRef.EndOpenMPDSABlock(nullptr);
3204 }
3205 (void)SemaRef.ActOnOpenMPDeclareMapperDirectiveEnd(NewDMD, /*S=*/nullptr,
3206 Clauses);
3207 if (!IsCorrect)
3208 return nullptr;
3209 return NewDMD;
3210}
3211
Alexey Bataev4244be22016-02-11 05:35:55 +00003212Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
3213 OMPCapturedExprDecl * /*D*/) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00003214 llvm_unreachable("Should not be met in templates");
3215}
3216
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00003217Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003218 return VisitFunctionDecl(D, nullptr);
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00003219}
3220
Richard Smithbc491202017-02-17 20:05:37 +00003221Decl *
3222TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
Richard Smith2600c632018-05-30 20:24:10 +00003223 Decl *Inst = VisitFunctionDecl(D, nullptr);
3224 if (Inst && !D->getDescribedFunctionTemplate())
3225 Owner->addDecl(Inst);
3226 return Inst;
Richard Smithbc491202017-02-17 20:05:37 +00003227}
3228
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00003229Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003230 return VisitCXXMethodDecl(D, nullptr);
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00003231}
3232
3233Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
3234 llvm_unreachable("There are only CXXRecordDecls in C++");
3235}
3236
3237Decl *
3238TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
3239 ClassTemplateSpecializationDecl *D) {
Richard Smith8a0dde72013-12-14 01:04:22 +00003240 // As a MS extension, we permit class-scope explicit specialization
3241 // of member class templates.
3242 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
3243 assert(ClassTemplate->getDeclContext()->isRecord() &&
3244 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3245 "can only instantiate an explicit specialization "
3246 "for a member class template");
3247
3248 // Lookup the already-instantiated declaration in the instantiation
Richard Smitha6b41d72019-05-03 23:51:38 +00003249 // of the class template.
3250 ClassTemplateDecl *InstClassTemplate =
3251 cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl(
3252 D->getLocation(), ClassTemplate, TemplateArgs));
Richard Smith8a0dde72013-12-14 01:04:22 +00003253 if (!InstClassTemplate)
Craig Topperc3ec1492014-05-26 06:22:03 +00003254 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00003255
3256 // Substitute into the template arguments of the class template explicit
3257 // specialization.
3258 TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
3259 castAs<TemplateSpecializationTypeLoc>();
3260 TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
3261 Loc.getRAngleLoc());
3262 SmallVector<TemplateArgumentLoc, 4> ArgLocs;
3263 for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
3264 ArgLocs.push_back(Loc.getArgLoc(I));
3265 if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(),
3266 InstTemplateArgs, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00003267 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00003268
3269 // Check that the template argument list is well-formed for this
3270 // class template.
3271 SmallVector<TemplateArgument, 4> Converted;
3272 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
3273 D->getLocation(),
3274 InstTemplateArgs,
3275 false,
3276 Converted))
Craig Topperc3ec1492014-05-26 06:22:03 +00003277 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00003278
3279 // Figure out where to insert this class template explicit specialization
3280 // in the member template's set of class template explicit specializations.
Craig Topperc3ec1492014-05-26 06:22:03 +00003281 void *InsertPos = nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00003282 ClassTemplateSpecializationDecl *PrevDecl =
Craig Topper7e0daca2014-06-26 04:58:53 +00003283 InstClassTemplate->findSpecialization(Converted, InsertPos);
Richard Smith8a0dde72013-12-14 01:04:22 +00003284
3285 // Check whether we've already seen a conflicting instantiation of this
3286 // declaration (for instance, if there was a prior implicit instantiation).
3287 bool Ignored;
3288 if (PrevDecl &&
3289 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
3290 D->getSpecializationKind(),
3291 PrevDecl,
3292 PrevDecl->getSpecializationKind(),
3293 PrevDecl->getPointOfInstantiation(),
3294 Ignored))
Craig Topperc3ec1492014-05-26 06:22:03 +00003295 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00003296
3297 // If PrevDecl was a definition and D is also a definition, diagnose.
3298 // This happens in cases like:
3299 //
3300 // template<typename T, typename U>
3301 // struct Outer {
3302 // template<typename X> struct Inner;
3303 // template<> struct Inner<T> {};
3304 // template<> struct Inner<U> {};
3305 // };
3306 //
3307 // Outer<int, int> outer; // error: the explicit specializations of Inner
3308 // // have the same signature.
3309 if (PrevDecl && PrevDecl->getDefinition() &&
3310 D->isThisDeclarationADefinition()) {
3311 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
3312 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
3313 diag::note_previous_definition);
Craig Topperc3ec1492014-05-26 06:22:03 +00003314 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00003315 }
3316
3317 // Create the class template partial specialization declaration.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003318 ClassTemplateSpecializationDecl *InstD =
3319 ClassTemplateSpecializationDecl::Create(
3320 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
3321 D->getLocation(), InstClassTemplate, Converted, PrevDecl);
Richard Smith8a0dde72013-12-14 01:04:22 +00003322
3323 // Add this partial specialization to the set of class template partial
3324 // specializations.
3325 if (!PrevDecl)
3326 InstClassTemplate->AddSpecialization(InstD, InsertPos);
3327
3328 // Substitute the nested name specifier, if any.
3329 if (SubstQualifier(D, InstD))
Craig Topperc3ec1492014-05-26 06:22:03 +00003330 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00003331
3332 // Build the canonical type that describes the converted template
3333 // arguments of the class template explicit specialization.
3334 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00003335 TemplateName(InstClassTemplate), Converted,
Richard Smith8a0dde72013-12-14 01:04:22 +00003336 SemaRef.Context.getRecordType(InstD));
3337
3338 // Build the fully-sugared type for this class template
3339 // specialization as the user wrote in the specialization
3340 // itself. This means that we'll pretty-print the type retrieved
3341 // from the specialization's declaration the way that the user
3342 // actually wrote the specialization, rather than formatting the
3343 // name based on the "canonical" representation used to store the
3344 // template arguments in the specialization.
3345 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
3346 TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
3347 CanonType);
3348
3349 InstD->setAccess(D->getAccess());
3350 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
3351 InstD->setSpecializationKind(D->getSpecializationKind());
3352 InstD->setTypeAsWritten(WrittenTy);
3353 InstD->setExternLoc(D->getExternLoc());
3354 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
3355
3356 Owner->addDecl(InstD);
3357
3358 // Instantiate the members of the class-scope explicit specialization eagerly.
3359 // We don't have support for lazy instantiation of an explicit specialization
3360 // yet, and MSVC eagerly instantiates in this case.
Richard Smitha6b41d72019-05-03 23:51:38 +00003361 // FIXME: This is wrong in standard C++.
Richard Smith8a0dde72013-12-14 01:04:22 +00003362 if (D->isThisDeclarationADefinition() &&
3363 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
3364 TSK_ImplicitInstantiation,
3365 /*Complain=*/true))
Craig Topperc3ec1492014-05-26 06:22:03 +00003366 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00003367
3368 return InstD;
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00003369}
3370
Larisse Voufo39a1e502013-08-06 01:03:05 +00003371Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3372 VarTemplateSpecializationDecl *D) {
3373
3374 TemplateArgumentListInfo VarTemplateArgsInfo;
3375 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
3376 assert(VarTemplate &&
3377 "A template specialization without specialized template?");
3378
Richard Smitha6b41d72019-05-03 23:51:38 +00003379 VarTemplateDecl *InstVarTemplate =
3380 cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl(
3381 D->getLocation(), VarTemplate, TemplateArgs));
3382 if (!InstVarTemplate)
3383 return nullptr;
3384
Larisse Voufo39a1e502013-08-06 01:03:05 +00003385 // Substitute the current template arguments.
3386 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
3387 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
3388 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
3389
3390 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
3391 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00003392 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003393
3394 // Check that the template argument list is well-formed for this template.
3395 SmallVector<TemplateArgument, 4> Converted;
Richard Smitha6b41d72019-05-03 23:51:38 +00003396 if (SemaRef.CheckTemplateArgumentList(InstVarTemplate, D->getLocation(),
3397 VarTemplateArgsInfo, false, Converted))
Craig Topperc3ec1492014-05-26 06:22:03 +00003398 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003399
Richard Smitha6b41d72019-05-03 23:51:38 +00003400 // Check whether we've already seen a declaration of this specialization.
Craig Topperc3ec1492014-05-26 06:22:03 +00003401 void *InsertPos = nullptr;
Richard Smitha6b41d72019-05-03 23:51:38 +00003402 VarTemplateSpecializationDecl *PrevDecl =
3403 InstVarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003404
Richard Smitha6b41d72019-05-03 23:51:38 +00003405 // Check whether we've already seen a conflicting instantiation of this
3406 // declaration (for instance, if there was a prior implicit instantiation).
3407 bool Ignored;
3408 if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl(
3409 D->getLocation(), D->getSpecializationKind(), PrevDecl,
3410 PrevDecl->getSpecializationKind(),
3411 PrevDecl->getPointOfInstantiation(), Ignored))
3412 return nullptr;
3413
3414 return VisitVarTemplateSpecializationDecl(
3415 InstVarTemplate, D, InsertPos, VarTemplateArgsInfo, Converted, PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003416}
3417
3418Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3419 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
3420 const TemplateArgumentListInfo &TemplateArgsInfo,
Richard Smitha6b41d72019-05-03 23:51:38 +00003421 ArrayRef<TemplateArgument> Converted,
3422 VarTemplateSpecializationDecl *PrevDecl) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003423
Larisse Voufo39a1e502013-08-06 01:03:05 +00003424 // Do substitution on the type of the declaration
3425 TypeSourceInfo *DI =
3426 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
3427 D->getTypeSpecStartLoc(), D->getDeclName());
3428 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00003429 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003430
3431 if (DI->getType()->isFunctionType()) {
3432 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
3433 << D->isStaticDataMember() << DI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00003434 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003435 }
3436
3437 // Build the instantiated declaration
3438 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
3439 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
David Majnemer8b622692016-07-03 21:17:51 +00003440 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003441 Var->setTemplateArgsInfo(TemplateArgsInfo);
Richard Smith8809a0c2013-09-27 20:14:12 +00003442 if (InsertPos)
3443 VarTemplate->AddSpecialization(Var, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003444
3445 // Substitute the nested name specifier, if any.
3446 if (SubstQualifier(D, Var))
Craig Topperc3ec1492014-05-26 06:22:03 +00003447 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003448
Richard Smitha6b41d72019-05-03 23:51:38 +00003449 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
3450 StartingScope, false, PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003451
3452 return Var;
3453}
3454
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00003455Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
3456 llvm_unreachable("@defs is not supported in Objective-C++");
3457}
3458
3459Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
3460 // FIXME: We need to be able to instantiate FriendTemplateDecls.
3461 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
3462 DiagnosticsEngine::Error,
3463 "cannot instantiate %0 yet");
3464 SemaRef.Diag(D->getLocation(), DiagID)
3465 << D->getDeclKindName();
3466
Craig Topperc3ec1492014-05-26 06:22:03 +00003467 return nullptr;
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00003468}
3469
Saar Razd7aae332019-07-10 21:25:49 +00003470Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) {
3471 llvm_unreachable("Concept definitions cannot reside inside a template");
3472}
3473
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00003474Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
3475 llvm_unreachable("Unexpected decl");
3476}
3477
John McCall76d824f2009-08-25 22:02:44 +00003478Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregor01afeef2009-08-28 20:31:08 +00003479 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregord002c7b2009-05-11 23:53:27 +00003480 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor71ad4772010-02-16 19:28:15 +00003481 if (D->isInvalidDecl())
Craig Topperc3ec1492014-05-26 06:22:03 +00003482 return nullptr;
Douglas Gregor71ad4772010-02-16 19:28:15 +00003483
Richard Smith26a92d52019-08-26 18:18:07 +00003484 Decl *SubstD;
3485 runWithSufficientStackSpace(D->getLocation(), [&] {
3486 SubstD = Instantiator.Visit(D);
3487 });
3488 return SubstD;
Douglas Gregord7e7a512009-03-17 21:15:40 +00003489}
3490
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003491/// Instantiates a nested template parameter list in the current
John McCall87a44eb2009-08-20 01:44:21 +00003492/// instantiation context.
3493///
3494/// \param L The parameter list to instantiate
3495///
3496/// \returns NULL if there was an error
3497TemplateParameterList *
John McCall76d824f2009-08-25 22:02:44 +00003498TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCall87a44eb2009-08-20 01:44:21 +00003499 // Get errors for all the parameters before bailing out.
3500 bool Invalid = false;
3501
3502 unsigned N = L->size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003503 typedef SmallVector<NamedDecl *, 8> ParamVector;
John McCall87a44eb2009-08-20 01:44:21 +00003504 ParamVector Params;
3505 Params.reserve(N);
Davide Italiano18960b92015-07-02 19:20:11 +00003506 for (auto &P : *L) {
3507 NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
John McCall87a44eb2009-08-20 01:44:21 +00003508 Params.push_back(D);
Douglas Gregore62e6a02009-11-11 19:13:48 +00003509 Invalid = Invalid || !D || D->isInvalidDecl();
John McCall87a44eb2009-08-20 01:44:21 +00003510 }
3511
3512 // Clean up if we had an error.
Douglas Gregorb412e172010-07-25 18:17:45 +00003513 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +00003514 return nullptr;
John McCall87a44eb2009-08-20 01:44:21 +00003515
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00003516 // Note: we substitute into associated constraints later
3517 Expr *const UninstantiatedRequiresClause = L->getRequiresClause();
3518
John McCall87a44eb2009-08-20 01:44:21 +00003519 TemplateParameterList *InstL
3520 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
David Majnemer902f8c62015-12-27 07:16:27 +00003521 L->getLAngleLoc(), Params,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00003522 L->getRAngleLoc(),
3523 UninstantiatedRequiresClause);
John McCall87a44eb2009-08-20 01:44:21 +00003524 return InstL;
Mike Stump11289f42009-09-09 15:08:12 +00003525}
John McCall87a44eb2009-08-20 01:44:21 +00003526
Richard Smith5d331022018-03-08 01:07:33 +00003527TemplateParameterList *
3528Sema::SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
3529 const MultiLevelTemplateArgumentList &TemplateArgs) {
3530 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
3531 return Instantiator.SubstTemplateParams(Params);
3532}
3533
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003534/// Instantiate the declaration of a class template partial
Douglas Gregor21610382009-10-29 00:04:11 +00003535/// specialization.
3536///
3537/// \param ClassTemplate the (instantiated) class template that is partially
3538// specialized by the instantiation of \p PartialSpec.
3539///
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003540/// \param PartialSpec the (uninstantiated) class template partial
Douglas Gregor21610382009-10-29 00:04:11 +00003541/// specialization that we are instantiating.
3542///
Douglas Gregor869853e2010-11-10 19:44:59 +00003543/// \returns The instantiated partial specialization, if successful; otherwise,
3544/// NULL to indicate an error.
3545ClassTemplatePartialSpecializationDecl *
Douglas Gregor21610382009-10-29 00:04:11 +00003546TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
3547 ClassTemplateDecl *ClassTemplate,
3548 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor954de172009-10-31 17:21:17 +00003549 // Create a local instantiation scope for this class template partial
3550 // specialization, which will contain the instantiations of the template
3551 // parameters.
John McCall19c1bfd2010-08-25 05:32:35 +00003552 LocalInstantiationScope Scope(SemaRef);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003553
Douglas Gregor21610382009-10-29 00:04:11 +00003554 // Substitute into the template parameters of the class template partial
3555 // specialization.
3556 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
3557 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
3558 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00003559 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003560
Douglas Gregor21610382009-10-29 00:04:11 +00003561 // Substitute into the template arguments of the class template partial
3562 // specialization.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00003563 const ASTTemplateArgumentListInfo *TemplArgInfo
3564 = PartialSpec->getTemplateArgsAsWritten();
3565 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
3566 TemplArgInfo->RAngleLoc);
3567 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
3568 TemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00003569 InstTemplateArgs, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00003570 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003571
Douglas Gregor21610382009-10-29 00:04:11 +00003572 // Check that the template argument list is well-formed for this
3573 // class template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003574 SmallVector<TemplateArgument, 4> Converted;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003575 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
Douglas Gregor21610382009-10-29 00:04:11 +00003576 PartialSpec->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003577 InstTemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00003578 false,
3579 Converted))
Craig Topperc3ec1492014-05-26 06:22:03 +00003580 return nullptr;
Douglas Gregor21610382009-10-29 00:04:11 +00003581
Richard Smith57aae072016-12-28 02:37:25 +00003582 // Check these arguments are valid for a template partial specialization.
3583 if (SemaRef.CheckTemplatePartialSpecializationArgs(
3584 PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
3585 Converted))
3586 return nullptr;
3587
Douglas Gregor21610382009-10-29 00:04:11 +00003588 // Figure out where to insert this class template partial specialization
3589 // in the member template's set of class template partial specializations.
Craig Topperc3ec1492014-05-26 06:22:03 +00003590 void *InsertPos = nullptr;
Douglas Gregor21610382009-10-29 00:04:11 +00003591 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00003592 = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003593
Douglas Gregor21610382009-10-29 00:04:11 +00003594 // Build the canonical type that describes the converted template
3595 // arguments of the class template partial specialization.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003596 QualType CanonType
Douglas Gregor21610382009-10-29 00:04:11 +00003597 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
David Majnemer6fbeee32016-07-07 04:43:07 +00003598 Converted);
Douglas Gregor21610382009-10-29 00:04:11 +00003599
3600 // Build the fully-sugared type for this class template
3601 // specialization as the user wrote in the specialization
3602 // itself. This means that we'll pretty-print the type retrieved
3603 // from the specialization's declaration the way that the user
3604 // actually wrote the specialization, rather than formatting the
3605 // name based on the "canonical" representation used to store the
3606 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00003607 TypeSourceInfo *WrittenTy
3608 = SemaRef.Context.getTemplateSpecializationTypeInfo(
3609 TemplateName(ClassTemplate),
3610 PartialSpec->getLocation(),
John McCall6b51f282009-11-23 01:53:49 +00003611 InstTemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00003612 CanonType);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003613
Douglas Gregor21610382009-10-29 00:04:11 +00003614 if (PrevDecl) {
3615 // We've already seen a partial specialization with the same template
3616 // parameters and template arguments. This can happen, for example, when
3617 // substituting the outer template arguments ends up causing two
3618 // class template partial specializations of a member class template
3619 // to have identical forms, e.g.,
3620 //
3621 // template<typename T, typename U>
3622 // struct Outer {
3623 // template<typename X, typename Y> struct Inner;
3624 // template<typename Y> struct Inner<T, Y>;
3625 // template<typename Y> struct Inner<U, Y>;
3626 // };
3627 //
3628 // Outer<int, int> outer; // error: the partial specializations of Inner
3629 // // have the same signature.
3630 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregor869853e2010-11-10 19:44:59 +00003631 << WrittenTy->getType();
Douglas Gregor21610382009-10-29 00:04:11 +00003632 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
3633 << SemaRef.Context.getTypeDeclType(PrevDecl);
Craig Topperc3ec1492014-05-26 06:22:03 +00003634 return nullptr;
Douglas Gregor21610382009-10-29 00:04:11 +00003635 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003636
3637
Douglas Gregor21610382009-10-29 00:04:11 +00003638 // Create the class template partial specialization declaration.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003639 ClassTemplatePartialSpecializationDecl *InstPartialSpec =
3640 ClassTemplatePartialSpecializationDecl::Create(
3641 SemaRef.Context, PartialSpec->getTagKind(), Owner,
3642 PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
3643 ClassTemplate, Converted, InstTemplateArgs, CanonType, nullptr);
John McCall3e11ebe2010-03-15 10:12:16 +00003644 // Substitute the nested name specifier, if any.
3645 if (SubstQualifier(PartialSpec, InstPartialSpec))
Craig Topperc3ec1492014-05-26 06:22:03 +00003646 return nullptr;
John McCall3e11ebe2010-03-15 10:12:16 +00003647
Douglas Gregor21610382009-10-29 00:04:11 +00003648 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor6044d692010-05-19 17:02:24 +00003649 InstPartialSpec->setTypeAsWritten(WrittenTy);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003650
Richard Smith57aae072016-12-28 02:37:25 +00003651 // Check the completed partial specialization.
3652 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
3653
Douglas Gregor21610382009-10-29 00:04:11 +00003654 // Add this partial specialization to the set of class template partial
3655 // specializations.
Craig Topperc3ec1492014-05-26 06:22:03 +00003656 ClassTemplate->AddPartialSpecialization(InstPartialSpec,
3657 /*InsertPos=*/nullptr);
Douglas Gregor869853e2010-11-10 19:44:59 +00003658 return InstPartialSpec;
Douglas Gregor21610382009-10-29 00:04:11 +00003659}
3660
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003661/// Instantiate the declaration of a variable template partial
Larisse Voufo39a1e502013-08-06 01:03:05 +00003662/// specialization.
3663///
3664/// \param VarTemplate the (instantiated) variable template that is partially
3665/// specialized by the instantiation of \p PartialSpec.
3666///
3667/// \param PartialSpec the (uninstantiated) variable template partial
3668/// specialization that we are instantiating.
3669///
3670/// \returns The instantiated partial specialization, if successful; otherwise,
3671/// NULL to indicate an error.
3672VarTemplatePartialSpecializationDecl *
3673TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
3674 VarTemplateDecl *VarTemplate,
3675 VarTemplatePartialSpecializationDecl *PartialSpec) {
3676 // Create a local instantiation scope for this variable template partial
3677 // specialization, which will contain the instantiations of the template
3678 // parameters.
3679 LocalInstantiationScope Scope(SemaRef);
3680
3681 // Substitute into the template parameters of the variable template partial
3682 // specialization.
3683 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
3684 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
3685 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00003686 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003687
3688 // Substitute into the template arguments of the variable template partial
3689 // specialization.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00003690 const ASTTemplateArgumentListInfo *TemplArgInfo
3691 = PartialSpec->getTemplateArgsAsWritten();
3692 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
3693 TemplArgInfo->RAngleLoc);
3694 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
3695 TemplArgInfo->NumTemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00003696 InstTemplateArgs, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00003697 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003698
3699 // Check that the template argument list is well-formed for this
3700 // class template.
3701 SmallVector<TemplateArgument, 4> Converted;
3702 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
3703 InstTemplateArgs, false, Converted))
Craig Topperc3ec1492014-05-26 06:22:03 +00003704 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003705
Richard Smith57aae072016-12-28 02:37:25 +00003706 // Check these arguments are valid for a template partial specialization.
3707 if (SemaRef.CheckTemplatePartialSpecializationArgs(
3708 PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
3709 Converted))
3710 return nullptr;
3711
Larisse Voufo39a1e502013-08-06 01:03:05 +00003712 // Figure out where to insert this variable template partial specialization
3713 // in the member template's set of variable template partial specializations.
Craig Topperc3ec1492014-05-26 06:22:03 +00003714 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003715 VarTemplateSpecializationDecl *PrevDecl =
Craig Topper7e0daca2014-06-26 04:58:53 +00003716 VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003717
3718 // Build the canonical type that describes the converted template
3719 // arguments of the variable template partial specialization.
3720 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00003721 TemplateName(VarTemplate), Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003722
3723 // Build the fully-sugared type for this variable template
3724 // specialization as the user wrote in the specialization
3725 // itself. This means that we'll pretty-print the type retrieved
3726 // from the specialization's declaration the way that the user
3727 // actually wrote the specialization, rather than formatting the
3728 // name based on the "canonical" representation used to store the
3729 // template arguments in the specialization.
3730 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
3731 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
3732 CanonType);
3733
3734 if (PrevDecl) {
3735 // We've already seen a partial specialization with the same template
3736 // parameters and template arguments. This can happen, for example, when
3737 // substituting the outer template arguments ends up causing two
3738 // variable template partial specializations of a member variable template
3739 // to have identical forms, e.g.,
3740 //
3741 // template<typename T, typename U>
3742 // struct Outer {
3743 // template<typename X, typename Y> pair<X,Y> p;
3744 // template<typename Y> pair<T, Y> p;
3745 // template<typename Y> pair<U, Y> p;
3746 // };
3747 //
3748 // Outer<int, int> outer; // error: the partial specializations of Inner
3749 // // have the same signature.
3750 SemaRef.Diag(PartialSpec->getLocation(),
3751 diag::err_var_partial_spec_redeclared)
3752 << WrittenTy->getType();
3753 SemaRef.Diag(PrevDecl->getLocation(),
3754 diag::note_var_prev_partial_spec_here);
Craig Topperc3ec1492014-05-26 06:22:03 +00003755 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003756 }
3757
3758 // Do substitution on the type of the declaration
3759 TypeSourceInfo *DI = SemaRef.SubstType(
3760 PartialSpec->getTypeSourceInfo(), TemplateArgs,
3761 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
3762 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00003763 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003764
3765 if (DI->getType()->isFunctionType()) {
3766 SemaRef.Diag(PartialSpec->getLocation(),
3767 diag::err_variable_instantiates_to_function)
3768 << PartialSpec->isStaticDataMember() << DI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00003769 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003770 }
3771
3772 // Create the variable template partial specialization declaration.
3773 VarTemplatePartialSpecializationDecl *InstPartialSpec =
3774 VarTemplatePartialSpecializationDecl::Create(
3775 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
3776 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
David Majnemer8b622692016-07-03 21:17:51 +00003777 DI, PartialSpec->getStorageClass(), Converted, InstTemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003778
3779 // Substitute the nested name specifier, if any.
3780 if (SubstQualifier(PartialSpec, InstPartialSpec))
Craig Topperc3ec1492014-05-26 06:22:03 +00003781 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003782
3783 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
3784 InstPartialSpec->setTypeAsWritten(WrittenTy);
3785
Richard Smith57aae072016-12-28 02:37:25 +00003786 // Check the completed partial specialization.
3787 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
3788
Larisse Voufo39a1e502013-08-06 01:03:05 +00003789 // Add this partial specialization to the set of variable template partial
3790 // specializations. The instantiation of the initializer is not necessary.
Craig Topperc3ec1492014-05-26 06:22:03 +00003791 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
Larisse Voufo4cda4612013-08-22 00:28:27 +00003792
Larisse Voufo4cda4612013-08-22 00:28:27 +00003793 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
Richard Smith541b38b2013-09-20 01:15:31 +00003794 LateAttrs, Owner, StartingScope);
Larisse Voufo4cda4612013-08-22 00:28:27 +00003795
Larisse Voufo39a1e502013-08-06 01:03:05 +00003796 return InstPartialSpec;
3797}
3798
John McCall58f10c32010-03-11 09:03:00 +00003799TypeSourceInfo*
John McCall76d824f2009-08-25 22:02:44 +00003800TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003801 SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall58f10c32010-03-11 09:03:00 +00003802 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
3803 assert(OldTInfo && "substituting function without type source info");
3804 assert(Params.empty() && "parameter vector is non-empty at start");
Craig Topperc3ec1492014-05-26 06:22:03 +00003805
3806 CXXRecordDecl *ThisContext = nullptr;
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00003807 Qualifiers ThisTypeQuals;
Douglas Gregor3024f072012-04-16 07:05:22 +00003808 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Richard Smithc3d2ebb2013-06-07 02:33:37 +00003809 ThisContext = cast<CXXRecordDecl>(Owner);
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00003810 ThisTypeQuals = Method->getMethodQualifiers();
Douglas Gregor3024f072012-04-16 07:05:22 +00003811 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003812
John McCallb29f78f2010-04-09 17:38:44 +00003813 TypeSourceInfo *NewTInfo
3814 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
3815 D->getTypeSpecStartLoc(),
Douglas Gregor3024f072012-04-16 07:05:22 +00003816 D->getDeclName(),
3817 ThisContext, ThisTypeQuals);
John McCall58f10c32010-03-11 09:03:00 +00003818 if (!NewTInfo)
Craig Topperc3ec1492014-05-26 06:22:03 +00003819 return nullptr;
Douglas Gregor21342092009-03-24 00:38:23 +00003820
Reid Klecknera09e44c2013-07-31 21:00:18 +00003821 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
3822 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
3823 if (NewTInfo != OldTInfo) {
3824 // Get parameters from the new type info.
Abramo Bagnaraa44c9022010-12-13 22:27:55 +00003825 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +00003826 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
Richard Smith198223b2012-07-18 01:29:05 +00003827 unsigned NewIdx = 0;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003828 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
Douglas Gregorf3010112011-01-07 16:43:16 +00003829 OldIdx != NumOldParams; ++OldIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003830 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
Richard Smith198223b2012-07-18 01:29:05 +00003831 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
3832
David Blaikie05785d12013-02-20 22:23:23 +00003833 Optional<unsigned> NumArgumentsInExpansion;
Richard Smith198223b2012-07-18 01:29:05 +00003834 if (OldParam->isParameterPack())
3835 NumArgumentsInExpansion =
3836 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
3837 TemplateArgs);
3838 if (!NumArgumentsInExpansion) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003839 // Simple case: normal parameter, or a parameter pack that's
Douglas Gregorf3010112011-01-07 16:43:16 +00003840 // instantiated to a (still-dependent) parameter pack.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003841 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
Douglas Gregorf3010112011-01-07 16:43:16 +00003842 Params.push_back(NewParam);
Richard Smith198223b2012-07-18 01:29:05 +00003843 Scope->InstantiatedLocal(OldParam, NewParam);
3844 } else {
3845 // Parameter pack expansion: make the instantiation an argument pack.
3846 Scope->MakeInstantiatedLocalArgPack(OldParam);
3847 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003848 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
Richard Smith198223b2012-07-18 01:29:05 +00003849 Params.push_back(NewParam);
3850 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
3851 }
Douglas Gregorf3010112011-01-07 16:43:16 +00003852 }
Douglas Gregor95c70ec2010-05-03 15:32:18 +00003853 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00003854 } else {
3855 // The function type itself was not dependent and therefore no
3856 // substitution occurred. However, we still need to instantiate
3857 // the function parameters themselves.
3858 const FunctionProtoType *OldProto =
3859 cast<FunctionProtoType>(OldProtoLoc.getType());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003860 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
3861 ++i) {
3862 ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
Reid Klecknera09e44c2013-07-31 21:00:18 +00003863 if (!OldParam) {
3864 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
Alp Toker9cacbab2014-01-20 20:26:09 +00003865 D, D->getLocation(), OldProto->getParamType(i)));
Reid Klecknera09e44c2013-07-31 21:00:18 +00003866 continue;
3867 }
3868
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00003869 ParmVarDecl *Parm =
Reid Klecknera09e44c2013-07-31 21:00:18 +00003870 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
Douglas Gregor95c70ec2010-05-03 15:32:18 +00003871 if (!Parm)
Craig Topperc3ec1492014-05-26 06:22:03 +00003872 return nullptr;
Douglas Gregor95c70ec2010-05-03 15:32:18 +00003873 Params.push_back(Parm);
3874 }
Douglas Gregor940bca72010-04-12 07:48:19 +00003875 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00003876 } else {
3877 // If the type of this function, after ignoring parentheses, is not
3878 // *directly* a function type, then we're instantiating a function that
3879 // was declared via a typedef or with attributes, e.g.,
3880 //
3881 // typedef int functype(int, int);
3882 // functype func;
3883 // int __cdecl meth(int, int);
3884 //
3885 // In this case, we'll just go instantiate the ParmVarDecls that we
3886 // synthesized in the method declaration.
3887 SmallVector<QualType, 4> ParamTypes;
John McCallc8e321d2016-03-01 02:09:25 +00003888 Sema::ExtParameterInfoBuilder ExtParamInfos;
David Majnemer59f77922016-06-24 04:05:48 +00003889 if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
3890 TemplateArgs, ParamTypes, &Params,
3891 ExtParamInfos))
Craig Topperc3ec1492014-05-26 06:22:03 +00003892 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00003893 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00003894
John McCall58f10c32010-03-11 09:03:00 +00003895 return NewTInfo;
Douglas Gregor21342092009-03-24 00:38:23 +00003896}
3897
Richard Smithf623c962012-04-17 00:58:00 +00003898/// Introduce the instantiated function parameters into the local
3899/// instantiation scope, and set the parameter names to those used
3900/// in the template.
Richard Smith2e321552014-11-12 02:00:47 +00003901static bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
Richard Smithf623c962012-04-17 00:58:00 +00003902 const FunctionDecl *PatternDecl,
3903 LocalInstantiationScope &Scope,
3904 const MultiLevelTemplateArgumentList &TemplateArgs) {
3905 unsigned FParamIdx = 0;
3906 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
3907 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
3908 if (!PatternParam->isParameterPack()) {
3909 // Simple case: not a parameter pack.
3910 assert(FParamIdx < Function->getNumParams());
3911 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
Richard Smith2e321552014-11-12 02:00:47 +00003912 FunctionParam->setDeclName(PatternParam->getDeclName());
Richard Smithaae40582014-03-13 00:28:45 +00003913 // If the parameter's type is not dependent, update it to match the type
3914 // in the pattern. They can differ in top-level cv-qualifiers, and we want
3915 // the pattern's type here. If the type is dependent, they can't differ,
Richard Smith2e321552014-11-12 02:00:47 +00003916 // per core issue 1668. Substitute into the type from the pattern, in case
3917 // it's instantiation-dependent.
Richard Smithaae40582014-03-13 00:28:45 +00003918 // FIXME: Updating the type to work around this is at best fragile.
Richard Smith2e321552014-11-12 02:00:47 +00003919 if (!PatternDecl->getType()->isDependentType()) {
3920 QualType T = S.SubstType(PatternParam->getType(), TemplateArgs,
3921 FunctionParam->getLocation(),
3922 FunctionParam->getDeclName());
3923 if (T.isNull())
3924 return true;
3925 FunctionParam->setType(T);
3926 }
Richard Smithaae40582014-03-13 00:28:45 +00003927
Richard Smithf623c962012-04-17 00:58:00 +00003928 Scope.InstantiatedLocal(PatternParam, FunctionParam);
3929 ++FParamIdx;
3930 continue;
3931 }
3932
3933 // Expand the parameter pack.
3934 Scope.MakeInstantiatedLocalArgPack(PatternParam);
David Blaikie05785d12013-02-20 22:23:23 +00003935 Optional<unsigned> NumArgumentsInExpansion
Richard Smithf623c962012-04-17 00:58:00 +00003936 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
Richard Trieuef1e06d2019-03-15 04:26:02 +00003937 if (NumArgumentsInExpansion) {
3938 QualType PatternType =
3939 PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
3940 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
3941 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
3942 FunctionParam->setDeclName(PatternParam->getDeclName());
3943 if (!PatternDecl->getType()->isDependentType()) {
3944 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg);
3945 QualType T = S.SubstType(PatternType, TemplateArgs,
3946 FunctionParam->getLocation(),
3947 FunctionParam->getDeclName());
3948 if (T.isNull())
3949 return true;
3950 FunctionParam->setType(T);
3951 }
Richard Smith2e321552014-11-12 02:00:47 +00003952
Richard Trieuef1e06d2019-03-15 04:26:02 +00003953 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
3954 ++FParamIdx;
3955 }
Richard Smithf623c962012-04-17 00:58:00 +00003956 }
3957 }
Richard Smithf623c962012-04-17 00:58:00 +00003958
Richard Smith2e321552014-11-12 02:00:47 +00003959 return false;
Richard Smithf623c962012-04-17 00:58:00 +00003960}
3961
3962void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
3963 FunctionDecl *Decl) {
Richard Smithd3729422012-04-19 00:08:28 +00003964 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
3965 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
Richard Smithf623c962012-04-17 00:58:00 +00003966 return;
3967
3968 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
3969 InstantiatingTemplate::ExceptionSpecification());
Alp Tokerd4a72d52013-10-08 08:09:04 +00003970 if (Inst.isInvalid()) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003971 // We hit the instantiation depth limit. Clear the exception specification
3972 // so that our callers don't have to cope with EST_Uninstantiated.
Richard Smith8acb4282014-07-31 21:57:55 +00003973 UpdateExceptionSpec(Decl, EST_None);
Richard Smithf623c962012-04-17 00:58:00 +00003974 return;
Richard Smithd3b5c9082012-07-27 04:22:15 +00003975 }
Richard Smith54f18e82016-08-31 02:15:21 +00003976 if (Inst.isAlreadyInstantiating()) {
3977 // This exception specification indirectly depends on itself. Reject.
3978 // FIXME: Corresponding rule in the standard?
3979 Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
3980 UpdateExceptionSpec(Decl, EST_None);
3981 return;
3982 }
Richard Smithf623c962012-04-17 00:58:00 +00003983
3984 // Enter the scope of this instantiation. We don't use
3985 // PushDeclContext because we don't have a scope.
3986 Sema::ContextRAII savedContext(*this, Decl);
3987 LocalInstantiationScope Scope(*this);
3988
3989 MultiLevelTemplateArgumentList TemplateArgs =
Craig Topperc3ec1492014-05-26 06:22:03 +00003990 getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true);
Richard Smithf623c962012-04-17 00:58:00 +00003991
Richard Smithd3729422012-04-19 00:08:28 +00003992 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
Richard Smith2e321552014-11-12 02:00:47 +00003993 if (addInstantiatedParametersToScope(*this, Decl, Template, Scope,
3994 TemplateArgs)) {
3995 UpdateExceptionSpec(Decl, EST_None);
3996 return;
3997 }
Richard Smithf623c962012-04-17 00:58:00 +00003998
Richard Smith2e321552014-11-12 02:00:47 +00003999 SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
4000 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +00004001}
4002
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004003/// Initializes the common fields of an instantiation function
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004004/// declaration (New) from the corresponding fields of its template (Tmpl).
4005///
4006/// \returns true if there was an error
Mike Stump11289f42009-09-09 15:08:12 +00004007bool
4008TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004009 FunctionDecl *Tmpl) {
David Blaikie5a0956e2012-07-16 18:50:45 +00004010 if (Tmpl->isDeleted())
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004011 New->setDeletedAsWritten();
Mike Stump11289f42009-09-09 15:08:12 +00004012
Richard Smith32918772017-02-14 00:25:28 +00004013 New->setImplicit(Tmpl->isImplicit());
4014
David Majnemerdbc0c8f2013-12-04 09:01:55 +00004015 // Forward the mangling number from the template to the instantiated decl.
4016 SemaRef.Context.setManglingNumber(New,
4017 SemaRef.Context.getManglingNumber(Tmpl));
4018
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00004019 // If we are performing substituting explicitly-specified template arguments
4020 // or deduced template arguments into a function template and we reach this
4021 // point, we are now past the point where SFINAE applies and have committed
Mike Stump11289f42009-09-09 15:08:12 +00004022 // to keeping the new function template specialization. We therefore
4023 // convert the active template instantiation for the function template
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00004024 // into a template instantiation for this specific function template
4025 // specialization, which is not a SFINAE context, so that we diagnose any
4026 // further errors in the declaration itself.
Richard Smith696e3122017-02-23 01:43:54 +00004027 typedef Sema::CodeSynthesisContext ActiveInstType;
4028 ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00004029 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
4030 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump11289f42009-09-09 15:08:12 +00004031 if (FunctionTemplateDecl *FunTmpl
Nick Lewyckycc8990f2012-11-16 08:40:59 +00004032 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
Mike Stump11289f42009-09-09 15:08:12 +00004033 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00004034 "Deduction from the wrong function template?");
Daniel Dunbar54c59642009-07-16 22:10:11 +00004035 (void) FunTmpl;
Gabor Horvath207e7b12018-02-10 14:04:45 +00004036 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00004037 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
Nick Lewyckycc8990f2012-11-16 08:40:59 +00004038 ActiveInst.Entity = New;
Gabor Horvath207e7b12018-02-10 14:04:45 +00004039 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00004040 }
4041 }
Mike Stump11289f42009-09-09 15:08:12 +00004042
Douglas Gregor049bdca2009-12-08 17:45:32 +00004043 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
4044 assert(Proto && "Function template without prototype?");
4045
Sebastian Redlfa453cf2011-03-12 11:50:43 +00004046 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
John McCalldb40c7f2010-12-14 08:05:40 +00004047 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00004048
Richard Smithf623c962012-04-17 00:58:00 +00004049 // DR1330: In C++11, defer instantiation of a non-trivial
4050 // exception specification.
Serge Pavlov3739f5e72015-06-29 17:50:19 +00004051 // DR1484: Local classes and their members are instantiated along with the
4052 // containing function.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004053 if (SemaRef.getLangOpts().CPlusPlus11 &&
Richard Smith8acb4282014-07-31 21:57:55 +00004054 EPI.ExceptionSpec.Type != EST_None &&
4055 EPI.ExceptionSpec.Type != EST_DynamicNone &&
Serge Pavlov3739f5e72015-06-29 17:50:19 +00004056 EPI.ExceptionSpec.Type != EST_BasicNoexcept &&
Serge Pavlov73c6a242015-08-23 10:22:28 +00004057 !Tmpl->isLexicallyWithinFunctionOrMethod()) {
Richard Smithd3729422012-04-19 00:08:28 +00004058 FunctionDecl *ExceptionSpecTemplate = Tmpl;
Richard Smith8acb4282014-07-31 21:57:55 +00004059 if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
4060 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
Richard Smith185be182013-04-10 05:48:59 +00004061 ExceptionSpecificationType NewEST = EST_Uninstantiated;
Richard Smith8acb4282014-07-31 21:57:55 +00004062 if (EPI.ExceptionSpec.Type == EST_Unevaluated)
Richard Smith185be182013-04-10 05:48:59 +00004063 NewEST = EST_Unevaluated;
Richard Smithd3729422012-04-19 00:08:28 +00004064
Richard Smithf623c962012-04-17 00:58:00 +00004065 // Mark the function has having an uninstantiated exception specification.
4066 const FunctionProtoType *NewProto
4067 = New->getType()->getAs<FunctionProtoType>();
4068 assert(NewProto && "Template instantiation without function prototype?");
4069 EPI = NewProto->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00004070 EPI.ExceptionSpec.Type = NewEST;
4071 EPI.ExceptionSpec.SourceDecl = New;
4072 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
Reid Kleckner896b32f2013-06-10 20:51:09 +00004073 New->setType(SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00004074 NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
Richard Smithf623c962012-04-17 00:58:00 +00004075 } else {
Faisal Vali40fd4ce2017-05-09 04:17:15 +00004076 Sema::ContextRAII SwitchContext(SemaRef, New);
Richard Smith2e321552014-11-12 02:00:47 +00004077 SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +00004078 }
Douglas Gregor049bdca2009-12-08 17:45:32 +00004079 }
4080
Rafael Espindolaba195cf2011-07-06 15:46:09 +00004081 // Get the definition. Leaves the variable unchanged if undefined.
Richard Smithf623c962012-04-17 00:58:00 +00004082 const FunctionDecl *Definition = Tmpl;
Rafael Espindolaba195cf2011-07-06 15:46:09 +00004083 Tmpl->isDefined(Definition);
4084
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00004085 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
4086 LateAttrs, StartingScope);
Douglas Gregor08329632010-06-15 17:05:35 +00004087
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004088 return false;
4089}
4090
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004091/// Initializes common fields of an instantiated method
Douglas Gregor21342092009-03-24 00:38:23 +00004092/// declaration (New) from the corresponding fields of its template
4093/// (Tmpl).
4094///
4095/// \returns true if there was an error
Mike Stump11289f42009-09-09 15:08:12 +00004096bool
4097TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor21342092009-03-24 00:38:23 +00004098 CXXMethodDecl *Tmpl) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004099 if (InitFunctionInstantiation(New, Tmpl))
4100 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004101
Richard Smith5159bbad2018-09-05 22:30:37 +00004102 if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11)
4103 SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New));
4104
Douglas Gregor21342092009-03-24 00:38:23 +00004105 New->setAccess(Tmpl->getAccess());
Fariborz Jahanian6dfc1972009-12-03 18:44:40 +00004106 if (Tmpl->isVirtualAsWritten())
Douglas Gregor11c024b2010-09-28 20:50:54 +00004107 New->setVirtualAsWritten(true);
Douglas Gregor21342092009-03-24 00:38:23 +00004108
Douglas Gregor21342092009-03-24 00:38:23 +00004109 // FIXME: New needs a pointer to Tmpl
4110 return false;
4111}
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00004112
Richard Smith50e291e2018-01-02 23:52:42 +00004113/// Instantiate (or find existing instantiation of) a function template with a
4114/// given set of template arguments.
4115///
4116/// Usually this should not be used, and template argument deduction should be
4117/// used in its place.
4118FunctionDecl *
4119Sema::InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
4120 const TemplateArgumentList *Args,
4121 SourceLocation Loc) {
4122 FunctionDecl *FD = FTD->getTemplatedDecl();
4123
4124 sema::TemplateDeductionInfo Info(Loc);
4125 InstantiatingTemplate Inst(
4126 *this, Loc, FTD, Args->asArray(),
4127 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
4128 if (Inst.isInvalid())
4129 return nullptr;
4130
4131 ContextRAII SavedContext(*this, FD);
4132 MultiLevelTemplateArgumentList MArgs(*Args);
4133
4134 return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs));
4135}
4136
Reid Kleckner61195e12017-01-05 01:08:22 +00004137/// In the MS ABI, we need to instantiate default arguments of dllexported
4138/// default constructors along with the constructor definition. This allows IR
4139/// gen to emit a constructor closure which calls the default constructor with
4140/// its default arguments.
4141static void InstantiateDefaultCtorDefaultArgs(Sema &S,
4142 CXXConstructorDecl *Ctor) {
4143 assert(S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4144 Ctor->isDefaultConstructor());
4145 unsigned NumParams = Ctor->getNumParams();
4146 if (NumParams == 0)
4147 return;
4148 DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>();
4149 if (!Attr)
4150 return;
4151 for (unsigned I = 0; I != NumParams; ++I) {
4152 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), Ctor,
4153 Ctor->getParamDecl(I));
4154 S.DiscardCleanupsInEvaluationContext();
4155 }
4156}
4157
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004158/// Instantiate the definition of the given function from its
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00004159/// template.
4160///
Douglas Gregordda7ced2009-06-30 17:20:14 +00004161/// \param PointOfInstantiation the point at which the instantiation was
4162/// required. Note that this is not precisely a "point of instantiation"
4163/// for the function, but it's close.
4164///
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00004165/// \param Function the already-instantiated declaration of a
Douglas Gregordda7ced2009-06-30 17:20:14 +00004166/// function template specialization or member function of a class template
4167/// specialization.
4168///
4169/// \param Recursive if true, recursively instantiates any functions that
4170/// are required by this instantiation.
Douglas Gregora8b89d22009-10-15 14:05:49 +00004171///
4172/// \param DefinitionRequired if true, then we are performing an explicit
4173/// instantiation where the body of the function is required. Complain if
4174/// there is no such body.
Douglas Gregor85673582009-05-18 17:01:57 +00004175void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregordda7ced2009-06-30 17:20:14 +00004176 FunctionDecl *Function,
Douglas Gregora8b89d22009-10-15 14:05:49 +00004177 bool Recursive,
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00004178 bool DefinitionRequired,
4179 bool AtEndOfTU) {
Richard Smithcb189572017-10-28 01:15:00 +00004180 if (Function->isInvalidDecl() || Function->isDefined() ||
4181 isa<CXXDeductionGuideDecl>(Function))
Douglas Gregorb4850462009-05-14 23:26:13 +00004182 return;
4183
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004184 // Never instantiate an explicit specialization except if it is a class scope
4185 // explicit specialization.
Richard Smithf19a8b02019-05-02 00:49:14 +00004186 TemplateSpecializationKind TSK =
4187 Function->getTemplateSpecializationKindForInstantiation();
4188 if (TSK == TSK_ExplicitSpecialization)
Douglas Gregor86d142a2009-10-08 07:24:58 +00004189 return;
Douglas Gregor69f6a362010-05-17 17:34:56 +00004190
Douglas Gregor24c332b2009-05-14 21:06:31 +00004191 // Find the function body that we'll be substituting.
Douglas Gregorafca3b42009-10-27 20:53:28 +00004192 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Alexis Hunt23f6b832011-05-27 20:00:14 +00004193 assert(PatternDecl && "instantiating a non-template");
4194
Richard Smith6f4e2e02016-08-23 19:41:39 +00004195 const FunctionDecl *PatternDef = PatternDecl->getDefinition();
Richard Smith3f6865a82016-08-23 21:12:54 +00004196 Stmt *Pattern = nullptr;
4197 if (PatternDef) {
4198 Pattern = PatternDef->getBody(PatternDef);
Richard Smith6f4e2e02016-08-23 19:41:39 +00004199 PatternDecl = PatternDef;
Richard Smith6c7161162017-08-12 01:46:03 +00004200 if (PatternDef->willHaveBody())
4201 PatternDef = nullptr;
Richard Smith3f6865a82016-08-23 21:12:54 +00004202 }
Douglas Gregor24c332b2009-05-14 21:06:31 +00004203
Vassil Vassilevb21ee082016-08-18 22:01:25 +00004204 // FIXME: We need to track the instantiation stack in order to know which
4205 // definitions should be visible within this instantiation.
4206 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function,
4207 Function->getInstantiatedFromMemberFunction(),
Richard Smith6f4e2e02016-08-23 19:41:39 +00004208 PatternDecl, PatternDef, TSK,
4209 /*Complain*/DefinitionRequired)) {
4210 if (DefinitionRequired)
4211 Function->setInvalidDecl();
4212 else if (TSK == TSK_ExplicitInstantiationDefinition) {
4213 // Try again at the end of the translation unit (at which point a
4214 // definition will be required).
4215 assert(!Recursive);
Sunil Srivastava15ed2922017-06-20 22:08:44 +00004216 Function->setInstantiationIsPending(true);
Richard Smith6f4e2e02016-08-23 19:41:39 +00004217 PendingInstantiations.push_back(
4218 std::make_pair(Function, PointOfInstantiation));
4219 } else if (TSK == TSK_ImplicitInstantiation) {
Nick Lewycky2adab1b2018-01-02 19:10:12 +00004220 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004221 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
Richard Smith6f4e2e02016-08-23 19:41:39 +00004222 Diag(PointOfInstantiation, diag::warn_func_template_missing)
4223 << Function;
4224 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
4225 if (getLangOpts().CPlusPlus11)
4226 Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
4227 << Function;
4228 }
4229 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +00004230
Richard Smith6f4e2e02016-08-23 19:41:39 +00004231 return;
4232 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +00004233
Francois Pichet1c229c02011-04-22 22:18:13 +00004234 // Postpone late parsed template instantiations.
Alexis Hunt23f6b832011-05-27 20:00:14 +00004235 if (PatternDecl->isLateTemplateParsed() &&
Nick Lewycky610128e2011-05-12 03:51:24 +00004236 !LateTemplateParser) {
Sunil Srivastava15ed2922017-06-20 22:08:44 +00004237 Function->setInstantiationIsPending(true);
Reid Kleckner24bd88c2018-03-26 18:22:47 +00004238 LateParsedInstantiations.push_back(
4239 std::make_pair(Function, PointOfInstantiation));
Francois Pichet1c229c02011-04-22 22:18:13 +00004240 return;
4241 }
4242
Anton Afanasyevd880de22019-03-30 08:42:48 +00004243 llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() {
Lubos Lunakab8cde42019-05-12 10:39:21 +00004244 std::string Name;
4245 llvm::raw_string_ostream OS(Name);
4246 Function->getNameForDiagnostic(OS, getPrintingPolicy(),
4247 /*Qualified=*/true);
4248 return Name;
Anton Afanasyevd880de22019-03-30 08:42:48 +00004249 });
4250
Nico Weberae4bb8c2014-08-15 23:21:41 +00004251 // If we're performing recursive template instantiation, create our own
4252 // queue of pending implicit instantiations that we will instantiate later,
4253 // while we're still within our own instantiation context.
4254 // This has to happen before LateTemplateParser below is called, so that
4255 // it marks vtables used in late parsed templates as used.
Richard Smith4f3e3812017-05-20 01:36:41 +00004256 GlobalEagerInstantiationScope GlobalInstantiations(*this,
4257 /*Enabled=*/Recursive);
4258 LocalEagerInstantiationScope LocalInstantiations(*this);
Nico Weberae4bb8c2014-08-15 23:21:41 +00004259
David Majnemerf0a84f22013-08-16 08:29:13 +00004260 // Call the LateTemplateParser callback if there is a need to late parse
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004261 // a templated function definition.
Alexis Hunt23f6b832011-05-27 20:00:14 +00004262 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
Francois Pichet1c229c02011-04-22 22:18:13 +00004263 LateTemplateParser) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00004264 // FIXME: Optimize to allow individual templates to be deserialized.
4265 if (PatternDecl->isFromASTFile())
4266 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
4267
Justin Lebar28f09c52016-10-10 16:26:08 +00004268 auto LPTIter = LateParsedTemplateMap.find(PatternDecl);
4269 assert(LPTIter != LateParsedTemplateMap.end() &&
4270 "missing LateParsedTemplate");
4271 LateTemplateParser(OpaqueParser, *LPTIter->second);
Francois Pichet1c229c02011-04-22 22:18:13 +00004272 Pattern = PatternDecl->getBody(PatternDecl);
4273 }
4274
Richard Smith6f4e2e02016-08-23 19:41:39 +00004275 // Note, we should never try to instantiate a deleted function template.
Ilya Biryukova27eca22017-12-20 14:32:38 +00004276 assert((Pattern || PatternDecl->isDefaulted() ||
4277 PatternDecl->hasSkippedBody()) &&
Richard Smith6f4e2e02016-08-23 19:41:39 +00004278 "unexpected kind of function template definition");
Douglas Gregor24c332b2009-05-14 21:06:31 +00004279
Richard Smith2a7d4812013-05-04 07:00:32 +00004280 // C++1y [temp.explicit]p10:
4281 // Except for inline functions, declarations with types deduced from their
4282 // initializer or return value, and class template specializations, other
4283 // explicit instantiation declarations have the effect of suppressing the
4284 // implicit instantiation of the entity to which they refer.
Vassil Vassilevb21ee082016-08-18 22:01:25 +00004285 if (TSK == TSK_ExplicitInstantiationDeclaration &&
Richard Smith2a7d4812013-05-04 07:00:32 +00004286 !PatternDecl->isInlined() &&
Alp Toker314cc812014-01-25 16:55:45 +00004287 !PatternDecl->getReturnType()->getContainedAutoType())
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00004288 return;
Mike Stump11289f42009-09-09 15:08:12 +00004289
Richard Smith195d8ef2014-05-29 03:15:31 +00004290 if (PatternDecl->isInlined()) {
4291 // Function, and all later redeclarations of it (from imported modules,
4292 // for instance), are now implicitly inline.
4293 for (auto *D = Function->getMostRecentDecl(); /**/;
4294 D = D->getPreviousDecl()) {
4295 D->setImplicitlyInline();
4296 if (D == Function)
4297 break;
4298 }
4299 }
Richard Smithf3814ad2013-01-25 00:08:28 +00004300
Douglas Gregor85673582009-05-18 17:01:57 +00004301 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
Richard Smith54f18e82016-08-31 02:15:21 +00004302 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004303 return;
Jordan Rose1e879d82018-03-23 00:07:18 +00004304 PrettyDeclStackTraceEntry CrashInfo(Context, Function, SourceLocation(),
Richard Smithe19b95d2016-05-26 20:23:13 +00004305 "instantiating function definition");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004306
Vassil Vassilevb21ee082016-08-18 22:01:25 +00004307 // The instantiation is visible here, even if it was first declared in an
4308 // unimported module.
Richard Smith90dc5252017-06-23 01:04:34 +00004309 Function->setVisibleDespiteOwningModule();
Vassil Vassilevb21ee082016-08-18 22:01:25 +00004310
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00004311 // Copy the inner loc start from the pattern.
4312 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
4313
Faisal Valid143a0c2017-04-01 21:30:49 +00004314 EnterExpressionEvaluationContext EvalContext(
4315 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
Douglas Gregor67da0d92009-05-15 17:59:04 +00004316
Douglas Gregorb4850462009-05-14 23:26:13 +00004317 // Introduce a new scope where local variable instantiations will be
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004318 // recorded, unless we're actually a member function within a local
4319 // class, in which case we need to merge our results with the parent
4320 // scope (of the enclosing function).
4321 bool MergeWithParentScope = false;
4322 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
4323 MergeWithParentScope = Rec->isLocalClass();
4324
4325 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump11289f42009-09-09 15:08:12 +00004326
Richard Smithbd305122012-12-11 01:14:52 +00004327 if (PatternDecl->isDefaulted())
Alexis Hunt61ae8d32011-05-23 23:14:04 +00004328 SetDeclDefaulted(Function, PatternDecl->getLocation());
Richard Smithbd305122012-12-11 01:14:52 +00004329 else {
Richard Smithcc928662014-10-17 20:37:29 +00004330 MultiLevelTemplateArgumentList TemplateArgs =
4331 getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl);
4332
4333 // Substitute into the qualifier; we can get a substitution failure here
4334 // through evil use of alias templates.
4335 // FIXME: Is CurContext correct for this? Should we go to the (instantiation
4336 // of the) lexical context of the pattern?
4337 SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
4338
Craig Topperc3ec1492014-05-26 06:22:03 +00004339 ActOnStartOfFunctionDef(nullptr, Function);
Richard Smithbd305122012-12-11 01:14:52 +00004340
4341 // Enter the scope of this instantiation. We don't use
4342 // PushDeclContext because we don't have a scope.
4343 Sema::ContextRAII savedContext(*this, Function);
4344
Richard Smith2e321552014-11-12 02:00:47 +00004345 if (addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
4346 TemplateArgs))
4347 return;
Richard Smithbd305122012-12-11 01:14:52 +00004348
Ilya Biryukov0ee4a082018-03-14 13:18:30 +00004349 StmtResult Body;
Ilya Biryukova27eca22017-12-20 14:32:38 +00004350 if (PatternDecl->hasSkippedBody()) {
4351 ActOnSkippedFunctionBody(Function);
Ilya Biryukov0ee4a082018-03-14 13:18:30 +00004352 Body = nullptr;
Ilya Biryukova27eca22017-12-20 14:32:38 +00004353 } else {
Ilya Biryukov95f0d322017-12-28 13:05:46 +00004354 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) {
4355 // If this is a constructor, instantiate the member initializers.
4356 InstantiateMemInitializers(Ctor, cast<CXXConstructorDecl>(PatternDecl),
4357 TemplateArgs);
4358
4359 // If this is an MS ABI dllexport default constructor, instantiate any
4360 // default arguments.
4361 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4362 Ctor->isDefaultConstructor()) {
4363 InstantiateDefaultCtorDefaultArgs(*this, Ctor);
4364 }
4365 }
4366
Ilya Biryukova27eca22017-12-20 14:32:38 +00004367 // Instantiate the function body.
Ilya Biryukov0ee4a082018-03-14 13:18:30 +00004368 Body = SubstStmt(Pattern, TemplateArgs);
Alexis Hunt61ae8d32011-05-23 23:14:04 +00004369
Ilya Biryukova27eca22017-12-20 14:32:38 +00004370 if (Body.isInvalid())
4371 Function->setInvalidDecl();
Ilya Biryukova27eca22017-12-20 14:32:38 +00004372 }
Ilya Biryukov0ee4a082018-03-14 13:18:30 +00004373 // FIXME: finishing the function body while in an expression evaluation
4374 // context seems wrong. Investigate more.
4375 ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true);
Richard Smithbd305122012-12-11 01:14:52 +00004376
4377 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
4378
Richard Smithd28ac5b2014-03-22 23:33:22 +00004379 if (auto *Listener = getASTMutationListener())
4380 Listener->FunctionDefinitionInstantiated(Function);
Richard Smith0ac1b8f2014-03-22 01:43:32 +00004381
Richard Smithbd305122012-12-11 01:14:52 +00004382 savedContext.pop();
Mike Stump11289f42009-09-09 15:08:12 +00004383 }
4384
Douglas Gregor28ad4b52009-05-26 20:50:29 +00004385 DeclGroupRef DG(Function);
4386 Consumer.HandleTopLevelDecl(DG);
Mike Stump11289f42009-09-09 15:08:12 +00004387
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004388 // This class may have local implicit instantiations that need to be
4389 // instantiation within this scope.
Richard Smith4f3e3812017-05-20 01:36:41 +00004390 LocalInstantiations.perform();
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004391 Scope.Exit();
Richard Smith4f3e3812017-05-20 01:36:41 +00004392 GlobalInstantiations.perform();
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00004393}
4394
Larisse Voufo39a1e502013-08-06 01:03:05 +00004395VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
4396 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
4397 const TemplateArgumentList &TemplateArgList,
4398 const TemplateArgumentListInfo &TemplateArgsInfo,
4399 SmallVectorImpl<TemplateArgument> &Converted,
4400 SourceLocation PointOfInstantiation, void *InsertPos,
4401 LateInstantiatedAttrVec *LateAttrs,
4402 LocalInstantiationScope *StartingScope) {
4403 if (FromVar->isInvalidDecl())
Craig Topperc3ec1492014-05-26 06:22:03 +00004404 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004405
4406 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
Alp Tokerd4a72d52013-10-08 08:09:04 +00004407 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00004408 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004409
4410 MultiLevelTemplateArgumentList TemplateArgLists;
4411 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
4412
Richard Smith8809a0c2013-09-27 20:14:12 +00004413 // Instantiate the first declaration of the variable template: for a partial
4414 // specialization of a static data member template, the first declaration may
4415 // or may not be the declaration in the class; if it's in the class, we want
4416 // to instantiate a member in the class (a declaration), and if it's outside,
4417 // we want to instantiate a definition.
Richard Smithbeef3452014-01-16 23:39:20 +00004418 //
4419 // If we're instantiating an explicitly-specialized member template or member
4420 // partial specialization, don't do this. The member specialization completely
4421 // replaces the original declaration in this case.
4422 bool IsMemberSpec = false;
4423 if (VarTemplatePartialSpecializationDecl *PartialSpec =
4424 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar))
4425 IsMemberSpec = PartialSpec->isMemberSpecialization();
4426 else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate())
4427 IsMemberSpec = FromTemplate->isMemberSpecialization();
4428 if (!IsMemberSpec)
4429 FromVar = FromVar->getFirstDecl();
Richard Smith8809a0c2013-09-27 20:14:12 +00004430
Manuel Klimek5843add2013-09-30 13:29:01 +00004431 MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
4432 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
4433 MultiLevelList);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004434
4435 // TODO: Set LateAttrs and StartingScope ...
4436
4437 return cast_or_null<VarTemplateSpecializationDecl>(
4438 Instantiator.VisitVarTemplateSpecializationDecl(
4439 VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
4440}
4441
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004442/// Instantiates a variable template specialization by completing it
Larisse Voufo39a1e502013-08-06 01:03:05 +00004443/// with appropriate type information and initializer.
4444VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
4445 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
4446 const MultiLevelTemplateArgumentList &TemplateArgs) {
Richard Smith435e6472017-12-02 02:48:42 +00004447 assert(PatternDecl->isThisDeclarationADefinition() &&
4448 "don't have a definition to instantiate from");
Larisse Voufo39a1e502013-08-06 01:03:05 +00004449
4450 // Do substitution on the type of the declaration
4451 TypeSourceInfo *DI =
Richard Smith8809a0c2013-09-27 20:14:12 +00004452 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00004453 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
4454 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00004455 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004456
4457 // Update the type of this variable template specialization.
4458 VarSpec->setType(DI->getType());
4459
Richard Smith435e6472017-12-02 02:48:42 +00004460 // Convert the declaration into a definition now.
4461 VarSpec->setCompleteDefinition();
4462
Larisse Voufo39a1e502013-08-06 01:03:05 +00004463 // Instantiate the initializer.
4464 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
4465
4466 return VarSpec;
4467}
4468
4469/// BuildVariableInstantiation - Used after a new variable has been created.
4470/// Sets basic variable data and decides whether to postpone the
4471/// variable instantiation.
4472void Sema::BuildVariableInstantiation(
4473 VarDecl *NewVar, VarDecl *OldVar,
4474 const MultiLevelTemplateArgumentList &TemplateArgs,
Richard Smith541b38b2013-09-20 01:15:31 +00004475 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
4476 LocalInstantiationScope *StartingScope,
Richard Smitha6b41d72019-05-03 23:51:38 +00004477 bool InstantiatingVarTemplate,
4478 VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) {
4479 // Instantiating a partial specialization to produce a partial
4480 // specialization.
4481 bool InstantiatingVarTemplatePartialSpec =
4482 isa<VarTemplatePartialSpecializationDecl>(OldVar) &&
4483 isa<VarTemplatePartialSpecializationDecl>(NewVar);
4484 // Instantiating from a variable template (or partial specialization) to
4485 // produce a variable template specialization.
4486 bool InstantiatingSpecFromTemplate =
4487 isa<VarTemplateSpecializationDecl>(NewVar) &&
4488 (OldVar->getDescribedVarTemplate() ||
4489 isa<VarTemplatePartialSpecializationDecl>(OldVar));
Larisse Voufo39a1e502013-08-06 01:03:05 +00004490
Richard Smith541b38b2013-09-20 01:15:31 +00004491 // If we are instantiating a local extern declaration, the
4492 // instantiation belongs lexically to the containing function.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004493 // If we are instantiating a static data member defined
4494 // out-of-line, the instantiation will have the same lexical
4495 // context (which will be a namespace scope) as the template.
Richard Smith541b38b2013-09-20 01:15:31 +00004496 if (OldVar->isLocalExternDecl()) {
4497 NewVar->setLocalExternDecl();
4498 NewVar->setLexicalDeclContext(Owner);
4499 } else if (OldVar->isOutOfLine())
Larisse Voufo39a1e502013-08-06 01:03:05 +00004500 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
4501 NewVar->setTSCSpec(OldVar->getTSCSpec());
4502 NewVar->setInitStyle(OldVar->getInitStyle());
4503 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
George Karpenkovec38cf72018-03-29 00:56:24 +00004504 NewVar->setObjCForDecl(OldVar->isObjCForDecl());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004505 NewVar->setConstexpr(OldVar->isConstexpr());
Richard Smithbb13c9a2013-09-28 04:02:39 +00004506 NewVar->setInitCapture(OldVar->isInitCapture());
Richard Smith1c34fb72013-08-13 18:18:50 +00004507 NewVar->setPreviousDeclInSameBlockScope(
4508 OldVar->isPreviousDeclInSameBlockScope());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004509 NewVar->setAccess(OldVar->getAccess());
4510
Richard Smith0b551192013-09-23 23:12:22 +00004511 if (!OldVar->isStaticDataMember()) {
Rafael Espindolae4865d22013-10-23 16:46:34 +00004512 if (OldVar->isUsed(false))
4513 NewVar->setIsUsed();
Larisse Voufo39a1e502013-08-06 01:03:05 +00004514 NewVar->setReferenced(OldVar->isReferenced());
4515 }
4516
4517 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
4518
Richard Smith541b38b2013-09-20 01:15:31 +00004519 LookupResult Previous(
4520 *this, NewVar->getDeclName(), NewVar->getLocation(),
4521 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
4522 : Sema::LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00004523 NewVar->isLocalExternDecl() ? Sema::ForExternalRedeclaration
4524 : forRedeclarationInCurContext());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004525
Argyrios Kyrtzidis91486222013-11-27 08:34:14 +00004526 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
4527 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
4528 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
Richard Smith1c34fb72013-08-13 18:18:50 +00004529 // We have a previous declaration. Use that one, so we merge with the
4530 // right type.
4531 if (NamedDecl *NewPrev = FindInstantiatedDecl(
4532 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
4533 Previous.addDecl(NewPrev);
4534 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
Richard Smitha6b41d72019-05-03 23:51:38 +00004535 OldVar->hasLinkage()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004536 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
Richard Smitha6b41d72019-05-03 23:51:38 +00004537 } else if (PrevDeclForVarTemplateSpecialization) {
4538 Previous.addDecl(PrevDeclForVarTemplateSpecialization);
4539 }
Larisse Voufo72caf2b2013-08-22 00:59:14 +00004540 CheckVariableDeclaration(NewVar, Previous);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004541
Richard Smith541b38b2013-09-20 01:15:31 +00004542 if (!InstantiatingVarTemplate) {
4543 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
4544 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
Larisse Voufo39a1e502013-08-06 01:03:05 +00004545 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
Richard Smith541b38b2013-09-20 01:15:31 +00004546 }
4547
4548 if (!OldVar->isOutOfLine()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004549 if (NewVar->getDeclContext()->isFunctionOrMethod())
4550 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
4551 }
4552
4553 // Link instantiations of static data members back to the template from
4554 // which they were instantiated.
Richard Smitha6b41d72019-05-03 23:51:38 +00004555 //
4556 // Don't do this when instantiating a template (we link the template itself
4557 // back in that case) nor when instantiating a static data member template
4558 // (that's not a member specialization).
4559 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate &&
4560 !InstantiatingSpecFromTemplate)
Larisse Voufo39a1e502013-08-06 01:03:05 +00004561 NewVar->setInstantiationOfStaticDataMember(OldVar,
4562 TSK_ImplicitInstantiation);
4563
Richard Smitha6b41d72019-05-03 23:51:38 +00004564 // If the pattern is an (in-class) explicit specialization, then the result
4565 // is also an explicit specialization.
4566 if (VarTemplateSpecializationDecl *OldVTSD =
4567 dyn_cast<VarTemplateSpecializationDecl>(OldVar)) {
4568 if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization &&
4569 !isa<VarTemplatePartialSpecializationDecl>(OldVTSD))
4570 cast<VarTemplateSpecializationDecl>(NewVar)->setSpecializationKind(
4571 TSK_ExplicitSpecialization);
4572 }
4573
David Majnemerdbc0c8f2013-12-04 09:01:55 +00004574 // Forward the mangling number from the template to the instantiated decl.
4575 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
David Majnemer2206bf52014-03-05 08:57:59 +00004576 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
David Majnemerdbc0c8f2013-12-04 09:01:55 +00004577
Richard Smitha6b41d72019-05-03 23:51:38 +00004578 // Figure out whether to eagerly instantiate the initializer.
4579 if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) {
4580 // We're producing a template. Don't instantiate the initializer yet.
4581 } else if (NewVar->getType()->isUndeducedType()) {
4582 // We need the type to complete the declaration of the variable.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004583 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
Richard Smitha6b41d72019-05-03 23:51:38 +00004584 } else if (InstantiatingSpecFromTemplate ||
4585 (OldVar->isInline() && OldVar->isThisDeclarationADefinition() &&
4586 !NewVar->isThisDeclarationADefinition())) {
4587 // Delay instantiation of the initializer for variable template
4588 // specializations or inline static data members until a definition of the
4589 // variable is needed.
4590 } else {
4591 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
4592 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004593
4594 // Diagnose unused local variables with dependent types, where the diagnostic
4595 // will have been deferred.
4596 if (!NewVar->isInvalidDecl() &&
Nico Weber72889432014-09-06 01:25:55 +00004597 NewVar->getDeclContext()->isFunctionOrMethod() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004598 OldVar->getType()->isDependentType())
4599 DiagnoseUnusedDecl(NewVar);
4600}
4601
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004602/// Instantiate the initializer of a variable.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004603void Sema::InstantiateVariableInitializer(
4604 VarDecl *Var, VarDecl *OldVar,
4605 const MultiLevelTemplateArgumentList &TemplateArgs) {
Richard Smith891fc7f2017-12-05 01:31:47 +00004606 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
4607 L->VariableDefinitionInstantiated(Var);
4608
Richard Smith62f19e72016-06-25 00:15:56 +00004609 // We propagate the 'inline' flag with the initializer, because it
4610 // would otherwise imply that the variable is a definition for a
4611 // non-static data member.
4612 if (OldVar->isInlineSpecified())
4613 Var->setInlineSpecified();
4614 else if (OldVar->isInline())
4615 Var->setImplicitlyInline();
Larisse Voufo39a1e502013-08-06 01:03:05 +00004616
Larisse Voufo39a1e502013-08-06 01:03:05 +00004617 if (OldVar->getInit()) {
Richard Smithc95d2c52017-09-22 04:25:05 +00004618 EnterExpressionEvaluationContext Evaluated(
4619 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, Var);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004620
4621 // Instantiate the initializer.
Akira Hatanakab87faff2016-04-28 23:50:12 +00004622 ExprResult Init;
4623
4624 {
4625 ContextRAII SwitchContext(*this, Var->getDeclContext());
4626 Init = SubstInitializer(OldVar->getInit(), TemplateArgs,
4627 OldVar->getInitStyle() == VarDecl::CallInit);
4628 }
4629
Larisse Voufo39a1e502013-08-06 01:03:05 +00004630 if (!Init.isInvalid()) {
Hans Wennborg91ebe6e2014-06-10 00:55:51 +00004631 Expr *InitExpr = Init.get();
4632
Richard Smith95b83e92014-07-10 20:53:43 +00004633 if (Var->hasAttr<DLLImportAttr>() &&
4634 (!InitExpr ||
4635 !InitExpr->isConstantInitializer(getASTContext(), false))) {
Hans Wennborg91ebe6e2014-06-10 00:55:51 +00004636 // Do not dynamically initialize dllimport variables.
Hans Wennborg91ebe6e2014-06-10 00:55:51 +00004637 } else if (InitExpr) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004638 bool DirectInit = OldVar->isDirectInit();
Richard Smith3beb7c62017-01-12 02:27:38 +00004639 AddInitializerToDecl(Var, InitExpr, DirectInit);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004640 } else
Richard Smith3beb7c62017-01-12 02:27:38 +00004641 ActOnUninitializedDecl(Var);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004642 } else {
4643 // FIXME: Not too happy about invalidating the declaration
4644 // because of a bogus initializer.
4645 Var->setInvalidDecl();
4646 }
Richard Smith54f18e82016-08-31 02:15:21 +00004647 } else {
George Burgess IV18b28a82018-03-20 03:27:44 +00004648 // `inline` variables are a definition and declaration all in one; we won't
4649 // pick up an initializer from anywhere else.
4650 if (Var->isStaticDataMember() && !Var->isInline()) {
Richard Smith54f18e82016-08-31 02:15:21 +00004651 if (!Var->isOutOfLine())
4652 return;
4653
4654 // If the declaration inside the class had an initializer, don't add
4655 // another one to the out-of-line definition.
4656 if (OldVar->getFirstDecl()->hasInit())
4657 return;
4658 }
4659
4660 // We'll add an initializer to a for-range declaration later.
George Karpenkovec38cf72018-03-29 00:56:24 +00004661 if (Var->isCXXForRangeDecl() || Var->isObjCForDecl())
Richard Smith54f18e82016-08-31 02:15:21 +00004662 return;
4663
Richard Smith3beb7c62017-01-12 02:27:38 +00004664 ActOnUninitializedDecl(Var);
Richard Smith54f18e82016-08-31 02:15:21 +00004665 }
Artem Beleviche9fa53a2018-06-06 22:37:25 +00004666
4667 if (getLangOpts().CUDA)
4668 checkAllowedCUDAInitializer(Var);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004669}
4670
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004671/// Instantiate the definition of the given variable from its
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00004672/// template.
4673///
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004674/// \param PointOfInstantiation the point at which the instantiation was
4675/// required. Note that this is not precisely a "point of instantiation"
Richard Smith891fc7f2017-12-05 01:31:47 +00004676/// for the variable, but it's close.
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004677///
Richard Smith891fc7f2017-12-05 01:31:47 +00004678/// \param Var the already-instantiated declaration of a templated variable.
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004679///
4680/// \param Recursive if true, recursively instantiates any functions that
4681/// are required by this instantiation.
Douglas Gregora8b89d22009-10-15 14:05:49 +00004682///
4683/// \param DefinitionRequired if true, then we are performing an explicit
Richard Smith891fc7f2017-12-05 01:31:47 +00004684/// instantiation where a definition of the variable is required. Complain
4685/// if there is no such definition.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004686void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
4687 VarDecl *Var, bool Recursive,
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00004688 bool DefinitionRequired, bool AtEndOfTU) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004689 if (Var->isInvalidDecl())
4690 return;
Mike Stump11289f42009-09-09 15:08:12 +00004691
Richard Smitha6b41d72019-05-03 23:51:38 +00004692 // Never instantiate an explicitly-specialized entity.
4693 TemplateSpecializationKind TSK =
4694 Var->getTemplateSpecializationKindForInstantiation();
4695 if (TSK == TSK_ExplicitSpecialization)
4696 return;
4697
4698 // Find the pattern and the arguments to substitute into it.
4699 VarDecl *PatternDecl = Var->getTemplateInstantiationPattern();
4700 assert(PatternDecl && "no pattern for templated variable");
Richard Smith8809a0c2013-09-27 20:14:12 +00004701 MultiLevelTemplateArgumentList TemplateArgs =
4702 getTemplateInstantiationArgs(Var);
Mike Stump11289f42009-09-09 15:08:12 +00004703
Richard Smitha6b41d72019-05-03 23:51:38 +00004704 VarTemplateSpecializationDecl *VarSpec =
4705 dyn_cast<VarTemplateSpecializationDecl>(Var);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004706 if (VarSpec) {
Richard Smith8809a0c2013-09-27 20:14:12 +00004707 // If this is a variable template specialization, make sure that it is
Richard Smitha6b41d72019-05-03 23:51:38 +00004708 // non-dependent.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004709 bool InstantiationDependent = false;
4710 assert(!TemplateSpecializationType::anyDependentTemplateArguments(
4711 VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
4712 "Only instantiate variable template specializations that are "
4713 "not type-dependent");
Larisse Voufo4154f462013-08-06 03:57:41 +00004714 (void)InstantiationDependent;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004715
Richard Smith8809a0c2013-09-27 20:14:12 +00004716 // If this is a static data member template, there might be an
4717 // uninstantiated initializer on the declaration. If so, instantiate
4718 // it now.
Richard Smith891fc7f2017-12-05 01:31:47 +00004719 //
4720 // FIXME: This largely duplicates what we would do below. The difference
4721 // is that along this path we may instantiate an initializer from an
4722 // in-class declaration of the template and instantiate the definition
4723 // from a separate out-of-class definition.
Richard Smith8809a0c2013-09-27 20:14:12 +00004724 if (PatternDecl->isStaticDataMember() &&
Rafael Espindola8db352d2013-10-17 15:37:26 +00004725 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
Richard Smith8809a0c2013-09-27 20:14:12 +00004726 !Var->hasInit()) {
4727 // FIXME: Factor out the duplicated instantiation context setup/tear down
4728 // code here.
4729 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
Richard Smith54f18e82016-08-31 02:15:21 +00004730 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
Richard Smith8809a0c2013-09-27 20:14:12 +00004731 return;
Jordan Rose1e879d82018-03-23 00:07:18 +00004732 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
Richard Smithe19b95d2016-05-26 20:23:13 +00004733 "instantiating variable initializer");
Richard Smith8809a0c2013-09-27 20:14:12 +00004734
Richard Smithedbc6e92016-10-14 21:41:24 +00004735 // The instantiation is visible here, even if it was first declared in an
4736 // unimported module.
Richard Smith90dc5252017-06-23 01:04:34 +00004737 Var->setVisibleDespiteOwningModule();
Richard Smithedbc6e92016-10-14 21:41:24 +00004738
Richard Smith8809a0c2013-09-27 20:14:12 +00004739 // If we're performing recursive template instantiation, create our own
4740 // queue of pending implicit instantiations that we will instantiate
4741 // later, while we're still within our own instantiation context.
Richard Smith4f3e3812017-05-20 01:36:41 +00004742 GlobalEagerInstantiationScope GlobalInstantiations(*this,
4743 /*Enabled=*/Recursive);
Richard Smith8809a0c2013-09-27 20:14:12 +00004744 LocalInstantiationScope Local(*this);
Richard Smith4f3e3812017-05-20 01:36:41 +00004745 LocalEagerInstantiationScope LocalInstantiations(*this);
Richard Smith8809a0c2013-09-27 20:14:12 +00004746
4747 // Enter the scope of this instantiation. We don't use
4748 // PushDeclContext because we don't have a scope.
4749 ContextRAII PreviousContext(*this, Var->getDeclContext());
4750 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
4751 PreviousContext.pop();
4752
Richard Smith8809a0c2013-09-27 20:14:12 +00004753 // This variable may have local implicit instantiations that need to be
4754 // instantiated within this scope.
Richard Smith4f3e3812017-05-20 01:36:41 +00004755 LocalInstantiations.perform();
Richard Smith8809a0c2013-09-27 20:14:12 +00004756 Local.Exit();
Richard Smith4f3e3812017-05-20 01:36:41 +00004757 GlobalInstantiations.perform();
Richard Smith8809a0c2013-09-27 20:14:12 +00004758 }
Richard Smith8809a0c2013-09-27 20:14:12 +00004759 } else {
Richard Smitha6b41d72019-05-03 23:51:38 +00004760 assert(Var->isStaticDataMember() && PatternDecl->isStaticDataMember() &&
4761 "not a static data member?");
Larisse Voufo39a1e502013-08-06 01:03:05 +00004762 }
4763
Richard Smitha6b41d72019-05-03 23:51:38 +00004764 VarDecl *Def = PatternDecl->getDefinition(getASTContext());
Richard Smith6739a102016-05-05 00:56:12 +00004765
Richard Smith8809a0c2013-09-27 20:14:12 +00004766 // If we don't have a definition of the variable template, we won't perform
4767 // any instantiation. Rather, we rely on the user to instantiate this
4768 // definition (or provide a specialization for it) in another translation
4769 // unit.
Richard Smithedbc6e92016-10-14 21:41:24 +00004770 if (!Def && !DefinitionRequired) {
4771 if (TSK == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth54080172010-08-25 08:44:16 +00004772 PendingInstantiations.push_back(
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004773 std::make_pair(Var, PointOfInstantiation));
Richard Smithedbc6e92016-10-14 21:41:24 +00004774 } else if (TSK == TSK_ImplicitInstantiation) {
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00004775 // Warn about missing definition at the end of translation unit.
Nick Lewycky2adab1b2018-01-02 19:10:12 +00004776 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004777 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00004778 Diag(PointOfInstantiation, diag::warn_var_template_missing)
4779 << Var;
4780 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
4781 if (getLangOpts().CPlusPlus11)
4782 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
4783 }
Richard Smithedbc6e92016-10-14 21:41:24 +00004784 return;
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004785 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004786 }
4787
Richard Smithedbc6e92016-10-14 21:41:24 +00004788 // FIXME: We need to track the instantiation stack in order to know which
4789 // definitions should be visible within this instantiation.
4790 // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
4791 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var,
4792 /*InstantiatedFromMember*/false,
4793 PatternDecl, Def, TSK,
4794 /*Complain*/DefinitionRequired))
4795 return;
4796
Larisse Voufo39a1e502013-08-06 01:03:05 +00004797 // C++11 [temp.explicit]p10:
Richard Smith4309b662017-10-18 22:45:01 +00004798 // Except for inline functions, const variables of literal types, variables
4799 // of reference types, [...] explicit instantiation declarations
Larisse Voufo39a1e502013-08-06 01:03:05 +00004800 // have the effect of suppressing the implicit instantiation of the entity
4801 // to which they refer.
Richard Smith715f7a12019-06-11 17:50:32 +00004802 //
4803 // FIXME: That's not exactly the same as "might be usable in constant
4804 // expressions", which only allows constexpr variables and const integral
4805 // types, not arbitrary const literal types.
Richard Smith4309b662017-10-18 22:45:01 +00004806 if (TSK == TSK_ExplicitInstantiationDeclaration &&
Richard Smith715f7a12019-06-11 17:50:32 +00004807 !Var->mightBeUsableInConstantExpressions(getASTContext()))
Douglas Gregor86d142a2009-10-08 07:24:58 +00004808 return;
Mike Stump11289f42009-09-09 15:08:12 +00004809
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00004810 // Make sure to pass the instantiated variable to the consumer at the end.
4811 struct PassToConsumerRAII {
4812 ASTConsumer &Consumer;
4813 VarDecl *Var;
4814
4815 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
4816 : Consumer(Consumer), Var(Var) { }
4817
4818 ~PassToConsumerRAII() {
Richard Smith8809a0c2013-09-27 20:14:12 +00004819 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00004820 }
4821 } PassToConsumerRAII(Consumer, Var);
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00004822
Reid Klecknere07140e2015-04-15 01:08:06 +00004823 // If we already have a definition, we're done.
4824 if (VarDecl *Def = Var->getDefinition()) {
4825 // We may be explicitly instantiating something we've already implicitly
4826 // instantiated.
4827 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
4828 PointOfInstantiation);
Richard Smith8809a0c2013-09-27 20:14:12 +00004829 return;
Reid Klecknere07140e2015-04-15 01:08:06 +00004830 }
Douglas Gregor57d4f972011-06-03 03:35:07 +00004831
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004832 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
Richard Smith54f18e82016-08-31 02:15:21 +00004833 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004834 return;
Jordan Rose1e879d82018-03-23 00:07:18 +00004835 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
Richard Smithe19b95d2016-05-26 20:23:13 +00004836 "instantiating variable definition");
Mike Stump11289f42009-09-09 15:08:12 +00004837
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004838 // If we're performing recursive template instantiation, create our own
4839 // queue of pending implicit instantiations that we will instantiate later,
4840 // while we're still within our own instantiation context.
Richard Smith4f3e3812017-05-20 01:36:41 +00004841 GlobalEagerInstantiationScope GlobalInstantiations(*this,
4842 /*Enabled=*/Recursive);
Mike Stump11289f42009-09-09 15:08:12 +00004843
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004844 // Enter the scope of this instantiation. We don't use
4845 // PushDeclContext because we don't have a scope.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004846 ContextRAII PreviousContext(*this, Var->getDeclContext());
Douglas Gregora86bc002012-02-16 21:36:18 +00004847 LocalInstantiationScope Local(*this);
John McCall2957e3e2011-02-14 20:37:25 +00004848
Richard Smith4f3e3812017-05-20 01:36:41 +00004849 LocalEagerInstantiationScope LocalInstantiations(*this);
4850
Larisse Voufo39a1e502013-08-06 01:03:05 +00004851 VarDecl *OldVar = Var;
Richard Smith62f19e72016-06-25 00:15:56 +00004852 if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
4853 // We're instantiating an inline static data member whose definition was
4854 // provided inside the class.
Richard Smith62f19e72016-06-25 00:15:56 +00004855 InstantiateVariableInitializer(Var, Def, TemplateArgs);
4856 } else if (!VarSpec) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004857 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Richard Smith8809a0c2013-09-27 20:14:12 +00004858 TemplateArgs));
Richard Smith62f19e72016-06-25 00:15:56 +00004859 } else if (Var->isStaticDataMember() &&
4860 Var->getLexicalDeclContext()->isRecord()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00004861 // We need to instantiate the definition of a static data member template,
4862 // and all we have is the in-class declaration of it. Instantiate a separate
4863 // declaration of the definition.
4864 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
4865 TemplateArgs);
4866 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
Craig Topperc3ec1492014-05-26 06:22:03 +00004867 VarSpec->getSpecializedTemplate(), Def, nullptr,
Richard Smith8809a0c2013-09-27 20:14:12 +00004868 VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
4869 if (Var) {
4870 llvm::PointerUnion<VarTemplateDecl *,
4871 VarTemplatePartialSpecializationDecl *> PatternPtr =
4872 VarSpec->getSpecializedTemplateOrPartial();
4873 if (VarTemplatePartialSpecializationDecl *Partial =
4874 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
4875 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
4876 Partial, &VarSpec->getTemplateInstantiationArgs());
4877
4878 // Merge the definition with the declaration.
4879 LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
Richard Smithbecb92d2017-10-10 22:33:17 +00004880 LookupOrdinaryName, forRedeclarationInCurContext());
Richard Smith8809a0c2013-09-27 20:14:12 +00004881 R.addDecl(OldVar);
4882 MergeVarDecl(Var, R);
4883
4884 // Attach the initializer.
4885 InstantiateVariableInitializer(Var, Def, TemplateArgs);
4886 }
4887 } else
4888 // Complete the existing variable's definition with an appropriately
4889 // substituted type and initializer.
4890 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004891
4892 PreviousContext.pop();
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004893
4894 if (Var) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004895 PassToConsumerRAII.Var = Var;
Richard Smith8809a0c2013-09-27 20:14:12 +00004896 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
4897 OldVar->getPointOfInstantiation());
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004898 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004899
4900 // This variable may have local implicit instantiations that need to be
4901 // instantiated within this scope.
Richard Smith4f3e3812017-05-20 01:36:41 +00004902 LocalInstantiations.perform();
Douglas Gregora86bc002012-02-16 21:36:18 +00004903 Local.Exit();
Richard Smith4f3e3812017-05-20 01:36:41 +00004904 GlobalInstantiations.perform();
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00004905}
Douglas Gregor51783312009-05-27 05:35:12 +00004906
Anders Carlsson70553942009-08-29 05:16:22 +00004907void
4908Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
4909 const CXXConstructorDecl *Tmpl,
4910 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00004911
Richard Trieu9becef62011-09-09 03:18:59 +00004912 SmallVector<CXXCtorInitializer*, 4> NewInits;
Richard Smith60f2e1e2012-09-25 00:23:05 +00004913 bool AnyErrors = Tmpl->isInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004914
Anders Carlsson70553942009-08-29 05:16:22 +00004915 // Instantiate all the initializers.
Aaron Ballman0ad78302014-03-13 17:34:31 +00004916 for (const auto *Init : Tmpl->inits()) {
Chandler Carruthf92bd8c2010-09-03 21:54:20 +00004917 // Only instantiate written initializers, let Sema re-construct implicit
4918 // ones.
4919 if (!Init->isWritten())
4920 continue;
4921
Douglas Gregor44e7df62011-01-04 00:32:56 +00004922 SourceLocation EllipsisLoc;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004923
Douglas Gregor44e7df62011-01-04 00:32:56 +00004924 if (Init->isPackExpansion()) {
4925 // This is a pack expansion. We should expand it now.
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004926 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
Nick Lewycky2c308502013-06-13 00:45:47 +00004927 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
Douglas Gregor44e7df62011-01-04 00:32:56 +00004928 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
Nick Lewycky2c308502013-06-13 00:45:47 +00004929 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
Douglas Gregor44e7df62011-01-04 00:32:56 +00004930 bool ShouldExpand = false;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00004931 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00004932 Optional<unsigned> NumExpansions;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004933 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004934 BaseTL.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00004935 Unexpanded,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004936 TemplateArgs, ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00004937 RetainExpansion,
Douglas Gregor44e7df62011-01-04 00:32:56 +00004938 NumExpansions)) {
4939 AnyErrors = true;
4940 New->setInvalidDecl();
4941 continue;
4942 }
4943 assert(ShouldExpand && "Partial instantiation of base initializer?");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004944
4945 // Loop over all of the arguments in the argument pack(s),
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004946 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00004947 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
4948
4949 // Instantiate the initializer.
Sebastian Redla9351792012-02-11 23:51:47 +00004950 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4951 /*CXXDirectInit=*/true);
4952 if (TempInit.isInvalid()) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00004953 AnyErrors = true;
4954 break;
4955 }
4956
4957 // Instantiate the base type.
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004958 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004959 TemplateArgs,
4960 Init->getSourceLocation(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004961 New->getDeclName());
4962 if (!BaseTInfo) {
4963 AnyErrors = true;
4964 break;
4965 }
4966
4967 // Build the initializer.
Sebastian Redla74948d2011-09-24 17:48:25 +00004968 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004969 BaseTInfo, TempInit.get(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004970 New->getParent(),
4971 SourceLocation());
4972 if (NewInit.isInvalid()) {
4973 AnyErrors = true;
4974 break;
4975 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004976
Douglas Gregor44e7df62011-01-04 00:32:56 +00004977 NewInits.push_back(NewInit.get());
Douglas Gregor44e7df62011-01-04 00:32:56 +00004978 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004979
Douglas Gregor44e7df62011-01-04 00:32:56 +00004980 continue;
4981 }
4982
Douglas Gregorb30f22b2010-03-02 07:38:39 +00004983 // Instantiate the initializer.
Sebastian Redla9351792012-02-11 23:51:47 +00004984 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4985 /*CXXDirectInit=*/true);
4986 if (TempInit.isInvalid()) {
Douglas Gregorb30f22b2010-03-02 07:38:39 +00004987 AnyErrors = true;
4988 continue;
Anders Carlsson70553942009-08-29 05:16:22 +00004989 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004990
Anders Carlsson70553942009-08-29 05:16:22 +00004991 MemInitResult NewInit;
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004992 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
4993 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
4994 TemplateArgs,
4995 Init->getSourceLocation(),
4996 New->getDeclName());
4997 if (!TInfo) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004998 AnyErrors = true;
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00004999 New->setInvalidDecl();
5000 continue;
5001 }
Sebastian Redla74948d2011-09-24 17:48:25 +00005002
Douglas Gregord73f3dd2011-11-01 01:16:03 +00005003 if (Init->isBaseInitializer())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005004 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
Douglas Gregord73f3dd2011-11-01 01:16:03 +00005005 New->getParent(), EllipsisLoc);
5006 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005007 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
Douglas Gregord73f3dd2011-11-01 01:16:03 +00005008 cast<CXXRecordDecl>(CurContext->getParent()));
Anders Carlsson70553942009-08-29 05:16:22 +00005009 } else if (Init->isMemberInitializer()) {
Douglas Gregor55e6b312011-03-04 19:46:35 +00005010 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
Francois Pichetd583da02010-12-04 09:14:42 +00005011 Init->getMemberLocation(),
5012 Init->getMember(),
5013 TemplateArgs));
Douglas Gregor55e6b312011-03-04 19:46:35 +00005014 if (!Member) {
5015 AnyErrors = true;
5016 New->setInvalidDecl();
5017 continue;
5018 }
Mike Stump11289f42009-09-09 15:08:12 +00005019
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005020 NewInit = BuildMemberInitializer(Member, TempInit.get(),
Sebastian Redla74948d2011-09-24 17:48:25 +00005021 Init->getSourceLocation());
Francois Pichetd583da02010-12-04 09:14:42 +00005022 } else if (Init->isIndirectMemberInitializer()) {
5023 IndirectFieldDecl *IndirectMember =
Douglas Gregor55e6b312011-03-04 19:46:35 +00005024 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
Francois Pichetd583da02010-12-04 09:14:42 +00005025 Init->getMemberLocation(),
5026 Init->getIndirectMember(), TemplateArgs));
5027
Douglas Gregor55e6b312011-03-04 19:46:35 +00005028 if (!IndirectMember) {
5029 AnyErrors = true;
5030 New->setInvalidDecl();
Sebastian Redla74948d2011-09-24 17:48:25 +00005031 continue;
Douglas Gregor55e6b312011-03-04 19:46:35 +00005032 }
Sebastian Redla74948d2011-09-24 17:48:25 +00005033
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005034 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
Sebastian Redla74948d2011-09-24 17:48:25 +00005035 Init->getSourceLocation());
Anders Carlsson70553942009-08-29 05:16:22 +00005036 }
5037
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005038 if (NewInit.isInvalid()) {
5039 AnyErrors = true;
Anders Carlsson70553942009-08-29 05:16:22 +00005040 New->setInvalidDecl();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005041 } else {
Richard Trieu9becef62011-09-09 03:18:59 +00005042 NewInits.push_back(NewInit.get());
Anders Carlsson70553942009-08-29 05:16:22 +00005043 }
5044 }
Mike Stump11289f42009-09-09 15:08:12 +00005045
Anders Carlsson70553942009-08-29 05:16:22 +00005046 // Assign all the initializers to the new constructor.
John McCall48871652010-08-21 09:40:31 +00005047 ActOnMemInitializers(New,
Anders Carlsson70553942009-08-29 05:16:22 +00005048 /*FIXME: ColonLoc */
5049 SourceLocation(),
David Blaikie3fc2f912013-01-17 05:26:25 +00005050 NewInits,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005051 AnyErrors);
Anders Carlsson70553942009-08-29 05:16:22 +00005052}
5053
John McCall59660882009-08-29 08:11:13 +00005054// TODO: this could be templated if the various decl types used the
5055// same method name.
5056static bool isInstantiationOf(ClassTemplateDecl *Pattern,
5057 ClassTemplateDecl *Instance) {
5058 Pattern = Pattern->getCanonicalDecl();
5059
5060 do {
5061 Instance = Instance->getCanonicalDecl();
5062 if (Pattern == Instance) return true;
5063 Instance = Instance->getInstantiatedFromMemberTemplate();
5064 } while (Instance);
5065
5066 return false;
5067}
5068
Douglas Gregor14d1bf42009-09-28 06:34:35 +00005069static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
5070 FunctionTemplateDecl *Instance) {
5071 Pattern = Pattern->getCanonicalDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005072
Douglas Gregor14d1bf42009-09-28 06:34:35 +00005073 do {
5074 Instance = Instance->getCanonicalDecl();
5075 if (Pattern == Instance) return true;
5076 Instance = Instance->getInstantiatedFromMemberTemplate();
5077 } while (Instance);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005078
Douglas Gregor14d1bf42009-09-28 06:34:35 +00005079 return false;
5080}
5081
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005082static bool
Douglas Gregor21610382009-10-29 00:04:11 +00005083isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
5084 ClassTemplatePartialSpecializationDecl *Instance) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005085 Pattern
Douglas Gregor21610382009-10-29 00:04:11 +00005086 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
5087 do {
5088 Instance = cast<ClassTemplatePartialSpecializationDecl>(
5089 Instance->getCanonicalDecl());
5090 if (Pattern == Instance)
5091 return true;
5092 Instance = Instance->getInstantiatedFromMember();
5093 } while (Instance);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005094
Douglas Gregor21610382009-10-29 00:04:11 +00005095 return false;
5096}
5097
John McCall59660882009-08-29 08:11:13 +00005098static bool isInstantiationOf(CXXRecordDecl *Pattern,
5099 CXXRecordDecl *Instance) {
5100 Pattern = Pattern->getCanonicalDecl();
5101
5102 do {
5103 Instance = Instance->getCanonicalDecl();
5104 if (Pattern == Instance) return true;
5105 Instance = Instance->getInstantiatedFromMemberClass();
5106 } while (Instance);
5107
5108 return false;
5109}
5110
5111static bool isInstantiationOf(FunctionDecl *Pattern,
5112 FunctionDecl *Instance) {
5113 Pattern = Pattern->getCanonicalDecl();
5114
5115 do {
5116 Instance = Instance->getCanonicalDecl();
5117 if (Pattern == Instance) return true;
5118 Instance = Instance->getInstantiatedFromMemberFunction();
5119 } while (Instance);
5120
5121 return false;
5122}
5123
5124static bool isInstantiationOf(EnumDecl *Pattern,
5125 EnumDecl *Instance) {
5126 Pattern = Pattern->getCanonicalDecl();
5127
5128 do {
5129 Instance = Instance->getCanonicalDecl();
5130 if (Pattern == Instance) return true;
5131 Instance = Instance->getInstantiatedFromMemberEnum();
5132 } while (Instance);
5133
5134 return false;
5135}
5136
John McCallb96ec562009-12-04 22:46:56 +00005137static bool isInstantiationOf(UsingShadowDecl *Pattern,
5138 UsingShadowDecl *Instance,
5139 ASTContext &C) {
Richard Smith32952e12014-10-14 02:00:47 +00005140 return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
5141 Pattern);
John McCallb96ec562009-12-04 22:46:56 +00005142}
5143
Richard Smith151c4562016-12-20 21:35:28 +00005144static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance,
John McCallb96ec562009-12-04 22:46:56 +00005145 ASTContext &C) {
Richard Smith32952e12014-10-14 02:00:47 +00005146 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
John McCallb96ec562009-12-04 22:46:56 +00005147}
5148
Richard Smith151c4562016-12-20 21:35:28 +00005149template<typename T>
5150static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other,
5151 ASTContext &Ctx) {
5152 // An unresolved using declaration can instantiate to an unresolved using
5153 // declaration, or to a using declaration or a using declaration pack.
5154 //
5155 // Multiple declarations can claim to be instantiated from an unresolved
5156 // using declaration if it's a pack expansion. We want the UsingPackDecl
5157 // in that case, not the individual UsingDecls within the pack.
5158 bool OtherIsPackExpansion;
5159 NamedDecl *OtherFrom;
5160 if (auto *OtherUUD = dyn_cast<T>(Other)) {
5161 OtherIsPackExpansion = OtherUUD->isPackExpansion();
5162 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD);
5163 } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) {
5164 OtherIsPackExpansion = true;
5165 OtherFrom = OtherUPD->getInstantiatedFromUsingDecl();
5166 } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) {
5167 OtherIsPackExpansion = false;
5168 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD);
5169 } else {
5170 return false;
5171 }
5172 return Pattern->isPackExpansion() == OtherIsPackExpansion &&
5173 declaresSameEntity(OtherFrom, Pattern);
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00005174}
5175
John McCall59660882009-08-29 08:11:13 +00005176static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
5177 VarDecl *Instance) {
5178 assert(Instance->isStaticDataMember());
5179
5180 Pattern = Pattern->getCanonicalDecl();
5181
5182 do {
5183 Instance = Instance->getCanonicalDecl();
5184 if (Pattern == Instance) return true;
5185 Instance = Instance->getInstantiatedFromStaticDataMember();
5186 } while (Instance);
5187
5188 return false;
5189}
5190
John McCallb96ec562009-12-04 22:46:56 +00005191// Other is the prospective instantiation
5192// D is the prospective pattern
Douglas Gregor51783312009-05-27 05:35:12 +00005193static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Richard Smith151c4562016-12-20 21:35:28 +00005194 if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D))
5195 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
John McCalle61f2ba2009-11-18 02:36:19 +00005196
Richard Smith151c4562016-12-20 21:35:28 +00005197 if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D))
5198 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
Douglas Gregor51783312009-05-27 05:35:12 +00005199
Richard Smith151c4562016-12-20 21:35:28 +00005200 if (D->getKind() != Other->getKind())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00005201 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005202
Richard Smithd8a9e372016-12-18 21:39:37 +00005203 if (auto *Record = dyn_cast<CXXRecordDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00005204 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump11289f42009-09-09 15:08:12 +00005205
Richard Smithd8a9e372016-12-18 21:39:37 +00005206 if (auto *Function = dyn_cast<FunctionDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00005207 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor51783312009-05-27 05:35:12 +00005208
Richard Smithd8a9e372016-12-18 21:39:37 +00005209 if (auto *Enum = dyn_cast<EnumDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00005210 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor51783312009-05-27 05:35:12 +00005211
Richard Smithd8a9e372016-12-18 21:39:37 +00005212 if (auto *Var = dyn_cast<VarDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00005213 if (Var->isStaticDataMember())
5214 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
5215
Richard Smithd8a9e372016-12-18 21:39:37 +00005216 if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00005217 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregorf3db0032009-08-28 22:03:51 +00005218
Richard Smithd8a9e372016-12-18 21:39:37 +00005219 if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other))
Douglas Gregor14d1bf42009-09-28 06:34:35 +00005220 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
5221
Richard Smithd8a9e372016-12-18 21:39:37 +00005222 if (auto *PartialSpec =
5223 dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
Douglas Gregor21610382009-10-29 00:04:11 +00005224 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
5225 PartialSpec);
5226
Richard Smithd8a9e372016-12-18 21:39:37 +00005227 if (auto *Field = dyn_cast<FieldDecl>(Other)) {
Anders Carlsson5da84842009-09-01 04:26:58 +00005228 if (!Field->getDeclName()) {
5229 // This is an unnamed field.
Richard Smith32952e12014-10-14 02:00:47 +00005230 return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field),
5231 cast<FieldDecl>(D));
Anders Carlsson5da84842009-09-01 04:26:58 +00005232 }
5233 }
Mike Stump11289f42009-09-09 15:08:12 +00005234
Richard Smithd8a9e372016-12-18 21:39:37 +00005235 if (auto *Using = dyn_cast<UsingDecl>(Other))
John McCallb96ec562009-12-04 22:46:56 +00005236 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
5237
Richard Smithd8a9e372016-12-18 21:39:37 +00005238 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other))
John McCallb96ec562009-12-04 22:46:56 +00005239 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
5240
Richard Smithd8a9e372016-12-18 21:39:37 +00005241 return D->getDeclName() &&
5242 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
Douglas Gregor51783312009-05-27 05:35:12 +00005243}
5244
5245template<typename ForwardIterator>
Mike Stump11289f42009-09-09 15:08:12 +00005246static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor51783312009-05-27 05:35:12 +00005247 NamedDecl *D,
5248 ForwardIterator first,
5249 ForwardIterator last) {
5250 for (; first != last; ++first)
5251 if (isInstantiationOf(Ctx, D, *first))
5252 return cast<NamedDecl>(*first);
5253
Craig Topperc3ec1492014-05-26 06:22:03 +00005254 return nullptr;
Douglas Gregor51783312009-05-27 05:35:12 +00005255}
5256
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005257/// Finds the instantiation of the given declaration context
John McCallaa74a0c2009-08-28 07:59:38 +00005258/// within the current instantiation.
5259///
5260/// \returns NULL if there was an error
Douglas Gregora04f2ca2010-03-01 15:56:25 +00005261DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregor64621e62009-09-16 18:34:49 +00005262 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCallaa74a0c2009-08-28 07:59:38 +00005263 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Richard Smith4f440e32017-06-08 01:08:50 +00005264 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true);
John McCallaa74a0c2009-08-28 07:59:38 +00005265 return cast_or_null<DeclContext>(ID);
5266 } else return DC;
5267}
5268
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005269/// Find the instantiation of the given declaration within the
Douglas Gregorcd3a0972009-05-27 17:54:46 +00005270/// current instantiation.
Douglas Gregor51783312009-05-27 05:35:12 +00005271///
5272/// This routine is intended to be used when \p D is a declaration
5273/// referenced from within a template, that needs to mapped into the
5274/// corresponding declaration within an instantiation. For example,
5275/// given:
5276///
5277/// \code
5278/// template<typename T>
5279/// struct X {
5280/// enum Kind {
5281/// KnownValue = sizeof(T)
5282/// };
5283///
5284/// bool getKind() const { return KnownValue; }
5285/// };
5286///
5287/// template struct X<int>;
5288/// \endcode
5289///
Erik Pilkington4cae0922019-07-30 23:38:18 +00005290/// In the instantiation of X<int>::getKind(), we need to map the \p
5291/// EnumConstantDecl for \p KnownValue (which refers to
5292/// X<T>::<Kind>::KnownValue) to its instantiation (X<int>::<Kind>::KnownValue).
5293/// \p FindInstantiatedDecl performs this mapping from within the instantiation
5294/// of X<int>.
Douglas Gregora04f2ca2010-03-01 15:56:25 +00005295NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Richard Smith4f440e32017-06-08 01:08:50 +00005296 const MultiLevelTemplateArgumentList &TemplateArgs,
5297 bool FindingInstantiatedContext) {
Douglas Gregor51783312009-05-27 05:35:12 +00005298 DeclContext *ParentDC = D->getDeclContext();
Fangrui Song6907ce22018-07-30 19:24:48 +00005299 // FIXME: Parmeters of pointer to functions (y below) that are themselves
Faisal Vali2cba1332013-10-23 06:44:28 +00005300 // parameters (p below) can have their ParentDC set to the translation-unit
Fangrui Song6907ce22018-07-30 19:24:48 +00005301 // - thus we can not consistently check if the ParentDC of such a parameter
Faisal Vali2cba1332013-10-23 06:44:28 +00005302 // is Dependent or/and a FunctionOrMethod.
Fangrui Song6907ce22018-07-30 19:24:48 +00005303 // For e.g. this code, during Template argument deduction tries to
Faisal Vali2cba1332013-10-23 06:44:28 +00005304 // find an instantiated decl for (T y) when the ParentDC for y is
Fangrui Song6907ce22018-07-30 19:24:48 +00005305 // the translation unit.
5306 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
Aaron Ballman36a53502014-01-16 13:03:14 +00005307 // float baz(float(*)()) { return 0.0; }
Faisal Vali2cba1332013-10-23 06:44:28 +00005308 // Foo(baz);
5309 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
5310 // it gets here, always has a FunctionOrMethod as its ParentDC??
5311 // For now:
5312 // - as long as we have a ParmVarDecl whose parent is non-dependent and
5313 // whose type is not instantiation dependent, do nothing to the decl
5314 // - otherwise find its instantiated decl.
5315 if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() &&
5316 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
5317 return D;
Rafael Espindola09b00e32013-10-23 04:12:23 +00005318 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregorb93971082010-02-05 19:54:12 +00005319 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Alexey Bataeve6aa4692018-09-13 16:54:05 +00005320 ((ParentDC->isFunctionOrMethod() ||
Michael Kruse251e1482019-02-01 20:25:04 +00005321 isa<OMPDeclareReductionDecl>(ParentDC) ||
5322 isa<OMPDeclareMapperDecl>(ParentDC)) &&
Alexey Bataeve6aa4692018-09-13 16:54:05 +00005323 ParentDC->isDependentContext()) ||
Douglas Gregora86bc002012-02-16 21:36:18 +00005324 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
Douglas Gregorf98d9b62009-05-27 17:07:49 +00005325 // D is a local of some kind. Look into the map of local
5326 // declarations to their instantiations.
Alexey Samsonov2c0aac22014-09-03 18:45:45 +00005327 if (CurrentInstantiationScope) {
5328 if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
5329 if (Decl *FD = Found->dyn_cast<Decl *>())
5330 return cast<NamedDecl>(FD);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005331
Alexey Samsonov2c0aac22014-09-03 18:45:45 +00005332 int PackIdx = ArgumentPackSubstitutionIndex;
5333 assert(PackIdx != -1 &&
5334 "found declaration pack but not pack expanding");
5335 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
5336 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
5337 }
Chris Lattnercab02a62011-02-17 20:34:02 +00005338 }
5339
Serge Pavlov7cd8f602013-07-15 06:14:07 +00005340 // If we're performing a partial substitution during template argument
5341 // deduction, we may not have values for template parameters yet. They
5342 // just map to themselves.
5343 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
5344 isa<TemplateTemplateParmDecl>(D))
5345 return D;
5346
Serge Pavlov074a5182013-08-10 12:00:21 +00005347 if (D->isInvalidDecl())
Craig Topperc3ec1492014-05-26 06:22:03 +00005348 return nullptr;
Serge Pavlov074a5182013-08-10 12:00:21 +00005349
Serge Pavlove7ad8312015-05-15 10:10:28 +00005350 // Normally this function only searches for already instantiated declaration
5351 // however we have to make an exclusion for local types used before
5352 // definition as in the code:
5353 //
5354 // template<typename T> void f1() {
5355 // void g1(struct x1);
5356 // struct x1 {};
5357 // }
5358 //
5359 // In this case instantiation of the type of 'g1' requires definition of
5360 // 'x1', which is defined later. Error recovery may produce an enum used
5361 // before definition. In these cases we need to instantiate relevant
5362 // declarations here.
5363 bool NeedInstantiate = false;
5364 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5365 NeedInstantiate = RD->isLocalClass();
5366 else
5367 NeedInstantiate = isa<EnumDecl>(D);
5368 if (NeedInstantiate) {
Serge Pavlov4c511742015-05-04 16:44:39 +00005369 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
5370 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
5371 return cast<TypeDecl>(Inst);
5372 }
5373
Chris Lattnercab02a62011-02-17 20:34:02 +00005374 // If we didn't find the decl, then we must have a label decl that hasn't
5375 // been found yet. Lazily instantiate it and return it now.
5376 assert(isa<LabelDecl>(D));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005377
Chris Lattnercab02a62011-02-17 20:34:02 +00005378 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
5379 assert(Inst && "Failed to instantiate label??");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005380
Chris Lattnercab02a62011-02-17 20:34:02 +00005381 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
5382 return cast<LabelDecl>(Inst);
Douglas Gregorf98d9b62009-05-27 17:07:49 +00005383 }
Douglas Gregor51783312009-05-27 05:35:12 +00005384
Douglas Gregor64621e62009-09-16 18:34:49 +00005385 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
5386 if (!Record->isDependentContext())
5387 return D;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005388
Douglas Gregor4109afa2011-11-07 17:43:18 +00005389 // Determine whether this record is the "templated" declaration describing
5390 // a class template or class template partial specialization.
Douglas Gregor64621e62009-09-16 18:34:49 +00005391 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
Douglas Gregor4109afa2011-11-07 17:43:18 +00005392 if (ClassTemplate)
5393 ClassTemplate = ClassTemplate->getCanonicalDecl();
5394 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5395 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
5396 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
Larisse Voufo39a1e502013-08-06 01:03:05 +00005397
Douglas Gregor4109afa2011-11-07 17:43:18 +00005398 // Walk the current context to find either the record or an instantiation of
5399 // it.
5400 DeclContext *DC = CurContext;
5401 while (!DC->isFileContext()) {
5402 // If we're performing substitution while we're inside the template
5403 // definition, we'll find our own context. We're done.
5404 if (DC->Equals(Record))
5405 return Record;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005406
Douglas Gregor4109afa2011-11-07 17:43:18 +00005407 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
5408 // Check whether we're in the process of instantiating a class template
5409 // specialization of the template we're mapping.
5410 if (ClassTemplateSpecializationDecl *InstSpec
5411 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
5412 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
5413 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
5414 return InstRecord;
5415 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00005416
Douglas Gregor4109afa2011-11-07 17:43:18 +00005417 // Check whether we're in the process of instantiating a member class.
5418 if (isInstantiationOf(Record, InstRecord))
5419 return InstRecord;
Douglas Gregor64621e62009-09-16 18:34:49 +00005420 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00005421
Douglas Gregor4109afa2011-11-07 17:43:18 +00005422 // Move to the outer template scope.
5423 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
5424 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
5425 DC = FD->getLexicalDeclContext();
5426 continue;
5427 }
Richard Smith32918772017-02-14 00:25:28 +00005428 // An implicit deduction guide acts as if it's within the class template
5429 // specialization described by its name and first N template params.
Richard Smithbc491202017-02-17 20:05:37 +00005430 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD);
5431 if (Guide && Guide->isImplicit()) {
5432 TemplateDecl *TD = Guide->getDeducedTemplate();
Richard Smith0cd9c042017-02-21 08:42:39 +00005433 // Convert the arguments to an "as-written" list.
Richard Smith32918772017-02-14 00:25:28 +00005434 TemplateArgumentListInfo Args(Loc, Loc);
Richard Smith0cd9c042017-02-21 08:42:39 +00005435 for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front(
5436 TD->getTemplateParameters()->size())) {
5437 ArrayRef<TemplateArgument> Unpacked(Arg);
5438 if (Arg.getKind() == TemplateArgument::Pack)
5439 Unpacked = Arg.pack_elements();
5440 for (TemplateArgument UnpackedArg : Unpacked)
5441 Args.addArgument(
5442 getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc));
5443 }
Richard Smith32918772017-02-14 00:25:28 +00005444 QualType T = CheckTemplateIdType(TemplateName(TD), Loc, Args);
5445 if (T.isNull())
5446 return nullptr;
Richard Smithe6d4b772017-06-07 02:42:27 +00005447 auto *SubstRecord = T->getAsCXXRecordDecl();
5448 assert(SubstRecord && "class template id not a class type?");
5449 // Check that this template-id names the primary template and not a
5450 // partial or explicit specialization. (In the latter cases, it's
5451 // meaningless to attempt to find an instantiation of D within the
5452 // specialization.)
5453 // FIXME: The standard doesn't say what should happen here.
Richard Smith4f440e32017-06-08 01:08:50 +00005454 if (FindingInstantiatedContext &&
5455 usesPartialOrExplicitSpecialization(
5456 Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) {
Richard Smithe6d4b772017-06-07 02:42:27 +00005457 Diag(Loc, diag::err_specialization_not_primary_template)
5458 << T << (SubstRecord->getTemplateSpecializationKind() ==
5459 TSK_ExplicitSpecialization);
5460 return nullptr;
5461 }
5462 DC = SubstRecord;
Richard Smith32918772017-02-14 00:25:28 +00005463 continue;
5464 }
John McCall59660882009-08-29 08:11:13 +00005465 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00005466
Douglas Gregor4109afa2011-11-07 17:43:18 +00005467 DC = DC->getParent();
John McCall59660882009-08-29 08:11:13 +00005468 }
Douglas Gregord225fa02010-02-05 22:40:03 +00005469
Douglas Gregor64621e62009-09-16 18:34:49 +00005470 // Fall through to deal with other dependent record types (e.g.,
5471 // anonymous unions in class templates).
5472 }
John McCall59660882009-08-29 08:11:13 +00005473
Douglas Gregor64621e62009-09-16 18:34:49 +00005474 if (!ParentDC->isDependentContext())
5475 return D;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005476
Douglas Gregora04f2ca2010-03-01 15:56:25 +00005477 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00005478 if (!ParentDC)
Craig Topperc3ec1492014-05-26 06:22:03 +00005479 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005480
Douglas Gregor51783312009-05-27 05:35:12 +00005481 if (ParentDC != D->getDeclContext()) {
5482 // We performed some kind of instantiation in the parent context,
5483 // so now we need to look into the instantiated parent context to
5484 // find the instantiation of the declaration D.
Douglas Gregora04f2ca2010-03-01 15:56:25 +00005485
John McCalle78aac42010-03-10 03:28:59 +00005486 // If our context used to be dependent, we may need to instantiate
5487 // it before performing lookup into that context.
Douglas Gregor528ad932011-03-06 20:12:45 +00005488 bool IsBeingInstantiated = false;
John McCalle78aac42010-03-10 03:28:59 +00005489 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00005490 if (!Spec->isDependentContext()) {
5491 QualType T = Context.getTypeDeclType(Spec);
John McCalle78aac42010-03-10 03:28:59 +00005492 const RecordType *Tag = T->getAs<RecordType>();
5493 assert(Tag && "type of non-dependent record is not a RecordType");
Douglas Gregor528ad932011-03-06 20:12:45 +00005494 if (Tag->isBeingDefined())
5495 IsBeingInstantiated = true;
John McCalle78aac42010-03-10 03:28:59 +00005496 if (!Tag->isBeingDefined() &&
5497 RequireCompleteType(Loc, T, diag::err_incomplete_type))
Craig Topperc3ec1492014-05-26 06:22:03 +00005498 return nullptr;
Douglas Gregor25edf432010-11-05 23:22:45 +00005499
5500 ParentDC = Tag->getDecl();
Douglas Gregora04f2ca2010-03-01 15:56:25 +00005501 }
5502 }
5503
Craig Topperc3ec1492014-05-26 06:22:03 +00005504 NamedDecl *Result = nullptr;
Richard Smith151c4562016-12-20 21:35:28 +00005505 // FIXME: If the name is a dependent name, this lookup won't necessarily
5506 // find it. Does that ever matter?
Akira Hatanaka59e3b432017-01-31 19:53:32 +00005507 if (auto Name = D->getDeclName()) {
5508 DeclarationNameInfo NameInfo(Name, D->getLocation());
Erik Pilkington4cae0922019-07-30 23:38:18 +00005509 DeclarationNameInfo NewNameInfo =
5510 SubstDeclarationNameInfo(NameInfo, TemplateArgs);
5511 Name = NewNameInfo.getName();
Akira Hatanaka59e3b432017-01-31 19:53:32 +00005512 if (!Name)
5513 return nullptr;
5514 DeclContext::lookup_result Found = ParentDC->lookup(Name);
Erik Pilkington4cae0922019-07-30 23:38:18 +00005515
5516 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) {
5517 VarTemplateDecl *Templ = cast_or_null<VarTemplateDecl>(
5518 findInstantiationOf(Context, VTSD->getSpecializedTemplate(),
5519 Found.begin(), Found.end()));
5520 if (!Templ)
5521 return nullptr;
5522 Result = getVarTemplateSpecialization(
5523 Templ, &VTSD->getTemplateArgsInfo(), NewNameInfo, SourceLocation());
5524 } else
5525 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
Douglas Gregor51783312009-05-27 05:35:12 +00005526 } else {
5527 // Since we don't have a name for the entity we're looking for,
5528 // our only option is to walk through all of the declarations to
5529 // find that name. This will occur in a few cases:
5530 //
5531 // - anonymous struct/union within a template
5532 // - unnamed class/struct/union/enum within a template
5533 //
5534 // FIXME: Find a better way to find these instantiations!
Mike Stump11289f42009-09-09 15:08:12 +00005535 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005536 ParentDC->decls_begin(),
5537 ParentDC->decls_end());
Douglas Gregor51783312009-05-27 05:35:12 +00005538 }
Mike Stump11289f42009-09-09 15:08:12 +00005539
Douglas Gregor528ad932011-03-06 20:12:45 +00005540 if (!Result) {
5541 if (isa<UsingShadowDecl>(D)) {
5542 // UsingShadowDecls can instantiate to nothing because of using hiding.
5543 } else if (Diags.hasErrorOccurred()) {
5544 // We've already complained about something, so most likely this
5545 // declaration failed to instantiate. There's no point in complaining
5546 // further, since this is normal in invalid code.
5547 } else if (IsBeingInstantiated) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005548 // The class in which this member exists is currently being
Douglas Gregor528ad932011-03-06 20:12:45 +00005549 // instantiated, and we haven't gotten around to instantiating this
5550 // member yet. This can happen when the code uses forward declarations
5551 // of member classes, and introduces ordering dependencies via
5552 // template instantiation.
5553 Diag(Loc, diag::err_member_not_yet_instantiated)
5554 << D->getDeclName()
5555 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
5556 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
Richard Smith169f2192012-03-26 20:28:16 +00005557 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
5558 // This enumeration constant was found when the template was defined,
5559 // but can't be found in the instantiation. This can happen if an
5560 // unscoped enumeration member is explicitly specialized.
5561 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
5562 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
5563 TemplateArgs));
5564 assert(Spec->getTemplateSpecializationKind() ==
5565 TSK_ExplicitSpecialization);
5566 Diag(Loc, diag::err_enumerator_does_not_exist)
5567 << D->getDeclName()
5568 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
5569 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
5570 << Context.getTypeDeclType(Spec);
Douglas Gregor528ad932011-03-06 20:12:45 +00005571 } else {
5572 // We should have found something, but didn't.
5573 llvm_unreachable("Unable to find instantiation of declaration!");
5574 }
5575 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005576
Douglas Gregor51783312009-05-27 05:35:12 +00005577 D = Result;
5578 }
5579
Douglas Gregor51783312009-05-27 05:35:12 +00005580 return D;
5581}
Douglas Gregor77b50e12009-06-22 23:06:13 +00005582
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005583/// Performs template instantiation for all implicit template
Douglas Gregor77b50e12009-06-22 23:06:13 +00005584/// instantiations we have seen until this point.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00005585void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregor7f792cf2010-01-16 22:29:39 +00005586 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth54080172010-08-25 08:44:16 +00005587 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor7f792cf2010-01-16 22:29:39 +00005588 PendingImplicitInstantiation Inst;
5589
5590 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth54080172010-08-25 08:44:16 +00005591 Inst = PendingInstantiations.front();
5592 PendingInstantiations.pop_front();
Douglas Gregor7f792cf2010-01-16 22:29:39 +00005593 } else {
5594 Inst = PendingLocalImplicitInstantiations.front();
5595 PendingLocalImplicitInstantiations.pop_front();
5596 }
Mike Stump11289f42009-09-09 15:08:12 +00005597
Douglas Gregora6ef8f02009-07-24 20:34:43 +00005598 // Instantiate function definitions
5599 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Chandler Carruthcfe41db2010-08-25 08:27:02 +00005600 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
5601 TSK_ExplicitInstantiationDefinition;
Erich Keane0fb16482018-08-13 18:33:20 +00005602 if (Function->isMultiVersion()) {
5603 getASTContext().forEachMultiversionedFunctionVersion(
5604 Function, [this, Inst, DefinitionRequired](FunctionDecl *CurFD) {
5605 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, CurFD, true,
5606 DefinitionRequired, true);
5607 if (CurFD->isDefined())
5608 CurFD->setInstantiationIsPending(false);
5609 });
5610 } else {
5611 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, Function, true,
5612 DefinitionRequired, true);
5613 if (Function->isDefined())
5614 Function->setInstantiationIsPending(false);
5615 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00005616 continue;
5617 }
Mike Stump11289f42009-09-09 15:08:12 +00005618
Larisse Voufo39a1e502013-08-06 01:03:05 +00005619 // Instantiate variable definitions
Douglas Gregora6ef8f02009-07-24 20:34:43 +00005620 VarDecl *Var = cast<VarDecl>(Inst.first);
Larisse Voufo39a1e502013-08-06 01:03:05 +00005621
5622 assert((Var->isStaticDataMember() ||
5623 isa<VarTemplateSpecializationDecl>(Var)) &&
5624 "Not a static data member, nor a variable template"
5625 " specialization?");
Anders Carlsson62215c42009-09-01 05:12:24 +00005626
Chandler Carruth6b4756a2010-02-13 10:17:50 +00005627 // Don't try to instantiate declarations if the most recent redeclaration
5628 // is invalid.
Douglas Gregorec9fd132012-01-14 16:38:05 +00005629 if (Var->getMostRecentDecl()->isInvalidDecl())
Chandler Carruth6b4756a2010-02-13 10:17:50 +00005630 continue;
5631
5632 // Check if the most recent declaration has changed the specialization kind
5633 // and removed the need for implicit instantiation.
Richard Smitha6b41d72019-05-03 23:51:38 +00005634 switch (Var->getMostRecentDecl()
5635 ->getTemplateSpecializationKindForInstantiation()) {
Chandler Carruth6b4756a2010-02-13 10:17:50 +00005636 case TSK_Undeclared:
David Blaikie83d382b2011-09-23 05:06:16 +00005637 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
Chandler Carruth6b4756a2010-02-13 10:17:50 +00005638 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth6b4756a2010-02-13 10:17:50 +00005639 case TSK_ExplicitSpecialization:
Chandler Carruthcfe41db2010-08-25 08:27:02 +00005640 continue; // No longer need to instantiate this type.
5641 case TSK_ExplicitInstantiationDefinition:
5642 // We only need an instantiation if the pending instantiation *is* the
5643 // explicit instantiation.
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00005644 if (Var != Var->getMostRecentDecl())
5645 continue;
5646 break;
Chandler Carruth6b4756a2010-02-13 10:17:50 +00005647 case TSK_ImplicitInstantiation:
5648 break;
5649 }
5650
Jordan Rose1e879d82018-03-23 00:07:18 +00005651 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00005652 "instantiating variable definition");
Chandler Carruthcfe41db2010-08-25 08:27:02 +00005653 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
5654 TSK_ExplicitInstantiationDefinition;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005655
5656 // Instantiate static data member definitions or variable template
5657 // specializations.
5658 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00005659 DefinitionRequired, true);
Douglas Gregor77b50e12009-06-22 23:06:13 +00005660 }
5661}
John McCallc62bb642010-03-24 05:22:00 +00005662
5663void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
5664 const MultiLevelTemplateArgumentList &TemplateArgs) {
Aaron Ballmanb105e492014-03-07 14:09:15 +00005665 for (auto DD : Pattern->ddiags()) {
John McCallc62bb642010-03-24 05:22:00 +00005666 switch (DD->getKind()) {
5667 case DependentDiagnostic::Access:
5668 HandleDependentAccessCheck(*DD, TemplateArgs);
5669 break;
5670 }
5671 }
5672}