blob: 91a402d6d8dc8c4a3ba0805b3efd78d60bac8ba4 [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"
Douglas Gregord7e7a512009-03-17 21:15:40 +000026
27using namespace clang;
28
David Majnemer192d1792013-11-27 08:20:38 +000029static bool isDeclWithinFunction(const Decl *D) {
30 const DeclContext *DC = D->getDeclContext();
31 if (DC->isFunctionOrMethod())
32 return true;
33
34 if (DC->isRecord())
35 return cast<CXXRecordDecl>(DC)->isLocalClass();
36
37 return false;
38}
39
Richard Smithcc928662014-10-17 20:37:29 +000040template<typename DeclT>
41static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
42 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor14454802011-02-25 02:25:35 +000043 if (!OldDecl->getQualifierLoc())
44 return false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000045
Richard Smithcc928662014-10-17 20:37:29 +000046 assert((NewDecl->getFriendObjectKind() ||
47 !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
48 "non-friend with qualified name defined in dependent context");
49 Sema::ContextRAII SavedContext(
50 SemaRef,
51 const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
52 ? NewDecl->getLexicalDeclContext()
53 : OldDecl->getLexicalDeclContext()));
54
Douglas Gregor14454802011-02-25 02:25:35 +000055 NestedNameSpecifierLoc NewQualifierLoc
Richard Smithcc928662014-10-17 20:37:29 +000056 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
57 TemplateArgs);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000058
Douglas Gregor14454802011-02-25 02:25:35 +000059 if (!NewQualifierLoc)
John McCall3e11ebe2010-03-15 10:12:16 +000060 return true;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000061
Douglas Gregor14454802011-02-25 02:25:35 +000062 NewDecl->setQualifierInfo(NewQualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +000063 return false;
64}
65
Richard Smithcc928662014-10-17 20:37:29 +000066bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
67 DeclaratorDecl *NewDecl) {
68 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
69}
70
John McCall3e11ebe2010-03-15 10:12:16 +000071bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
72 TagDecl *NewDecl) {
Richard Smithcc928662014-10-17 20:37:29 +000073 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
John McCall3e11ebe2010-03-15 10:12:16 +000074}
75
DeLesley Hutchinsceec3062012-01-20 22:37:06 +000076// Include attribute instantiation code.
77#include "clang/Sema/AttrTemplateInstantiate.inc"
78
Richard Smith44c247f2013-02-22 08:32:16 +000079static void instantiateDependentAlignedAttr(
80 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
81 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
82 if (Aligned->isAlignmentExpr()) {
83 // The alignment expression is a constant expression.
Faisal Valid143a0c2017-04-01 21:30:49 +000084 EnterExpressionEvaluationContext Unevaluated(
85 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Richard Smith44c247f2013-02-22 08:32:16 +000086 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
87 if (!Result.isInvalid())
Nikola Smiljanic01a75982014-05-29 10:55:11 +000088 S.AddAlignedAttr(Aligned->getLocation(), New, Result.getAs<Expr>(),
Richard Smith44c247f2013-02-22 08:32:16 +000089 Aligned->getSpellingListIndex(), IsPackExpansion);
90 } else {
91 TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
92 TemplateArgs, Aligned->getLocation(),
93 DeclarationName());
94 if (Result)
95 S.AddAlignedAttr(Aligned->getLocation(), New, Result,
96 Aligned->getSpellingListIndex(), IsPackExpansion);
97 }
98}
99
100static void instantiateDependentAlignedAttr(
101 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
102 const AlignedAttr *Aligned, Decl *New) {
103 if (!Aligned->isPackExpansion()) {
104 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
105 return;
106 }
107
108 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
109 if (Aligned->isAlignmentExpr())
110 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
111 Unexpanded);
112 else
113 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
114 Unexpanded);
115 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
116
117 // Determine whether we can expand this attribute pack yet.
118 bool Expand = true, RetainExpansion = false;
119 Optional<unsigned> NumExpansions;
120 // FIXME: Use the actual location of the ellipsis.
121 SourceLocation EllipsisLoc = Aligned->getLocation();
122 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
123 Unexpanded, TemplateArgs, Expand,
124 RetainExpansion, NumExpansions))
125 return;
126
127 if (!Expand) {
128 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
129 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
130 } else {
131 for (unsigned I = 0; I != *NumExpansions; ++I) {
132 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
133 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
134 }
135 }
136}
137
Hal Finkelee90a222014-09-26 05:04:30 +0000138static void instantiateDependentAssumeAlignedAttr(
139 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
140 const AssumeAlignedAttr *Aligned, Decl *New) {
141 // The alignment expression is a constant expression.
Faisal Valid143a0c2017-04-01 21:30:49 +0000142 EnterExpressionEvaluationContext Unevaluated(
143 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Hal Finkelee90a222014-09-26 05:04:30 +0000144
145 Expr *E, *OE = nullptr;
146 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
147 if (Result.isInvalid())
148 return;
149 E = Result.getAs<Expr>();
150
151 if (Aligned->getOffset()) {
152 Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
153 if (Result.isInvalid())
154 return;
155 OE = Result.getAs<Expr>();
156 }
157
158 S.AddAssumeAlignedAttr(Aligned->getLocation(), New, E, OE,
159 Aligned->getSpellingListIndex());
160}
161
Hal Finkel1b0d24e2014-10-02 21:21:25 +0000162static void instantiateDependentAlignValueAttr(
163 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
164 const AlignValueAttr *Aligned, Decl *New) {
165 // The alignment expression is a constant expression.
Faisal Valid143a0c2017-04-01 21:30:49 +0000166 EnterExpressionEvaluationContext Unevaluated(
167 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Hal Finkel1b0d24e2014-10-02 21:21:25 +0000168 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
169 if (!Result.isInvalid())
170 S.AddAlignValueAttr(Aligned->getLocation(), New, Result.getAs<Expr>(),
171 Aligned->getSpellingListIndex());
172}
173
Erich Keane623efd82017-03-30 21:48:55 +0000174static void instantiateDependentAllocAlignAttr(
175 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
176 const AllocAlignAttr *Align, Decl *New) {
177 Expr *Param = IntegerLiteral::Create(
Joel E. Denny81508102018-03-13 14:51:22 +0000178 S.getASTContext(),
179 llvm::APInt(64, Align->getParamIndex().getSourceIndex()),
Erich Keane623efd82017-03-30 21:48:55 +0000180 S.getASTContext().UnsignedLongLongTy, Align->getLocation());
181 S.AddAllocAlignAttr(Align->getLocation(), New, Param,
182 Align->getSpellingListIndex());
183}
184
George Burgess IV177399e2017-01-09 04:12:14 +0000185static Expr *instantiateDependentFunctionAttrCondition(
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000186 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
George Burgess IV177399e2017-01-09 04:12:14 +0000187 const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000188 Expr *Cond = nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000189 {
George Burgess IV177399e2017-01-09 04:12:14 +0000190 Sema::ContextRAII SwitchContext(S, New);
Faisal Valid143a0c2017-04-01 21:30:49 +0000191 EnterExpressionEvaluationContext Unevaluated(
192 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
George Burgess IV177399e2017-01-09 04:12:14 +0000193 ExprResult Result = S.SubstExpr(OldCond, TemplateArgs);
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000194 if (Result.isInvalid())
George Burgess IV177399e2017-01-09 04:12:14 +0000195 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000196 Cond = Result.getAs<Expr>();
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000197 }
George Burgess IV00431952016-11-17 01:33:54 +0000198 if (!Cond->isTypeDependent()) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000199 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
200 if (Converted.isInvalid())
George Burgess IV177399e2017-01-09 04:12:14 +0000201 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000202 Cond = Converted.get();
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000203 }
204
205 SmallVector<PartialDiagnosticAt, 8> Diags;
George Burgess IV177399e2017-01-09 04:12:14 +0000206 if (OldCond->isValueDependent() && !Cond->isValueDependent() &&
207 !Expr::isPotentialConstantExprUnevaluated(Cond, New, Diags)) {
208 S.Diag(A->getLocation(), diag::err_attr_cond_never_constant_expr) << A;
209 for (const auto &P : Diags)
210 S.Diag(P.first, P.second);
211 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000212 }
George Burgess IV177399e2017-01-09 04:12:14 +0000213 return Cond;
214}
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000215
George Burgess IV177399e2017-01-09 04:12:14 +0000216static void instantiateDependentEnableIfAttr(
217 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
218 const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) {
219 Expr *Cond = instantiateDependentFunctionAttrCondition(
220 S, TemplateArgs, EIA, EIA->getCond(), Tmpl, New);
221
222 if (Cond)
223 New->addAttr(new (S.getASTContext()) EnableIfAttr(
224 EIA->getLocation(), S.getASTContext(), Cond, EIA->getMessage(),
225 EIA->getSpellingListIndex()));
226}
227
228static void instantiateDependentDiagnoseIfAttr(
229 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
230 const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) {
231 Expr *Cond = instantiateDependentFunctionAttrCondition(
232 S, TemplateArgs, DIA, DIA->getCond(), Tmpl, New);
233
234 if (Cond)
235 New->addAttr(new (S.getASTContext()) DiagnoseIfAttr(
236 DIA->getLocation(), S.getASTContext(), Cond, DIA->getMessage(),
237 DIA->getDiagnosticType(), DIA->getArgDependent(), New,
238 DIA->getSpellingListIndex()));
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000239}
240
Artem Belevich7093e402015-04-21 22:55:54 +0000241// Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
242// template A as the base and arguments from TemplateArgs.
243static void instantiateDependentCUDALaunchBoundsAttr(
244 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
245 const CUDALaunchBoundsAttr &Attr, Decl *New) {
246 // The alignment expression is a constant expression.
Faisal Valid143a0c2017-04-01 21:30:49 +0000247 EnterExpressionEvaluationContext Unevaluated(
248 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Artem Belevich7093e402015-04-21 22:55:54 +0000249
250 ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
251 if (Result.isInvalid())
252 return;
253 Expr *MaxThreads = Result.getAs<Expr>();
254
255 Expr *MinBlocks = nullptr;
256 if (Attr.getMinBlocks()) {
257 Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
258 if (Result.isInvalid())
259 return;
260 MinBlocks = Result.getAs<Expr>();
261 }
262
263 S.AddLaunchBoundsAttr(Attr.getLocation(), New, MaxThreads, MinBlocks,
264 Attr.getSpellingListIndex());
265}
266
Denis Zobnind9e2dcd2016-02-02 13:50:39 +0000267static void
268instantiateDependentModeAttr(Sema &S,
269 const MultiLevelTemplateArgumentList &TemplateArgs,
270 const ModeAttr &Attr, Decl *New) {
271 S.AddModeAttr(Attr.getRange(), New, Attr.getMode(),
272 Attr.getSpellingListIndex(), /*InInstantiation=*/true);
273}
274
Alexey Bataev2af33e32016-04-07 12:45:37 +0000275/// Instantiation of 'declare simd' attribute and its arguments.
276static void instantiateOMPDeclareSimdDeclAttr(
277 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
278 const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +0000279 // Allow 'this' in clauses with varlists.
280 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
281 New = FTD->getTemplatedDecl();
282 auto *FD = cast<FunctionDecl>(New);
283 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
Alexey Bataevecba70f2016-04-12 11:02:11 +0000284 SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
285 SmallVector<unsigned, 4> LinModifiers;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +0000286
287 auto &&Subst = [&](Expr *E) -> ExprResult {
288 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
289 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
290 Sema::ContextRAII SavedContext(S, FD);
291 LocalInstantiationScope Local(S);
292 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
293 Local.InstantiatedLocal(
294 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
295 return S.SubstExpr(E, TemplateArgs);
296 }
Mikael Nilsson9d2872d2018-12-13 10:15:27 +0000297 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
Alexey Bataeve48a5fc2016-04-12 05:28:34 +0000298 FD->isCXXInstanceMember());
299 return S.SubstExpr(E, TemplateArgs);
300 };
301
Alexey Bataevecba70f2016-04-12 11:02:11 +0000302 ExprResult Simdlen;
303 if (auto *E = Attr.getSimdlen())
304 Simdlen = Subst(E);
305
Alexey Bataeve48a5fc2016-04-12 05:28:34 +0000306 if (Attr.uniforms_size() > 0) {
307 for(auto *E : Attr.uniforms()) {
308 ExprResult Inst = Subst(E);
309 if (Inst.isInvalid())
310 continue;
311 Uniforms.push_back(Inst.get());
312 }
Alexey Bataev2af33e32016-04-07 12:45:37 +0000313 }
314
Alexey Bataevd93d3762016-04-12 09:35:56 +0000315 auto AI = Attr.alignments_begin();
316 for (auto *E : Attr.aligneds()) {
317 ExprResult Inst = Subst(E);
318 if (Inst.isInvalid())
319 continue;
320 Aligneds.push_back(Inst.get());
321 Inst = ExprEmpty();
322 if (*AI)
323 Inst = S.SubstExpr(*AI, TemplateArgs);
324 Alignments.push_back(Inst.get());
325 ++AI;
326 }
Alexey Bataevecba70f2016-04-12 11:02:11 +0000327
328 auto SI = Attr.steps_begin();
329 for (auto *E : Attr.linears()) {
330 ExprResult Inst = Subst(E);
331 if (Inst.isInvalid())
332 continue;
333 Linears.push_back(Inst.get());
334 Inst = ExprEmpty();
335 if (*SI)
336 Inst = S.SubstExpr(*SI, TemplateArgs);
337 Steps.push_back(Inst.get());
338 ++SI;
339 }
340 LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
Alexey Bataevd93d3762016-04-12 09:35:56 +0000341 (void)S.ActOnOpenMPDeclareSimdDirective(
342 S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
Alexey Bataevecba70f2016-04-12 11:02:11 +0000343 Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
344 Attr.getRange());
Alexey Bataev2af33e32016-04-07 12:45:37 +0000345}
346
Erich Keanea32910d2017-03-23 18:51:54 +0000347void Sema::InstantiateAttrsForDecl(
348 const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl,
349 Decl *New, LateInstantiatedAttrVec *LateAttrs,
350 LocalInstantiationScope *OuterMostScope) {
351 if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) {
352 for (const auto *TmplAttr : Tmpl->attrs()) {
353 // FIXME: If any of the special case versions from InstantiateAttrs become
354 // applicable to template declaration, we'll need to add them here.
355 CXXThisScopeRAII ThisScope(
356 *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()),
Mikael Nilsson9d2872d2018-12-13 10:15:27 +0000357 Qualifiers(), ND->isCXXInstanceMember());
Erich Keanea32910d2017-03-23 18:51:54 +0000358
359 Attr *NewAttr = sema::instantiateTemplateAttributeForDecl(
360 TmplAttr, Context, *this, TemplateArgs);
Richard Smith33bddbd2018-01-04 23:42:29 +0000361 if (NewAttr)
Erich Keanea32910d2017-03-23 18:51:54 +0000362 New->addAttr(NewAttr);
363 }
364 }
365}
366
George Karpenkov1657f362018-11-30 02:18:37 +0000367static Sema::RetainOwnershipKind
368attrToRetainOwnershipKind(const Attr *A) {
369 switch (A->getKind()) {
370 case clang::attr::CFConsumed:
371 return Sema::RetainOwnershipKind::CF;
372 case clang::attr::OSConsumed:
373 return Sema::RetainOwnershipKind::OS;
374 case clang::attr::NSConsumed:
375 return Sema::RetainOwnershipKind::NS;
376 default:
377 llvm_unreachable("Wrong argument supplied");
378 }
379}
380
John McCall6602bb12010-08-01 02:01:53 +0000381void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000382 const Decl *Tmpl, Decl *New,
383 LateInstantiatedAttrVec *LateAttrs,
384 LocalInstantiationScope *OuterMostScope) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000385 for (const auto *TmplAttr : Tmpl->attrs()) {
Chandler Carruthf40c42f2010-06-25 03:22:07 +0000386 // FIXME: This should be generalized to more than just the AlignedAttr.
Richard Smith44c247f2013-02-22 08:32:16 +0000387 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
388 if (Aligned && Aligned->isAlignmentDependent()) {
389 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
390 continue;
Chandler Carruthf40c42f2010-06-25 03:22:07 +0000391 }
392
Hal Finkelee90a222014-09-26 05:04:30 +0000393 const AssumeAlignedAttr *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr);
394 if (AssumeAligned) {
395 instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
396 continue;
397 }
398
Hal Finkel1b0d24e2014-10-02 21:21:25 +0000399 const AlignValueAttr *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr);
400 if (AlignValue) {
401 instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
402 continue;
403 }
404
Erich Keane623efd82017-03-30 21:48:55 +0000405 if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) {
406 instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New);
407 continue;
408 }
409
410
George Burgess IV00431952016-11-17 01:33:54 +0000411 if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000412 instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
George Burgess IV177399e2017-01-09 04:12:14 +0000413 cast<FunctionDecl>(New));
414 continue;
415 }
416
417 if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) {
418 instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl,
419 cast<FunctionDecl>(New));
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000420 continue;
421 }
422
Artem Belevich7093e402015-04-21 22:55:54 +0000423 if (const CUDALaunchBoundsAttr *CUDALaunchBounds =
424 dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
425 instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs,
426 *CUDALaunchBounds, New);
427 continue;
428 }
429
Denis Zobnind9e2dcd2016-02-02 13:50:39 +0000430 if (const ModeAttr *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
431 instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
432 continue;
433 }
434
Alexey Bataev2af33e32016-04-07 12:45:37 +0000435 if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
436 instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
437 continue;
438 }
439
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +0000440 // Existing DLL attribute on the instantiation takes precedence.
441 if (TmplAttr->getKind() == attr::DLLExport ||
442 TmplAttr->getKind() == attr::DLLImport) {
443 if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
444 continue;
445 }
446 }
447
John McCall477f2bb2016-03-03 06:39:32 +0000448 if (auto ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
449 AddParameterABIAttr(ABIAttr->getRange(), New, ABIAttr->getABI(),
450 ABIAttr->getSpellingListIndex());
451 continue;
452 }
453
George Karpenkov1657f362018-11-30 02:18:37 +0000454 if (isa<NSConsumedAttr>(TmplAttr) || isa<OSConsumedAttr>(TmplAttr) ||
455 isa<CFConsumedAttr>(TmplAttr)) {
456 AddXConsumedAttr(New, TmplAttr->getRange(),
457 TmplAttr->getSpellingListIndex(),
458 attrToRetainOwnershipKind(TmplAttr),
459 /*template instantiation=*/true);
John McCall3b5a8f52016-03-03 00:10:03 +0000460 continue;
461 }
462
Richard Smith44c247f2013-02-22 08:32:16 +0000463 assert(!TmplAttr->isPackExpansion());
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000464 if (TmplAttr->isLateParsed() && LateAttrs) {
465 // Late parsed attributes must be instantiated and attached after the
466 // enclosing class has been instantiated. See Sema::InstantiateClass.
Craig Topperc3ec1492014-05-26 06:22:03 +0000467 LocalInstantiationScope *Saved = nullptr;
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000468 if (CurrentInstantiationScope)
469 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
470 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
471 } else {
Richard Smithc3d2ebb2013-06-07 02:33:37 +0000472 // Allow 'this' within late-parsed attributes.
473 NamedDecl *ND = dyn_cast<NamedDecl>(New);
474 CXXRecordDecl *ThisContext =
475 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
Mikael Nilsson9d2872d2018-12-13 10:15:27 +0000476 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
Richard Smithc3d2ebb2013-06-07 02:33:37 +0000477 ND && ND->isCXXInstanceMember());
478
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +0000479 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
480 *this, TemplateArgs);
Richard Smith33bddbd2018-01-04 23:42:29 +0000481 if (NewAttr)
Rafael Espindola7f90b7d2012-05-15 14:09:55 +0000482 New->addAttr(NewAttr);
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000483 }
Anders Carlsson3d709752009-11-07 06:07:58 +0000484 }
485}
486
Richard Smith41c79d92014-10-11 00:37:16 +0000487/// Get the previous declaration of a declaration for the purposes of template
488/// instantiation. If this finds a previous declaration, then the previous
489/// declaration of the instantiation of D should be an instantiation of the
490/// result of this function.
491template<typename DeclT>
492static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
493 DeclT *Result = D->getPreviousDecl();
494
495 // If the declaration is within a class, and the previous declaration was
496 // merged from a different definition of that class, then we don't have a
497 // previous declaration for the purpose of template instantiation.
498 if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
499 D->getLexicalDeclContext() != Result->getLexicalDeclContext())
500 return nullptr;
501
502 return Result;
503}
504
Douglas Gregor8a655532009-03-25 15:45:12 +0000505Decl *
506TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000507 llvm_unreachable("Translation units cannot be instantiated");
Douglas Gregor8a655532009-03-25 15:45:12 +0000508}
509
510Decl *
Nico Weber66220292016-03-02 17:28:48 +0000511TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
512 llvm_unreachable("pragma comment cannot be instantiated");
513}
514
Nico Webercbbaeb12016-03-02 19:28:54 +0000515Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
516 PragmaDetectMismatchDecl *D) {
517 llvm_unreachable("pragma comment cannot be instantiated");
518}
519
Nico Weber66220292016-03-02 17:28:48 +0000520Decl *
Richard Smithf19e1272015-03-07 00:04:49 +0000521TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
522 llvm_unreachable("extern \"C\" context cannot be instantiated");
523}
524
525Decl *
Chris Lattnercab02a62011-02-17 20:34:02 +0000526TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
527 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
528 D->getIdentifier());
529 Owner->addDecl(Inst);
530 return Inst;
531}
532
533Decl *
Douglas Gregor8a655532009-03-25 15:45:12 +0000534TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000535 llvm_unreachable("Namespaces cannot be instantiated");
Douglas Gregor8a655532009-03-25 15:45:12 +0000536}
537
John McCalld8d0d432010-02-16 06:53:13 +0000538Decl *
539TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
540 NamespaceAliasDecl *Inst
541 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
542 D->getNamespaceLoc(),
543 D->getAliasLoc(),
Douglas Gregorc05ba2e2011-02-25 17:08:07 +0000544 D->getIdentifier(),
545 D->getQualifierLoc(),
John McCalld8d0d432010-02-16 06:53:13 +0000546 D->getTargetNameLoc(),
547 D->getNamespace());
548 Owner->addDecl(Inst);
549 return Inst;
550}
551
Richard Smith3f1b5d02011-05-05 21:57:07 +0000552Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
553 bool IsTypeAlias) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000554 bool Invalid = false;
John McCallbcd03502009-12-07 02:54:59 +0000555 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor678d76c2011-07-01 01:22:09 +0000556 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor5a5073e2010-05-24 17:22:01 +0000557 DI->getType()->isVariablyModifiedType()) {
John McCall703a3f82009-10-24 08:00:42 +0000558 DI = SemaRef.SubstType(DI, TemplateArgs,
559 D->getLocation(), D->getDeclName());
560 if (!DI) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000561 Invalid = true;
John McCallbcd03502009-12-07 02:54:59 +0000562 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000563 }
Douglas Gregor5597ab42010-05-07 23:12:07 +0000564 } else {
565 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000566 }
Mike Stump11289f42009-09-09 15:08:12 +0000567
Richard Smith2ddcbab2012-10-23 00:32:41 +0000568 // HACK: g++ has a bug where it gets the value kind of ?: wrong.
569 // libstdc++ relies upon this bug in its implementation of common_type.
570 // If we happen to be processing that implementation, fake up the g++ ?:
571 // semantics. See LWG issue 2141 for more information on the bug.
572 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
573 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
574 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
575 DT->isReferenceType() &&
576 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
577 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
578 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000579 SemaRef.getSourceManager().isInSystemHeader(D->getBeginLoc()))
Richard Smith2ddcbab2012-10-23 00:32:41 +0000580 // Fold it to the (non-reference) type which g++ would have produced.
581 DI = SemaRef.Context.getTrivialTypeSourceInfo(
582 DI->getType().getNonReferenceType());
583
Douglas Gregord7e7a512009-03-17 21:15:40 +0000584 // Create the new typedef
Richard Smithdda56e42011-04-15 14:24:37 +0000585 TypedefNameDecl *Typedef;
586 if (IsTypeAlias)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000587 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
Richard Smithdda56e42011-04-15 14:24:37 +0000588 D->getLocation(), D->getIdentifier(), DI);
589 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000590 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
Richard Smithdda56e42011-04-15 14:24:37 +0000591 D->getLocation(), D->getIdentifier(), DI);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000592 if (Invalid)
593 Typedef->setInvalidDecl();
594
John McCall04fcd0d2011-02-01 08:20:08 +0000595 // If the old typedef was the name for linkage purposes of an anonymous
596 // tag decl, re-establish that relationship for the new typedef.
597 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
598 TagDecl *oldTag = oldTagType->getDecl();
Douglas Gregord831d952013-03-08 22:15:15 +0000599 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
John McCall04fcd0d2011-02-01 08:20:08 +0000600 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
John McCall5ea95772013-03-09 00:54:27 +0000601 assert(!newTag->hasNameForLinkage());
Richard Smithdda56e42011-04-15 14:24:37 +0000602 newTag->setTypedefNameForAnonDecl(Typedef);
John McCall04fcd0d2011-02-01 08:20:08 +0000603 }
Douglas Gregor83eb5032010-04-23 16:25:07 +0000604 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000605
Richard Smith41c79d92014-10-11 00:37:16 +0000606 if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000607 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
608 TemplateArgs);
Douglas Gregor55e6b312011-03-04 19:46:35 +0000609 if (!InstPrev)
Craig Topperc3ec1492014-05-26 06:22:03 +0000610 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000611
Rafael Espindolacde2c8f2011-12-26 22:42:47 +0000612 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
613
614 // If the typedef types are not identical, reject them.
615 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
616
Rafael Espindola8db352d2013-10-17 15:37:26 +0000617 Typedef->setPreviousDecl(InstPrevTypedef);
John McCall91f1a022009-12-30 00:31:22 +0000618 }
619
John McCall6602bb12010-08-01 02:01:53 +0000620 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
Douglas Gregor83eb5032010-04-23 16:25:07 +0000621
John McCall401982f2010-01-20 21:53:11 +0000622 Typedef->setAccess(D->getAccess());
Mike Stump11289f42009-09-09 15:08:12 +0000623
Douglas Gregord7e7a512009-03-17 21:15:40 +0000624 return Typedef;
625}
626
Richard Smithdda56e42011-04-15 14:24:37 +0000627Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000628 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
Richard Smith41c79d92014-10-11 00:37:16 +0000629 if (Typedef)
630 Owner->addDecl(Typedef);
Richard Smith3f1b5d02011-05-05 21:57:07 +0000631 return Typedef;
Richard Smithdda56e42011-04-15 14:24:37 +0000632}
633
634Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000635 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
Richard Smith41c79d92014-10-11 00:37:16 +0000636 if (Typedef)
637 Owner->addDecl(Typedef);
Richard Smith3f1b5d02011-05-05 21:57:07 +0000638 return Typedef;
639}
640
641Decl *
642TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
643 // Create a local instantiation scope for this type alias template, which
644 // will contain the instantiations of the template parameters.
645 LocalInstantiationScope Scope(SemaRef);
646
647 TemplateParameterList *TempParams = D->getTemplateParameters();
648 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
649 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +0000650 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000651
652 TypeAliasDecl *Pattern = D->getTemplatedDecl();
653
Craig Topperc3ec1492014-05-26 06:22:03 +0000654 TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
Richard Smith41c79d92014-10-11 00:37:16 +0000655 if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000656 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +0000657 if (!Found.empty()) {
658 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
Richard Smith3f1b5d02011-05-05 21:57:07 +0000659 }
660 }
661
662 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
663 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
664 if (!AliasInst)
Craig Topperc3ec1492014-05-26 06:22:03 +0000665 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000666
667 TypeAliasTemplateDecl *Inst
668 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
669 D->getDeclName(), InstParams, AliasInst);
Richard Smith43ccec8e2014-08-26 03:52:16 +0000670 AliasInst->setDescribedAliasTemplate(Inst);
Richard Smith3f1b5d02011-05-05 21:57:07 +0000671 if (PrevAliasTemplate)
Rafael Espindola8db352d2013-10-17 15:37:26 +0000672 Inst->setPreviousDecl(PrevAliasTemplate);
Richard Smith3f1b5d02011-05-05 21:57:07 +0000673
674 Inst->setAccess(D->getAccess());
675
676 if (!PrevAliasTemplate)
677 Inst->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000678
Richard Smith3f1b5d02011-05-05 21:57:07 +0000679 Owner->addDecl(Inst);
680
681 return Inst;
Richard Smithdda56e42011-04-15 14:24:37 +0000682}
683
Richard Smithbdb84f32016-07-22 23:36:59 +0000684Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) {
Richard Smith3997b1b2016-08-12 01:55:21 +0000685 auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(),
686 D->getIdentifier());
Richard Smith81df9eb2017-10-02 22:43:36 +0000687 NewBD->setReferenced(D->isReferenced());
Richard Smith3997b1b2016-08-12 01:55:21 +0000688 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewBD);
689 return NewBD;
Richard Smithbdb84f32016-07-22 23:36:59 +0000690}
691
692Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
Richard Smith3997b1b2016-08-12 01:55:21 +0000693 // Transform the bindings first.
694 SmallVector<BindingDecl*, 16> NewBindings;
695 for (auto *OldBD : D->bindings())
696 NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD)));
697 ArrayRef<BindingDecl*> NewBindingArray = NewBindings;
698
699 auto *NewDD = cast_or_null<DecompositionDecl>(
700 VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray));
701
702 if (!NewDD || NewDD->isInvalidDecl())
703 for (auto *NewBD : NewBindings)
704 NewBD->setInvalidDecl();
705
706 return NewDD;
Richard Smithbdb84f32016-07-22 23:36:59 +0000707}
708
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000709Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000710 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000711}
712
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000713Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
Richard Smith3997b1b2016-08-12 01:55:21 +0000714 bool InstantiatingVarTemplate,
715 ArrayRef<BindingDecl*> *Bindings) {
Larisse Voufo39a1e502013-08-06 01:03:05 +0000716
John McCall76d824f2009-08-25 22:02:44 +0000717 // Do substitution on the type of the declaration
Richard Smithee579842017-01-30 20:39:26 +0000718 TypeSourceInfo *DI = SemaRef.SubstType(
719 D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(),
720 D->getDeclName(), /*AllowDeducedTST*/true);
John McCallf1abcdc2009-10-21 02:39:02 +0000721 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +0000722 return nullptr;
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000723
Douglas Gregor61623342010-09-12 07:37:24 +0000724 if (DI->getType()->isFunctionType()) {
725 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
726 << D->isStaticDataMember() << DI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +0000727 return nullptr;
Douglas Gregor61623342010-09-12 07:37:24 +0000728 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000729
Richard Smith541b38b2013-09-20 01:15:31 +0000730 DeclContext *DC = Owner;
731 if (D->isLocalExternDecl())
732 SemaRef.adjustContextForLocalExternDecl(DC);
733
Larisse Voufo39a1e502013-08-06 01:03:05 +0000734 // Build the instantiated declaration.
Richard Smith3997b1b2016-08-12 01:55:21 +0000735 VarDecl *Var;
736 if (Bindings)
737 Var = DecompositionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
738 D->getLocation(), DI->getType(), DI,
739 D->getStorageClass(), *Bindings);
740 else
741 Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
742 D->getLocation(), D->getIdentifier(), DI->getType(),
743 DI, D->getStorageClass());
Mike Stump11289f42009-09-09 15:08:12 +0000744
Douglas Gregor8ca0c642011-12-10 01:22:52 +0000745 // In ARC, infer 'retaining' for variables of retainable type.
Fangrui Song6907ce22018-07-30 19:24:48 +0000746 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
Douglas Gregor8ca0c642011-12-10 01:22:52 +0000747 SemaRef.inferObjCARCLifetime(Var))
748 Var->setInvalidDecl();
749
Larisse Voufo39a1e502013-08-06 01:03:05 +0000750 // Substitute the nested name specifier, if any.
751 if (SubstQualifier(D, Var))
Craig Topperc3ec1492014-05-26 06:22:03 +0000752 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000753
Richard Smith541b38b2013-09-20 01:15:31 +0000754 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000755 StartingScope, InstantiatingVarTemplate);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +0000756
757 if (D->isNRVOVariable()) {
758 QualType ReturnType = cast<FunctionDecl>(DC)->getReturnType();
Richard Trieu09c163b2018-03-15 03:00:55 +0000759 if (SemaRef.isCopyElisionCandidate(ReturnType, Var, Sema::CES_Strict))
Taiju Tsuiki3be68e12018-06-19 05:35:30 +0000760 Var->setNRVOVariable(true);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +0000761 }
Taiju Tsuiki3be68e12018-06-19 05:35:30 +0000762
Alexander Kornienko83a4e182014-05-27 21:29:22 +0000763 Var->setImplicit(D->isImplicit());
764
Hans Wennborg262baa42018-10-31 10:34:46 +0000765 if (Var->isStaticLocal())
766 SemaRef.CheckStaticLocalForDllExport(Var);
767
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000768 return Var;
769}
770
Abramo Bagnarad7340582010-06-05 05:09:32 +0000771Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
772 AccessSpecDecl* AD
773 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
774 D->getAccessSpecifierLoc(), D->getColonLoc());
775 Owner->addHiddenDecl(AD);
776 return AD;
777}
778
Douglas Gregord7e7a512009-03-17 21:15:40 +0000779Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
780 bool Invalid = false;
John McCallbcd03502009-12-07 02:54:59 +0000781 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor678d76c2011-07-01 01:22:09 +0000782 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor5a5073e2010-05-24 17:22:01 +0000783 DI->getType()->isVariablyModifiedType()) {
John McCall90459c52009-10-22 23:33:21 +0000784 DI = SemaRef.SubstType(DI, TemplateArgs,
785 D->getLocation(), D->getDeclName());
786 if (!DI) {
John McCallbcd03502009-12-07 02:54:59 +0000787 DI = D->getTypeSourceInfo();
John McCall90459c52009-10-22 23:33:21 +0000788 Invalid = true;
789 } else if (DI->getType()->isFunctionType()) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000790 // C++ [temp.arg.type]p3:
791 // If a declaration acquires a function type through a type
792 // dependent on a template-parameter and this causes a
793 // declaration that does not use the syntactic form of a
794 // function declarator to have function type, the program is
795 // ill-formed.
796 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall90459c52009-10-22 23:33:21 +0000797 << DI->getType();
Douglas Gregord7e7a512009-03-17 21:15:40 +0000798 Invalid = true;
799 }
Douglas Gregor5597ab42010-05-07 23:12:07 +0000800 } else {
801 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000802 }
803
804 Expr *BitWidth = D->getBitWidth();
805 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +0000806 BitWidth = nullptr;
Douglas Gregord7e7a512009-03-17 21:15:40 +0000807 else if (BitWidth) {
Richard Smith764d2fe2011-12-20 02:08:33 +0000808 // The bit-width expression is a constant expression.
Faisal Valid143a0c2017-04-01 21:30:49 +0000809 EnterExpressionEvaluationContext Unevaluated(
810 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000811
John McCalldadc5752010-08-24 06:29:42 +0000812 ExprResult InstantiatedBitWidth
John McCall76d824f2009-08-25 22:02:44 +0000813 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000814 if (InstantiatedBitWidth.isInvalid()) {
815 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +0000816 BitWidth = nullptr;
Douglas Gregord7e7a512009-03-17 21:15:40 +0000817 } else
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000818 BitWidth = InstantiatedBitWidth.getAs<Expr>();
Douglas Gregord7e7a512009-03-17 21:15:40 +0000819 }
820
John McCall90459c52009-10-22 23:33:21 +0000821 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
822 DI->getType(), DI,
Mike Stump11289f42009-09-09 15:08:12 +0000823 cast<RecordDecl>(Owner),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000824 D->getLocation(),
825 D->isMutable(),
826 BitWidth,
Richard Smith2b013182012-06-10 03:12:00 +0000827 D->getInClassInitStyle(),
Richard Smith47ad0172012-05-23 04:22:22 +0000828 D->getInnerLocStart(),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000829 D->getAccess(),
Craig Topperc3ec1492014-05-26 06:22:03 +0000830 nullptr);
Douglas Gregor3c74d412009-10-14 20:14:33 +0000831 if (!Field) {
832 cast<Decl>(Owner)->setInvalidDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +0000833 return nullptr;
Douglas Gregor3c74d412009-10-14 20:14:33 +0000834 }
Mike Stump11289f42009-09-09 15:08:12 +0000835
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000836 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000837
Richard Smith848e1f12013-02-01 08:12:08 +0000838 if (Field->hasAttrs())
839 SemaRef.CheckAlignasUnderalignment(Field);
840
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000841 if (Invalid)
842 Field->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000843
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000844 if (!Field->getDeclName()) {
845 // Keep track of where this decl came from.
846 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000847 }
Douglas Gregor04163182010-05-21 00:31:19 +0000848 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
849 if (Parent->isAnonymousStructOrUnion() &&
Sebastian Redl50c68252010-08-31 00:36:30 +0000850 Parent->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor04163182010-05-21 00:31:19 +0000851 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000852 }
Mike Stump11289f42009-09-09 15:08:12 +0000853
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000854 Field->setImplicit(D->isImplicit());
John McCall401982f2010-01-20 21:53:11 +0000855 Field->setAccess(D->getAccess());
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000856 Owner->addDecl(Field);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000857
858 return Field;
859}
860
John McCall5e77d762013-04-16 07:28:30 +0000861Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
862 bool Invalid = false;
863 TypeSourceInfo *DI = D->getTypeSourceInfo();
864
865 if (DI->getType()->isVariablyModifiedType()) {
866 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
Aaron Ballman1bda4592014-01-03 01:09:27 +0000867 << D;
John McCall5e77d762013-04-16 07:28:30 +0000868 Invalid = true;
869 } else if (DI->getType()->isInstantiationDependentType()) {
870 DI = SemaRef.SubstType(DI, TemplateArgs,
871 D->getLocation(), D->getDeclName());
872 if (!DI) {
873 DI = D->getTypeSourceInfo();
874 Invalid = true;
875 } else if (DI->getType()->isFunctionType()) {
876 // C++ [temp.arg.type]p3:
877 // If a declaration acquires a function type through a type
878 // dependent on a template-parameter and this causes a
879 // declaration that does not use the syntactic form of a
880 // function declarator to have function type, the program is
881 // ill-formed.
882 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
883 << DI->getType();
884 Invalid = true;
885 }
886 } else {
887 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
888 }
889
Richard Smithf7981722013-11-22 09:01:48 +0000890 MSPropertyDecl *Property = MSPropertyDecl::Create(
891 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000892 DI, D->getBeginLoc(), D->getGetterId(), D->getSetterId());
John McCall5e77d762013-04-16 07:28:30 +0000893
894 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
895 StartingScope);
896
897 if (Invalid)
898 Property->setInvalidDecl();
899
900 Property->setAccess(D->getAccess());
901 Owner->addDecl(Property);
902
903 return Property;
904}
905
Francois Pichet783dd6e2010-11-21 06:08:52 +0000906Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
907 NamedDecl **NamedChain =
908 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
909
910 int i = 0;
Aaron Ballman29c94602014-03-07 18:36:15 +0000911 for (auto *PI : D->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +0000912 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
Douglas Gregor55e6b312011-03-04 19:46:35 +0000913 TemplateArgs);
914 if (!Next)
Craig Topperc3ec1492014-05-26 06:22:03 +0000915 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000916
Douglas Gregor55e6b312011-03-04 19:46:35 +0000917 NamedChain[i++] = Next;
918 }
Francois Pichet783dd6e2010-11-21 06:08:52 +0000919
Francois Pichetdbafc192010-12-09 10:07:54 +0000920 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
Aaron Ballman260995b2014-10-15 16:58:18 +0000921 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
922 SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
David Majnemer59f77922016-06-24 04:05:48 +0000923 {NamedChain, D->getChainingSize()});
Francois Pichet783dd6e2010-11-21 06:08:52 +0000924
NAKAMURA Takumi729be142014-10-27 12:37:26 +0000925 for (const auto *Attr : D->attrs())
926 IndirectField->addAttr(Attr->clone(SemaRef.Context));
Francois Pichet783dd6e2010-11-21 06:08:52 +0000927
928 IndirectField->setImplicit(D->isImplicit());
929 IndirectField->setAccess(D->getAccess());
930 Owner->addDecl(IndirectField);
931 return IndirectField;
932}
933
John McCallaa74a0c2009-08-28 07:59:38 +0000934Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCallaa74a0c2009-08-28 07:59:38 +0000935 // Handle friend type expressions by simply substituting template
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000936 // parameters into the pattern type and checking the result.
John McCall15ad0962010-03-25 18:04:51 +0000937 if (TypeSourceInfo *Ty = D->getFriendType()) {
Chandler Carruth08836322011-05-01 00:51:33 +0000938 TypeSourceInfo *InstTy;
939 // If this is an unsupported friend, don't bother substituting template
940 // arguments into it. The actual type referred to won't be used by any
941 // parts of Clang, and may not be valid for instantiating. Just use the
942 // same info for the instantiated friend.
943 if (D->isUnsupportedFriend()) {
944 InstTy = Ty;
945 } else {
946 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
947 D->getLocation(), DeclarationName());
948 }
949 if (!InstTy)
Craig Topperc3ec1492014-05-26 06:22:03 +0000950 return nullptr;
John McCallaa74a0c2009-08-28 07:59:38 +0000951
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000952 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getBeginLoc(),
Abramo Bagnara254b6302011-10-29 20:52:52 +0000953 D->getFriendLoc(), InstTy);
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000954 if (!FD)
Craig Topperc3ec1492014-05-26 06:22:03 +0000955 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000956
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000957 FD->setAccess(AS_public);
John McCallace48cd2010-10-19 01:40:49 +0000958 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000959 Owner->addDecl(FD);
960 return FD;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000961 }
962
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000963 NamedDecl *ND = D->getFriendDecl();
964 assert(ND && "friend decl must be a decl or a type!");
965
John McCallb9c78482010-04-08 09:05:18 +0000966 // All of the Visit implementations for the various potential friend
967 // declarations have to be carefully written to work for friend
968 // objects, with the most important detail being that the target
969 // decl should almost certainly not be placed in Owner.
970 Decl *NewND = Visit(ND);
Craig Topperc3ec1492014-05-26 06:22:03 +0000971 if (!NewND) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000972
John McCallaa74a0c2009-08-28 07:59:38 +0000973 FriendDecl *FD =
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000974 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000975 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall75c03bb2009-08-29 03:50:18 +0000976 FD->setAccess(AS_public);
John McCallace48cd2010-10-19 01:40:49 +0000977 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCallaa74a0c2009-08-28 07:59:38 +0000978 Owner->addDecl(FD);
979 return FD;
John McCall58de3582009-08-14 02:03:10 +0000980}
981
Douglas Gregord7e7a512009-03-17 21:15:40 +0000982Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
983 Expr *AssertExpr = D->getAssertExpr();
Mike Stump11289f42009-09-09 15:08:12 +0000984
Richard Smith764d2fe2011-12-20 02:08:33 +0000985 // The expression in a static assertion is a constant expression.
Faisal Valid143a0c2017-04-01 21:30:49 +0000986 EnterExpressionEvaluationContext Unevaluated(
987 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000988
John McCalldadc5752010-08-24 06:29:42 +0000989 ExprResult InstantiatedAssertExpr
John McCall76d824f2009-08-25 22:02:44 +0000990 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000991 if (InstantiatedAssertExpr.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +0000992 return nullptr;
Douglas Gregord7e7a512009-03-17 21:15:40 +0000993
Richard Smithded9c2e2012-07-11 22:37:56 +0000994 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
John McCallb268a282010-08-23 23:25:46 +0000995 InstantiatedAssertExpr.get(),
Richard Smithded9c2e2012-07-11 22:37:56 +0000996 D->getMessage(),
997 D->getRParenLoc(),
998 D->isFailed());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000999}
1000
1001Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001002 EnumDecl *PrevDecl = nullptr;
Richard Smith41c79d92014-10-11 00:37:16 +00001003 if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
Richard Smith2e6610a2012-03-26 04:58:10 +00001004 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
Richard Smith41c79d92014-10-11 00:37:16 +00001005 PatternPrev,
Richard Smith2e6610a2012-03-26 04:58:10 +00001006 TemplateArgs);
Craig Topperc3ec1492014-05-26 06:22:03 +00001007 if (!Prev) return nullptr;
Richard Smith2e6610a2012-03-26 04:58:10 +00001008 PrevDecl = cast<EnumDecl>(Prev);
1009 }
1010
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001011 EnumDecl *Enum =
1012 EnumDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1013 D->getLocation(), D->getIdentifier(), PrevDecl,
1014 D->isScoped(), D->isScopedUsingClassTag(), D->isFixed());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001015 if (D->isFixed()) {
Richard Smith4b38ded2012-03-14 23:13:10 +00001016 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00001017 // If we have type source information for the underlying type, it means it
1018 // has been explicitly set by the user. Perform substitution on it before
1019 // moving on.
1020 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
Richard Smith4b38ded2012-03-14 23:13:10 +00001021 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
1022 DeclarationName());
1023 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
Douglas Gregor0bf31402010-10-08 23:50:27 +00001024 Enum->setIntegerType(SemaRef.Context.IntTy);
Richard Smith4b38ded2012-03-14 23:13:10 +00001025 else
1026 Enum->setIntegerTypeSourceInfo(NewTI);
1027 } else {
Douglas Gregor0bf31402010-10-08 23:50:27 +00001028 assert(!D->getIntegerType()->isDependentType()
1029 && "Dependent type without type source info");
1030 Enum->setIntegerType(D->getIntegerType());
1031 }
1032 }
1033
John McCall811a0f52010-10-22 23:36:17 +00001034 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
1035
Richard Smith4b38ded2012-03-14 23:13:10 +00001036 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
Douglas Gregor6c2adff2009-03-25 22:00:53 +00001037 Enum->setAccess(D->getAccess());
David Majnemerdbc0c8f2013-12-04 09:01:55 +00001038 // Forward the mangling number from the template to the instantiated decl.
1039 SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
David Majnemer00350522015-08-31 18:48:39 +00001040 // See if the old tag was defined along with a declarator.
1041 // If it did, mark the new tag as being associated with that declarator.
1042 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1043 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD);
1044 // See if the old tag was defined along with a typedef.
1045 // If it did, mark the new tag as being associated with that typedef.
1046 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1047 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND);
Craig Topperc3ec1492014-05-26 06:22:03 +00001048 if (SubstQualifier(D, Enum)) return nullptr;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001049 Owner->addDecl(Enum);
Richard Smith4b38ded2012-03-14 23:13:10 +00001050
Richard Smith258a7442012-03-26 04:08:46 +00001051 EnumDecl *Def = D->getDefinition();
1052 if (Def && Def != D) {
1053 // If this is an out-of-line definition of an enum member template, check
1054 // that the underlying types match in the instantiation of both
1055 // declarations.
1056 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
1057 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1058 QualType DefnUnderlying =
1059 SemaRef.SubstType(TI->getType(), TemplateArgs,
1060 UnderlyingLoc, DeclarationName());
1061 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
Reid Klecknerb0a17ed2018-02-12 17:37:06 +00001062 DefnUnderlying, /*IsFixed=*/true, Enum);
Richard Smith258a7442012-03-26 04:08:46 +00001063 }
1064 }
Douglas Gregord7e7a512009-03-17 21:15:40 +00001065
Richard Smith4b38ded2012-03-14 23:13:10 +00001066 // C++11 [temp.inst]p1: The implicit instantiation of a class template
1067 // specialization causes the implicit instantiation of the declarations, but
1068 // not the definitions of scoped member enumerations.
David Majnemer192d1792013-11-27 08:20:38 +00001069 //
1070 // DR1484 clarifies that enumeration definitions inside of a template
1071 // declaration aren't considered entities that can be separately instantiated
1072 // from the rest of the entity they are declared inside of.
1073 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
1074 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
Richard Smith258a7442012-03-26 04:08:46 +00001075 InstantiateEnumDefinition(Enum, Def);
David Majnemer192d1792013-11-27 08:20:38 +00001076 }
Richard Smith4b38ded2012-03-14 23:13:10 +00001077
1078 return Enum;
1079}
1080
1081void TemplateDeclInstantiator::InstantiateEnumDefinition(
1082 EnumDecl *Enum, EnumDecl *Pattern) {
1083 Enum->startDefinition();
1084
Richard Smith7d137e32012-03-23 03:33:32 +00001085 // Update the location to refer to the definition.
1086 Enum->setLocation(Pattern->getLocation());
1087
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001088 SmallVector<Decl*, 4> Enumerators;
Douglas Gregord7e7a512009-03-17 21:15:40 +00001089
Craig Topperc3ec1492014-05-26 06:22:03 +00001090 EnumConstantDecl *LastEnumConst = nullptr;
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001091 for (auto *EC : Pattern->enumerators()) {
Douglas Gregord7e7a512009-03-17 21:15:40 +00001092 // The specified value for the enumerator.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001093 ExprResult Value((Expr *)nullptr);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00001094 if (Expr *UninstValue = EC->getInitExpr()) {
Richard Smith764d2fe2011-12-20 02:08:33 +00001095 // The enumerator's value expression is a constant expression.
Faisal Valid143a0c2017-04-01 21:30:49 +00001096 EnterExpressionEvaluationContext Unevaluated(
1097 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +00001098
John McCall76d824f2009-08-25 22:02:44 +00001099 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00001100 }
Douglas Gregord7e7a512009-03-17 21:15:40 +00001101
1102 // Drop the initial value and continue.
1103 bool isInvalid = false;
1104 if (Value.isInvalid()) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001105 Value = nullptr;
Douglas Gregord7e7a512009-03-17 21:15:40 +00001106 isInvalid = true;
1107 }
1108
Mike Stump11289f42009-09-09 15:08:12 +00001109 EnumConstantDecl *EnumConst
Douglas Gregord7e7a512009-03-17 21:15:40 +00001110 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
1111 EC->getLocation(), EC->getIdentifier(),
John McCallb268a282010-08-23 23:25:46 +00001112 Value.get());
Douglas Gregord7e7a512009-03-17 21:15:40 +00001113
1114 if (isInvalid) {
1115 if (EnumConst)
1116 EnumConst->setInvalidDecl();
1117 Enum->setInvalidDecl();
1118 }
1119
1120 if (EnumConst) {
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001121 SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
John McCall811a0f52010-10-22 23:36:17 +00001122
John McCallf9b528c2010-01-23 22:37:59 +00001123 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001124 Enum->addDecl(EnumConst);
John McCall48871652010-08-21 09:40:31 +00001125 Enumerators.push_back(EnumConst);
Douglas Gregord7e7a512009-03-17 21:15:40 +00001126 LastEnumConst = EnumConst;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001127
Richard Smith4b38ded2012-03-14 23:13:10 +00001128 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
1129 !Enum->isScoped()) {
Douglas Gregoraff9c1a2010-03-01 19:00:07 +00001130 // If the enumeration is within a function or method, record the enum
1131 // constant as a local.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001132 SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
Douglas Gregoraff9c1a2010-03-01 19:00:07 +00001133 }
Douglas Gregord7e7a512009-03-17 21:15:40 +00001134 }
1135 }
Mike Stump11289f42009-09-09 15:08:12 +00001136
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00001137 SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
Erich Keanec480f302018-07-12 21:09:05 +00001138 Enumerators, nullptr, ParsedAttributesView());
Douglas Gregord7e7a512009-03-17 21:15:40 +00001139}
1140
Douglas Gregor9106b822009-03-25 15:04:13 +00001141Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +00001142 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
Douglas Gregor9106b822009-03-25 15:04:13 +00001143}
1144
David Majnemerd9b1a4f2015-11-04 03:40:30 +00001145Decl *
1146TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
1147 llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
1148}
1149
John McCall87a44eb2009-08-20 01:44:21 +00001150Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall598b4402010-03-25 06:39:04 +00001151 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1152
Douglas Gregor954de172009-10-31 17:21:17 +00001153 // Create a local instantiation scope for this class template, which
1154 // will contain the instantiations of the template parameters.
John McCall19c1bfd2010-08-25 05:32:35 +00001155 LocalInstantiationScope Scope(SemaRef);
John McCall87a44eb2009-08-20 01:44:21 +00001156 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCall76d824f2009-08-25 22:02:44 +00001157 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump11289f42009-09-09 15:08:12 +00001158 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00001159 return nullptr;
John McCall87a44eb2009-08-20 01:44:21 +00001160
1161 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall598b4402010-03-25 06:39:04 +00001162
1163 // Instantiate the qualifier. We have to do this first in case
1164 // we're a friend declaration, because if we are then we need to put
1165 // the new declaration in the appropriate context.
Douglas Gregor14454802011-02-25 02:25:35 +00001166 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
1167 if (QualifierLoc) {
1168 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1169 TemplateArgs);
1170 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00001171 return nullptr;
John McCall598b4402010-03-25 06:39:04 +00001172 }
1173
Craig Topperc3ec1492014-05-26 06:22:03 +00001174 CXXRecordDecl *PrevDecl = nullptr;
1175 ClassTemplateDecl *PrevClassTemplate = nullptr;
John McCall598b4402010-03-25 06:39:04 +00001176
Richard Smith41c79d92014-10-11 00:37:16 +00001177 if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
Nick Lewycky61478912010-11-08 23:29:42 +00001178 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +00001179 if (!Found.empty()) {
1180 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
Nick Lewycky61478912010-11-08 23:29:42 +00001181 if (PrevClassTemplate)
1182 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1183 }
1184 }
1185
John McCall598b4402010-03-25 06:39:04 +00001186 // If this isn't a friend, then it's a member template, in which
1187 // case we just want to build the instantiation in the
1188 // specialization. If it is a friend, we want to build it in
1189 // the appropriate context.
1190 DeclContext *DC = Owner;
1191 if (isFriend) {
Douglas Gregor14454802011-02-25 02:25:35 +00001192 if (QualifierLoc) {
John McCall598b4402010-03-25 06:39:04 +00001193 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +00001194 SS.Adopt(QualifierLoc);
John McCall598b4402010-03-25 06:39:04 +00001195 DC = SemaRef.computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +00001196 if (!DC) return nullptr;
John McCall598b4402010-03-25 06:39:04 +00001197 } else {
1198 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
1199 Pattern->getDeclContext(),
1200 TemplateArgs);
1201 }
1202
1203 // Look for a previous declaration of the template in the owning
1204 // context.
1205 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
Richard Smithbecb92d2017-10-10 22:33:17 +00001206 Sema::LookupOrdinaryName,
1207 SemaRef.forRedeclarationInCurContext());
John McCall598b4402010-03-25 06:39:04 +00001208 SemaRef.LookupQualifiedName(R, DC);
1209
1210 if (R.isSingleResult()) {
1211 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
1212 if (PrevClassTemplate)
1213 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1214 }
1215
Douglas Gregor14454802011-02-25 02:25:35 +00001216 if (!PrevClassTemplate && QualifierLoc) {
John McCall598b4402010-03-25 06:39:04 +00001217 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregorf5af3582010-03-31 23:17:41 +00001218 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
Douglas Gregor14454802011-02-25 02:25:35 +00001219 << QualifierLoc.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00001220 return nullptr;
John McCall598b4402010-03-25 06:39:04 +00001221 }
1222
Douglas Gregor01e09d92010-04-08 18:16:15 +00001223 bool AdoptedPreviousTemplateParams = false;
John McCall598b4402010-03-25 06:39:04 +00001224 if (PrevClassTemplate) {
Douglas Gregor01e09d92010-04-08 18:16:15 +00001225 bool Complain = true;
1226
1227 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
1228 // template for struct std::tr1::__detail::_Map_base, where the
1229 // template parameters of the friend declaration don't match the
1230 // template parameters of the original declaration. In this one
1231 // case, we don't complain about the ill-formed friend
1232 // declaration.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001233 if (isFriend && Pattern->getIdentifier() &&
Douglas Gregor01e09d92010-04-08 18:16:15 +00001234 Pattern->getIdentifier()->isStr("_Map_base") &&
1235 DC->isNamespace() &&
1236 cast<NamespaceDecl>(DC)->getIdentifier() &&
1237 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
1238 DeclContext *DCParent = DC->getParent();
1239 if (DCParent->isNamespace() &&
1240 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
1241 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
Richard Trieuc771d5d2014-05-28 02:16:01 +00001242 if (cast<Decl>(DCParent)->isInStdNamespace())
Douglas Gregor01e09d92010-04-08 18:16:15 +00001243 Complain = false;
1244 }
1245 }
1246
John McCall598b4402010-03-25 06:39:04 +00001247 TemplateParameterList *PrevParams
Richard Smithc4577662018-09-12 02:13:47 +00001248 = PrevClassTemplate->getMostRecentDecl()->getTemplateParameters();
John McCall598b4402010-03-25 06:39:04 +00001249
1250 // Make sure the parameter lists match.
1251 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001252 Complain,
Douglas Gregor01e09d92010-04-08 18:16:15 +00001253 Sema::TPL_TemplateMatch)) {
1254 if (Complain)
Craig Topperc3ec1492014-05-26 06:22:03 +00001255 return nullptr;
Douglas Gregor01e09d92010-04-08 18:16:15 +00001256
1257 AdoptedPreviousTemplateParams = true;
1258 InstParams = PrevParams;
1259 }
John McCall598b4402010-03-25 06:39:04 +00001260
1261 // Do some additional validation, then merge default arguments
1262 // from the existing declarations.
Douglas Gregor01e09d92010-04-08 18:16:15 +00001263 if (!AdoptedPreviousTemplateParams &&
1264 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall598b4402010-03-25 06:39:04 +00001265 Sema::TPC_ClassTemplate))
Craig Topperc3ec1492014-05-26 06:22:03 +00001266 return nullptr;
John McCall598b4402010-03-25 06:39:04 +00001267 }
1268 }
1269
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001270 CXXRecordDecl *RecordInst = CXXRecordDecl::Create(
1271 SemaRef.Context, Pattern->getTagKind(), DC, Pattern->getBeginLoc(),
1272 Pattern->getLocation(), Pattern->getIdentifier(), PrevDecl,
1273 /*DelayTypeCreation=*/true);
John McCall87a44eb2009-08-20 01:44:21 +00001274
Douglas Gregor14454802011-02-25 02:25:35 +00001275 if (QualifierLoc)
1276 RecordInst->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +00001277
Louis Dionne3c011e12018-09-14 14:07:16 +00001278 SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs,
1279 StartingScope);
1280
John McCall87a44eb2009-08-20 01:44:21 +00001281 ClassTemplateDecl *Inst
John McCall598b4402010-03-25 06:39:04 +00001282 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
Vassil Vassilev352e4412017-01-12 09:16:26 +00001283 D->getIdentifier(), InstParams, RecordInst);
1284 assert(!(isFriend && Owner->isDependentContext()));
1285 Inst->setPreviousDecl(PrevClassTemplate);
1286
John McCall87a44eb2009-08-20 01:44:21 +00001287 RecordInst->setDescribedClassTemplate(Inst);
John McCall17762b82010-04-08 20:25:50 +00001288
John McCall598b4402010-03-25 06:39:04 +00001289 if (isFriend) {
John McCall17762b82010-04-08 20:25:50 +00001290 if (PrevClassTemplate)
1291 Inst->setAccess(PrevClassTemplate->getAccess());
1292 else
1293 Inst->setAccess(D->getAccess());
1294
Richard Smith64017682013-07-17 23:53:16 +00001295 Inst->setObjectOfFriendDecl();
John McCall598b4402010-03-25 06:39:04 +00001296 // TODO: do we want to track the instantiation progeny of this
1297 // friend target decl?
1298 } else {
Douglas Gregor412e8bc2009-10-30 21:07:27 +00001299 Inst->setAccess(D->getAccess());
Nick Lewycky61478912010-11-08 23:29:42 +00001300 if (!PrevClassTemplate)
1301 Inst->setInstantiatedFromMemberTemplate(D);
John McCall598b4402010-03-25 06:39:04 +00001302 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001303
Douglas Gregoref06ccf2009-10-12 23:11:44 +00001304 // Trigger creation of the type for the instantiation.
John McCalle78aac42010-03-10 03:28:59 +00001305 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor9961ce92010-07-08 18:37:38 +00001306 Inst->getInjectedClassNameSpecialization());
John McCall17762b82010-04-08 20:25:50 +00001307
Douglas Gregorbb3b46e2009-10-30 22:42:42 +00001308 // Finish handling of friends.
John McCall598b4402010-03-25 06:39:04 +00001309 if (isFriend) {
Richard Smith05afe5e2012-03-13 03:12:56 +00001310 DC->makeDeclVisibleInContext(Inst);
Abramo Bagnaraedf99ff2011-11-26 13:33:46 +00001311 Inst->setLexicalDeclContext(Owner);
1312 RecordInst->setLexicalDeclContext(Owner);
Douglas Gregor412e8bc2009-10-30 21:07:27 +00001313 return Inst;
Douglas Gregorbb3b46e2009-10-30 22:42:42 +00001314 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001315
Abramo Bagnaraedf99ff2011-11-26 13:33:46 +00001316 if (D->isOutOfLine()) {
1317 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1318 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
1319 }
1320
John McCall87a44eb2009-08-20 01:44:21 +00001321 Owner->addDecl(Inst);
Douglas Gregor869853e2010-11-10 19:44:59 +00001322
1323 if (!PrevClassTemplate) {
1324 // Queue up any out-of-line partial specializations of this member
1325 // class template; the client will force their instantiation once
1326 // the enclosing class has been instantiated.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001327 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregor869853e2010-11-10 19:44:59 +00001328 D->getPartialSpecializations(PartialSpecs);
1329 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
Rafael Espindola8db352d2013-10-17 15:37:26 +00001330 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
Douglas Gregor869853e2010-11-10 19:44:59 +00001331 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
1332 }
1333
John McCall87a44eb2009-08-20 01:44:21 +00001334 return Inst;
1335}
1336
Douglas Gregore704c9d2009-08-27 16:57:43 +00001337Decl *
Douglas Gregore4b05162009-10-07 17:21:34 +00001338TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1339 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregor21610382009-10-29 00:04:11 +00001340 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001341
Douglas Gregor21610382009-10-29 00:04:11 +00001342 // Lookup the already-instantiated declaration in the instantiation
1343 // of the class template and return that.
1344 DeclContext::lookup_result Found
1345 = Owner->lookup(ClassTemplate->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +00001346 if (Found.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +00001347 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001348
Douglas Gregor21610382009-10-29 00:04:11 +00001349 ClassTemplateDecl *InstClassTemplate
David Blaikieff7d47a2012-12-19 00:45:41 +00001350 = dyn_cast<ClassTemplateDecl>(Found.front());
Douglas Gregor21610382009-10-29 00:04:11 +00001351 if (!InstClassTemplate)
Craig Topperc3ec1492014-05-26 06:22:03 +00001352 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001353
Douglas Gregor869853e2010-11-10 19:44:59 +00001354 if (ClassTemplatePartialSpecializationDecl *Result
1355 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1356 return Result;
1357
1358 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregore4b05162009-10-07 17:21:34 +00001359}
1360
Larisse Voufo39a1e502013-08-06 01:03:05 +00001361Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1362 assert(D->getTemplatedDecl()->isStaticDataMember() &&
1363 "Only static data member templates are allowed.");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001364
1365 // Create a local instantiation scope for this variable template, which
1366 // will contain the instantiations of the template parameters.
1367 LocalInstantiationScope Scope(SemaRef);
1368 TemplateParameterList *TempParams = D->getTemplateParameters();
1369 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1370 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00001371 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00001372
1373 VarDecl *Pattern = D->getTemplatedDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00001374 VarTemplateDecl *PrevVarTemplate = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00001375
Richard Smith41c79d92014-10-11 00:37:16 +00001376 if (getPreviousDeclForInstantiation(Pattern)) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00001377 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1378 if (!Found.empty())
1379 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1380 }
1381
Richard Smith1c34fb72013-08-13 18:18:50 +00001382 VarDecl *VarInst =
Larisse Voufo72caf2b2013-08-22 00:59:14 +00001383 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1384 /*InstantiatingVarTemplate=*/true));
Nick Lewycky6ca07ca2015-08-10 21:54:08 +00001385 if (!VarInst) return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00001386
1387 DeclContext *DC = Owner;
1388
Larisse Voufo39a1e502013-08-06 01:03:05 +00001389 VarTemplateDecl *Inst = VarTemplateDecl::Create(
1390 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
Richard Smithbeef3452014-01-16 23:39:20 +00001391 VarInst);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001392 VarInst->setDescribedVarTemplate(Inst);
Richard Smithbeef3452014-01-16 23:39:20 +00001393 Inst->setPreviousDecl(PrevVarTemplate);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001394
1395 Inst->setAccess(D->getAccess());
1396 if (!PrevVarTemplate)
1397 Inst->setInstantiatedFromMemberTemplate(D);
1398
1399 if (D->isOutOfLine()) {
1400 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1401 VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1402 }
1403
1404 Owner->addDecl(Inst);
1405
1406 if (!PrevVarTemplate) {
1407 // Queue up any out-of-line partial specializations of this member
1408 // variable template; the client will force their instantiation once
1409 // the enclosing class has been instantiated.
1410 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1411 D->getPartialSpecializations(PartialSpecs);
1412 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
Rafael Espindola8db352d2013-10-17 15:37:26 +00001413 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
Larisse Voufo39a1e502013-08-06 01:03:05 +00001414 OutOfLineVarPartialSpecs.push_back(
1415 std::make_pair(Inst, PartialSpecs[I]));
1416 }
1417
1418 return Inst;
1419}
1420
1421Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1422 VarTemplatePartialSpecializationDecl *D) {
1423 assert(D->isStaticDataMember() &&
1424 "Only static data member templates are allowed.");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001425
1426 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1427
1428 // Lookup the already-instantiated declaration and return that.
1429 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1430 assert(!Found.empty() && "Instantiation found nothing?");
1431
1432 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1433 assert(InstVarTemplate && "Instantiation did not find a variable template?");
1434
1435 if (VarTemplatePartialSpecializationDecl *Result =
1436 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1437 return Result;
1438
1439 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1440}
1441
Douglas Gregore4b05162009-10-07 17:21:34 +00001442Decl *
Douglas Gregore704c9d2009-08-27 16:57:43 +00001443TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor954de172009-10-31 17:21:17 +00001444 // Create a local instantiation scope for this function template, which
1445 // will contain the instantiations of the template parameters and then get
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001446 // merged with the local instantiation scope for the function template
Douglas Gregor954de172009-10-31 17:21:17 +00001447 // itself.
John McCall19c1bfd2010-08-25 05:32:35 +00001448 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor14cf7522010-04-30 18:55:50 +00001449
Douglas Gregore704c9d2009-08-27 16:57:43 +00001450 TemplateParameterList *TempParams = D->getTemplateParameters();
1451 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump11289f42009-09-09 15:08:12 +00001452 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00001453 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001454
Craig Topperc3ec1492014-05-26 06:22:03 +00001455 FunctionDecl *Instantiated = nullptr;
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001456 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001457 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001458 InstParams));
1459 else
1460 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001461 D->getTemplatedDecl(),
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001462 InstParams));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001463
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001464 if (!Instantiated)
Craig Topperc3ec1492014-05-26 06:22:03 +00001465 return nullptr;
Douglas Gregore704c9d2009-08-27 16:57:43 +00001466
Mike Stump11289f42009-09-09 15:08:12 +00001467 // Link the instantiated function template declaration to the function
Douglas Gregore704c9d2009-08-27 16:57:43 +00001468 // template from which it was instantiated.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001469 FunctionTemplateDecl *InstTemplate
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001470 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregorca027af2009-10-12 22:27:17 +00001471 InstTemplate->setAccess(D->getAccess());
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001472 assert(InstTemplate &&
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001473 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCall2079d0b2009-12-14 23:19:40 +00001474
John McCall30837102010-03-26 23:10:15 +00001475 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1476
John McCall2079d0b2009-12-14 23:19:40 +00001477 // Link the instantiation back to the pattern *unless* this is a
1478 // non-definition friend declaration.
1479 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCall30837102010-03-26 23:10:15 +00001480 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001481 InstTemplate->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001482
John McCall30837102010-03-26 23:10:15 +00001483 // Make declarations visible in the appropriate context.
John McCalla0a96892012-08-10 03:15:35 +00001484 if (!isFriend) {
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001485 Owner->addDecl(InstTemplate);
John McCalla0a96892012-08-10 03:15:35 +00001486 } else if (InstTemplate->getDeclContext()->isRecord() &&
Richard Smith41c79d92014-10-11 00:37:16 +00001487 !getPreviousDeclForInstantiation(D)) {
John McCalla0a96892012-08-10 03:15:35 +00001488 SemaRef.CheckFriendAccess(InstTemplate);
1489 }
John McCall30837102010-03-26 23:10:15 +00001490
Douglas Gregore704c9d2009-08-27 16:57:43 +00001491 return InstTemplate;
1492}
1493
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001494Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001495 CXXRecordDecl *PrevDecl = nullptr;
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001496 if (D->isInjectedClassName())
1497 PrevDecl = cast<CXXRecordDecl>(Owner);
Richard Smith41c79d92014-10-11 00:37:16 +00001498 else if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001499 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
Richard Smith41c79d92014-10-11 00:37:16 +00001500 PatternPrev,
John McCalle9f92a02009-12-15 22:29:06 +00001501 TemplateArgs);
Craig Topperc3ec1492014-05-26 06:22:03 +00001502 if (!Prev) return nullptr;
John McCalle9f92a02009-12-15 22:29:06 +00001503 PrevDecl = cast<CXXRecordDecl>(Prev);
1504 }
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001505
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001506 CXXRecordDecl *Record = CXXRecordDecl::Create(
1507 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
1508 D->getLocation(), D->getIdentifier(), PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00001509
1510 // Substitute the nested name specifier, if any.
1511 if (SubstQualifier(D, Record))
Craig Topperc3ec1492014-05-26 06:22:03 +00001512 return nullptr;
John McCall3e11ebe2010-03-15 10:12:16 +00001513
Louis Dionne3c011e12018-09-14 14:07:16 +00001514 SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs,
1515 StartingScope);
1516
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001517 Record->setImplicit(D->isImplicit());
Eli Friedmanbda4ef12009-08-27 19:11:42 +00001518 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1519 // the tag decls introduced by friend class declarations don't have an access
1520 // specifier. Remove once this area of the code gets sorted out.
1521 if (D->getAccess() != AS_none)
1522 Record->setAccess(D->getAccess());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001523 if (!D->isInjectedClassName())
Douglas Gregorbbe8f462009-10-08 15:14:33 +00001524 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001525
John McCallaa74a0c2009-08-28 07:59:38 +00001526 // If the original function was part of a friend declaration,
1527 // inherit its namespace state.
Richard Smith64017682013-07-17 23:53:16 +00001528 if (D->getFriendObjectKind())
1529 Record->setObjectOfFriendDecl();
John McCallaa74a0c2009-08-28 07:59:38 +00001530
Douglas Gregor04163182010-05-21 00:31:19 +00001531 // Make sure that anonymous structs and unions are recorded.
David Majnemer192d1792013-11-27 08:20:38 +00001532 if (D->isAnonymousStructOrUnion())
Douglas Gregor04163182010-05-21 00:31:19 +00001533 Record->setAnonymousStructOrUnion(true);
David Majnemer192d1792013-11-27 08:20:38 +00001534
1535 if (D->isLocalClass())
1536 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
Anders Carlsson5da84842009-09-01 04:26:58 +00001537
David Majnemerdbc0c8f2013-12-04 09:01:55 +00001538 // Forward the mangling number from the template to the instantiated decl.
1539 SemaRef.Context.setManglingNumber(Record,
1540 SemaRef.Context.getManglingNumber(D));
1541
David Majnemer00350522015-08-31 18:48:39 +00001542 // See if the old tag was defined along with a declarator.
1543 // If it did, mark the new tag as being associated with that declarator.
1544 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1545 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD);
1546
1547 // See if the old tag was defined along with a typedef.
1548 // If it did, mark the new tag as being associated with that typedef.
1549 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1550 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND);
1551
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001552 Owner->addDecl(Record);
David Majnemer192d1792013-11-27 08:20:38 +00001553
1554 // DR1484 clarifies that the members of a local class are instantiated as part
1555 // of the instantiation of their enclosing entity.
1556 if (D->isCompleteDefinition() && D->isLocalClass()) {
Richard Smith4f3e3812017-05-20 01:36:41 +00001557 Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef);
Richard Smithb0b68012015-05-11 23:09:06 +00001558
David Majnemera64cb5a2014-02-22 00:17:46 +00001559 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1560 TSK_ImplicitInstantiation,
1561 /*Complain=*/true);
Richard Smithb0b68012015-05-11 23:09:06 +00001562
Richard Smithece47582017-01-04 23:45:01 +00001563 // For nested local classes, we will instantiate the members when we
1564 // reach the end of the outermost (non-nested) local class.
1565 if (!D->isCXXClassMember())
1566 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1567 TSK_ImplicitInstantiation);
Richard Smithb0b68012015-05-11 23:09:06 +00001568
1569 // This class may have local implicit instantiations that need to be
1570 // performed within this scope.
Richard Smith4f3e3812017-05-20 01:36:41 +00001571 LocalInstantiations.perform();
David Majnemer192d1792013-11-27 08:20:38 +00001572 }
Nico Weber72889432014-09-06 01:25:55 +00001573
1574 SemaRef.DiagnoseUnusedNestedTypedefs(Record);
1575
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001576 return Record;
1577}
1578
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001579/// Adjust the given function type for an instantiation of the
Douglas Gregor89f593a2012-09-13 21:56:43 +00001580/// given declaration, to cope with modifications to the function's type that
1581/// aren't reflected in the type-source information.
1582///
1583/// \param D The declaration we're instantiating.
1584/// \param TInfo The already-instantiated type.
1585static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1586 FunctionDecl *D,
1587 TypeSourceInfo *TInfo) {
Douglas Gregor1af8ad42012-09-13 22:01:49 +00001588 const FunctionProtoType *OrigFunc
1589 = D->getType()->castAs<FunctionProtoType>();
1590 const FunctionProtoType *NewFunc
1591 = TInfo->getType()->castAs<FunctionProtoType>();
1592 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1593 return TInfo->getType();
1594
1595 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1596 NewEPI.ExtInfo = OrigFunc->getExtInfo();
Alp Toker314cc812014-01-25 16:55:45 +00001597 return Context.getFunctionType(NewFunc->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00001598 NewFunc->getParamTypes(), NewEPI);
Douglas Gregor89f593a2012-09-13 21:56:43 +00001599}
1600
John McCallaa74a0c2009-08-28 07:59:38 +00001601/// Normal class members are of more specific types and therefore
Richard Smith4fa145152017-12-21 19:43:39 +00001602/// don't make it here. This function serves three purposes:
John McCallaa74a0c2009-08-28 07:59:38 +00001603/// 1) instantiating function templates
1604/// 2) substituting friend declarations
Richard Smith4fa145152017-12-21 19:43:39 +00001605/// 3) substituting deduction guide declarations for nested class templates
Douglas Gregor33636e62009-12-24 20:56:24 +00001606Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001607 TemplateParameterList *TemplateParams) {
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001608 // Check whether there is already a function template specialization for
1609 // this declaration.
1610 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
John McCall2f88d7d2010-03-27 05:57:59 +00001611 if (FunctionTemplate && !TemplateParams) {
Richard Smith47752e42013-05-03 23:46:09 +00001612 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump11289f42009-09-09 15:08:12 +00001613
Craig Topperc3ec1492014-05-26 06:22:03 +00001614 void *InsertPos = nullptr;
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001615 FunctionDecl *SpecFunc
Craig Topper7e0daca2014-06-26 04:58:53 +00001616 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001617
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001618 // If we already have a function template specialization, return it.
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001619 if (SpecFunc)
1620 return SpecFunc;
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001621 }
Mike Stump11289f42009-09-09 15:08:12 +00001622
John McCall2f88d7d2010-03-27 05:57:59 +00001623 bool isFriend;
1624 if (FunctionTemplate)
1625 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1626 else
1627 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1628
Craig Topperc3ec1492014-05-26 06:22:03 +00001629 bool MergeWithParentScope = (TemplateParams != nullptr) ||
Douglas Gregor9f44d142010-05-21 21:25:08 +00001630 Owner->isFunctionOrMethod() ||
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001631 !(isa<Decl>(Owner) &&
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001632 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall19c1bfd2010-08-25 05:32:35 +00001633 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump11289f42009-09-09 15:08:12 +00001634
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001635 SmallVector<ParmVarDecl *, 4> Params;
David Blaikie4d142962011-11-10 05:42:04 +00001636 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall58f10c32010-03-11 09:03:00 +00001637 if (!TInfo)
Craig Topperc3ec1492014-05-26 06:22:03 +00001638 return nullptr;
Douglas Gregor89f593a2012-09-13 21:56:43 +00001639 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
John McCall58de3582009-08-14 02:03:10 +00001640
Douglas Gregor14454802011-02-25 02:25:35 +00001641 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1642 if (QualifierLoc) {
1643 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1644 TemplateArgs);
1645 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00001646 return nullptr;
John McCalle0b2ddb2010-03-26 04:53:08 +00001647 }
1648
John McCallce410662010-02-06 01:50:47 +00001649 // If we're instantiating a local function declaration, put the result
Richard Smith541b38b2013-09-20 01:15:31 +00001650 // in the enclosing namespace; otherwise we need to find the instantiated
1651 // context.
John McCallce410662010-02-06 01:50:47 +00001652 DeclContext *DC;
Richard Smith541b38b2013-09-20 01:15:31 +00001653 if (D->isLocalExternDecl()) {
John McCallce410662010-02-06 01:50:47 +00001654 DC = Owner;
Richard Smith541b38b2013-09-20 01:15:31 +00001655 SemaRef.adjustContextForLocalExternDecl(DC);
1656 } else if (isFriend && QualifierLoc) {
John McCalle0b2ddb2010-03-26 04:53:08 +00001657 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +00001658 SS.Adopt(QualifierLoc);
John McCalle0b2ddb2010-03-26 04:53:08 +00001659 DC = SemaRef.computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +00001660 if (!DC) return nullptr;
John McCalle0b2ddb2010-03-26 04:53:08 +00001661 } else {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001662 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001663 TemplateArgs);
John McCalle0b2ddb2010-03-26 04:53:08 +00001664 }
John McCallce410662010-02-06 01:50:47 +00001665
Richard Smith4fa145152017-12-21 19:43:39 +00001666 DeclarationNameInfo NameInfo
1667 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1668
Richard Smithbc491202017-02-17 20:05:37 +00001669 FunctionDecl *Function;
Faisal Vali81b756e2017-10-22 14:45:08 +00001670 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
Richard Smithbc491202017-02-17 20:05:37 +00001671 Function = CXXDeductionGuideDecl::Create(
Faisal Vali81b756e2017-10-22 14:45:08 +00001672 SemaRef.Context, DC, D->getInnerLocStart(), DGuide->isExplicit(),
Richard Smith4fa145152017-12-21 19:43:39 +00001673 NameInfo, T, TInfo, D->getSourceRange().getEnd());
Faisal Vali81b756e2017-10-22 14:45:08 +00001674 if (DGuide->isCopyDeductionCandidate())
1675 cast<CXXDeductionGuideDecl>(Function)->setIsCopyDeductionCandidate();
Richard Smithc660c8f2018-03-16 13:36:56 +00001676 Function->setAccess(D->getAccess());
Faisal Vali81b756e2017-10-22 14:45:08 +00001677 } else {
Richard Smithbc491202017-02-17 20:05:37 +00001678 Function = FunctionDecl::Create(
Richard Smith4fa145152017-12-21 19:43:39 +00001679 SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo,
Richard Smithbc491202017-02-17 20:05:37 +00001680 D->getCanonicalDecl()->getStorageClass(), D->isInlineSpecified(),
1681 D->hasWrittenPrototype(), D->isConstexpr());
1682 Function->setRangeEnd(D->getSourceRange().getEnd());
1683 }
John McCall3e11ebe2010-03-15 10:12:16 +00001684
Richard Smithf3814ad2013-01-25 00:08:28 +00001685 if (D->isInlined())
1686 Function->setImplicitlyInline();
1687
Douglas Gregor14454802011-02-25 02:25:35 +00001688 if (QualifierLoc)
1689 Function->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +00001690
Richard Smith541b38b2013-09-20 01:15:31 +00001691 if (D->isLocalExternDecl())
1692 Function->setLocalExternDecl();
1693
John McCall30837102010-03-26 23:10:15 +00001694 DeclContext *LexicalDC = Owner;
Richard Smith541b38b2013-09-20 01:15:31 +00001695 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
John McCall30837102010-03-26 23:10:15 +00001696 assert(D->getDeclContext()->isFileContext());
1697 LexicalDC = D->getDeclContext();
1698 }
1699
1700 Function->setLexicalDeclContext(LexicalDC);
Mike Stump11289f42009-09-09 15:08:12 +00001701
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001702 // Attach the parameters
Reid Klecknera09e44c2013-07-31 21:00:18 +00001703 for (unsigned P = 0; P < Params.size(); ++P)
1704 if (Params[P])
1705 Params[P]->setOwningFunction(Function);
David Blaikie9c70e042011-09-21 18:16:56 +00001706 Function->setParams(Params);
John McCallaa74a0c2009-08-28 07:59:38 +00001707
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001708 if (TemplateParams) {
1709 // Our resulting instantiation is actually a function template, since we
1710 // are substituting only the outer template parameters. For example, given
1711 //
1712 // template<typename T>
1713 // struct X {
1714 // template<typename U> friend void f(T, U);
1715 // };
1716 //
1717 // X<int> x;
1718 //
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001719 // We are instantiating the friend function template "f" within X<int>,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001720 // which means substituting int for T, but leaving "f" as a friend function
1721 // template.
1722 // Build the function template itself.
John McCalle0b2ddb2010-03-26 04:53:08 +00001723 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001724 Function->getLocation(),
1725 Function->getDeclName(),
1726 TemplateParams, Function);
1727 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCall30837102010-03-26 23:10:15 +00001728
1729 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalle0b2ddb2010-03-26 04:53:08 +00001730
1731 if (isFriend && D->isThisDeclarationADefinition()) {
John McCalle0b2ddb2010-03-26 04:53:08 +00001732 FunctionTemplate->setInstantiatedFromMemberTemplate(
1733 D->getDescribedFunctionTemplate());
1734 }
Douglas Gregorffe14e32009-11-14 01:20:54 +00001735 } else if (FunctionTemplate) {
1736 // Record this function template specialization.
Richard Smith47752e42013-05-03 23:46:09 +00001737 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregord5058122010-02-11 01:19:42 +00001738 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001739 TemplateArgumentList::CreateCopy(SemaRef.Context,
David Majnemer8b622692016-07-03 21:17:51 +00001740 Innermost),
Craig Topperc3ec1492014-05-26 06:22:03 +00001741 /*InsertPos=*/nullptr);
Richard Smith152bcd22017-01-28 02:56:07 +00001742 } else if (isFriend && D->isThisDeclarationADefinition()) {
1743 // Do not connect the friend to the template unless it's actually a
1744 // definition. We don't want non-template functions to be marked as being
1745 // template instantiations.
John McCalle0b2ddb2010-03-26 04:53:08 +00001746 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCallaa74a0c2009-08-28 07:59:38 +00001747 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001748
Richard Smith64095fc2019-01-11 01:59:33 +00001749 if (isFriend)
1750 Function->setObjectOfFriendDecl();
1751
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001752 if (InitFunctionInstantiation(Function, D))
1753 Function->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001754
Richard Smith64095fc2019-01-11 01:59:33 +00001755 bool IsExplicitSpecialization = false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001756
Richard Smith541b38b2013-09-20 01:15:31 +00001757 LookupResult Previous(
1758 SemaRef, Function->getDeclName(), SourceLocation(),
1759 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
1760 : Sema::LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00001761 D->isLocalExternDecl() ? Sema::ForExternalRedeclaration
1762 : SemaRef.forRedeclarationInCurContext());
John McCall1f82f242009-11-18 22:49:29 +00001763
John McCallb9c78482010-04-08 09:05:18 +00001764 if (DependentFunctionTemplateSpecializationInfo *Info
1765 = D->getDependentSpecializationInfo()) {
1766 assert(isFriend && "non-friend has dependent specialization info?");
1767
John McCallb9c78482010-04-08 09:05:18 +00001768 // Instantiate the explicit template arguments.
1769 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1770 Info->getRAngleLoc());
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001771 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1772 ExplicitArgs, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00001773 return nullptr;
John McCallb9c78482010-04-08 09:05:18 +00001774
1775 // Map the candidate templates to their instantiations.
1776 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1777 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1778 Info->getTemplate(I),
1779 TemplateArgs);
Craig Topperc3ec1492014-05-26 06:22:03 +00001780 if (!Temp) return nullptr;
John McCallb9c78482010-04-08 09:05:18 +00001781
1782 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1783 }
1784
1785 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1786 &ExplicitArgs,
1787 Previous))
1788 Function->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001789
Richard Smith64095fc2019-01-11 01:59:33 +00001790 IsExplicitSpecialization = true;
1791 } else if (const ASTTemplateArgumentListInfo *Info =
1792 D->getTemplateSpecializationArgsAsWritten()) {
1793 // The name of this function was written as a template-id.
1794 SemaRef.LookupQualifiedName(Previous, DC);
John McCallb9c78482010-04-08 09:05:18 +00001795
Richard Smith64095fc2019-01-11 01:59:33 +00001796 // Instantiate the explicit template arguments.
1797 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1798 Info->getRAngleLoc());
1799 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1800 ExplicitArgs, TemplateArgs))
1801 return nullptr;
1802
1803 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1804 &ExplicitArgs,
1805 Previous))
1806 Function->setInvalidDecl();
1807
1808 IsExplicitSpecialization = true;
John McCallb9c78482010-04-08 09:05:18 +00001809 } else if (TemplateParams || !FunctionTemplate) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001810 // Look only into the namespace where the friend would be declared to
1811 // find a previous declaration. This is the innermost enclosing namespace,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001812 // as described in ActOnFriendFunctionDecl.
John McCall1f82f242009-11-18 22:49:29 +00001813 SemaRef.LookupQualifiedName(Previous, DC);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001814
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001815 // In C++, the previous declaration we find might be a tag type
1816 // (class or enum). In this case, the new declaration will hide the
1817 // tag type. Note that this does does not apply if we're declaring a
1818 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00001819 if (Previous.isSingleTagDecl())
1820 Previous.clear();
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001821 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001822
Craig Topperc3ec1492014-05-26 06:22:03 +00001823 SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
Richard Smith64095fc2019-01-11 01:59:33 +00001824 IsExplicitSpecialization);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001825
John McCallb9467b62010-04-24 01:30:58 +00001826 NamedDecl *PrincipalDecl = (TemplateParams
1827 ? cast<NamedDecl>(FunctionTemplate)
1828 : Function);
1829
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001830 // If the original function was part of a friend declaration,
1831 // inherit its namespace state and add it to the owner.
John McCalle0b2ddb2010-03-26 04:53:08 +00001832 if (isFriend) {
Serge Pavlovacfcd782018-12-06 09:35:04 +00001833 Function->setObjectOfFriendDecl();
1834 if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate())
1835 FT->setObjectOfFriendDecl();
Richard Smith05afe5e2012-03-13 03:12:56 +00001836 DC->makeDeclVisibleInContext(PrincipalDecl);
Gabor Greif718d5152010-08-30 21:10:05 +00001837
Richard Smith91dfaac2014-02-03 02:37:59 +00001838 bool QueuedInstantiation = false;
Gabor Greif718d5152010-08-30 21:10:05 +00001839
Richard Smith91dfaac2014-02-03 02:37:59 +00001840 // C++11 [temp.friend]p4 (DR329):
1841 // When a function is defined in a friend function declaration in a class
1842 // template, the function is instantiated when the function is odr-used.
1843 // The same restrictions on multiple declarations and definitions that
1844 // apply to non-template function declarations and definitions also apply
1845 // to these implicit definitions.
1846 if (D->isThisDeclarationADefinition()) {
Serge Pavlove6e534c2018-03-01 07:04:11 +00001847 SemaRef.CheckForFunctionRedefinition(Function);
1848 if (!Function->isInvalidDecl()) {
1849 for (auto R : Function->redecls()) {
1850 if (R == Function)
1851 continue;
Richard Smith91dfaac2014-02-03 02:37:59 +00001852
Serge Pavlove6e534c2018-03-01 07:04:11 +00001853 // If some prior declaration of this function has been used, we need
1854 // to instantiate its definition.
1855 if (!QueuedInstantiation && R->isUsed(false)) {
1856 if (MemberSpecializationInfo *MSInfo =
1857 Function->getMemberSpecializationInfo()) {
1858 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1859 SourceLocation Loc = R->getLocation(); // FIXME
1860 MSInfo->setPointOfInstantiation(Loc);
1861 SemaRef.PendingLocalImplicitInstantiations.push_back(
1862 std::make_pair(Function, Loc));
1863 QueuedInstantiation = true;
1864 }
Douglas Gregorb92ea592010-05-18 05:45:02 +00001865 }
Richard Smith91dfaac2014-02-03 02:37:59 +00001866 }
Douglas Gregorb92ea592010-05-18 05:45:02 +00001867 }
1868 }
1869 }
Richard Smithf3597652017-05-10 00:01:13 +00001870
1871 // Check the template parameter list against the previous declaration. The
1872 // goal here is to pick up default arguments added since the friend was
1873 // declared; we know the template parameter lists match, since otherwise
1874 // we would not have picked this template as the previous declaration.
1875 if (TemplateParams && FunctionTemplate->getPreviousDecl()) {
1876 SemaRef.CheckTemplateParameterList(
1877 TemplateParams,
1878 FunctionTemplate->getPreviousDecl()->getTemplateParameters(),
1879 Function->isThisDeclarationADefinition()
1880 ? Sema::TPC_FriendFunctionTemplateDefinition
1881 : Sema::TPC_FriendFunctionTemplate);
1882 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001883 }
1884
Richard Smith541b38b2013-09-20 01:15:31 +00001885 if (Function->isLocalExternDecl() && !Function->getPreviousDecl())
1886 DC->makeDeclVisibleInContext(PrincipalDecl);
1887
John McCallb9467b62010-04-24 01:30:58 +00001888 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1889 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1890 PrincipalDecl->setNonMemberOperator();
1891
Alexis Hunt1fb4e762011-05-23 21:07:59 +00001892 assert(!D->isDefaulted() && "only methods should be defaulted");
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001893 return Function;
1894}
1895
Douglas Gregore704c9d2009-08-27 16:57:43 +00001896Decl *
1897TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001898 TemplateParameterList *TemplateParams,
1899 bool IsClassScopeSpecialization) {
Douglas Gregor97628d62009-08-21 00:16:32 +00001900 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
Douglas Gregore704c9d2009-08-27 16:57:43 +00001901 if (FunctionTemplate && !TemplateParams) {
Mike Stump11289f42009-09-09 15:08:12 +00001902 // We are creating a function template specialization from a function
1903 // template. Check whether there is already a function template
Douglas Gregore704c9d2009-08-27 16:57:43 +00001904 // specialization for this particular set of template arguments.
Richard Smith47752e42013-05-03 23:46:09 +00001905 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump11289f42009-09-09 15:08:12 +00001906
Craig Topperc3ec1492014-05-26 06:22:03 +00001907 void *InsertPos = nullptr;
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001908 FunctionDecl *SpecFunc
Craig Topper7e0daca2014-06-26 04:58:53 +00001909 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001910
Douglas Gregor97628d62009-08-21 00:16:32 +00001911 // If we already have a function template specialization, return it.
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001912 if (SpecFunc)
1913 return SpecFunc;
Douglas Gregor97628d62009-08-21 00:16:32 +00001914 }
1915
John McCall2f88d7d2010-03-27 05:57:59 +00001916 bool isFriend;
1917 if (FunctionTemplate)
1918 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1919 else
1920 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1921
Craig Topperc3ec1492014-05-26 06:22:03 +00001922 bool MergeWithParentScope = (TemplateParams != nullptr) ||
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001923 !(isa<Decl>(Owner) &&
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001924 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall19c1bfd2010-08-25 05:32:35 +00001925 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor37256522009-05-14 21:44:34 +00001926
John McCalld0e23ec2010-10-19 02:26:41 +00001927 // Instantiate enclosing template arguments for friends.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001928 SmallVector<TemplateParameterList *, 4> TempParamLists;
John McCalld0e23ec2010-10-19 02:26:41 +00001929 unsigned NumTempParamLists = 0;
1930 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
Benjamin Kramer9dc549b2015-08-04 14:46:06 +00001931 TempParamLists.resize(NumTempParamLists);
John McCalld0e23ec2010-10-19 02:26:41 +00001932 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1933 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1934 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1935 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00001936 return nullptr;
John McCalld0e23ec2010-10-19 02:26:41 +00001937 TempParamLists[I] = InstParams;
1938 }
1939 }
1940
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001941 SmallVector<ParmVarDecl *, 4> Params;
Benjamin Kramer1dd48bc2012-01-20 14:42:32 +00001942 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall58f10c32010-03-11 09:03:00 +00001943 if (!TInfo)
Craig Topperc3ec1492014-05-26 06:22:03 +00001944 return nullptr;
Douglas Gregor89f593a2012-09-13 21:56:43 +00001945 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001946
Douglas Gregor14454802011-02-25 02:25:35 +00001947 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1948 if (QualifierLoc) {
1949 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
John McCall2f88d7d2010-03-27 05:57:59 +00001950 TemplateArgs);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001951 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00001952 return nullptr;
John McCall2f88d7d2010-03-27 05:57:59 +00001953 }
1954
1955 DeclContext *DC = Owner;
1956 if (isFriend) {
Douglas Gregor14454802011-02-25 02:25:35 +00001957 if (QualifierLoc) {
John McCall2f88d7d2010-03-27 05:57:59 +00001958 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +00001959 SS.Adopt(QualifierLoc);
John McCall2f88d7d2010-03-27 05:57:59 +00001960 DC = SemaRef.computeDeclContext(SS);
John McCall1a1b53e2010-10-19 05:01:53 +00001961
1962 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
Craig Topperc3ec1492014-05-26 06:22:03 +00001963 return nullptr;
John McCall2f88d7d2010-03-27 05:57:59 +00001964 } else {
1965 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1966 D->getDeclContext(),
1967 TemplateArgs);
1968 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001969 if (!DC) return nullptr;
John McCall2f88d7d2010-03-27 05:57:59 +00001970 }
1971
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001972 // Build the instantiated method declaration.
John McCall2f88d7d2010-03-27 05:57:59 +00001973 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Craig Topperc3ec1492014-05-26 06:22:03 +00001974 CXXMethodDecl *Method = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001975
Abramo Bagnaradff19302011-03-08 08:55:46 +00001976 SourceLocation StartLoc = D->getInnerLocStart();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001977 DeclarationNameInfo NameInfo
1978 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregore8394862009-08-21 22:43:28 +00001979 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00001980 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001981 StartLoc, NameInfo, T, TInfo,
Mike Stump11289f42009-09-09 15:08:12 +00001982 Constructor->isExplicit(),
Reid Kleckner0f764e52015-04-07 20:46:51 +00001983 Constructor->isInlineSpecified(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001984 false, Constructor->isConstexpr());
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001985 Method->setRangeEnd(Constructor->getEndLoc());
Douglas Gregore8394862009-08-21 22:43:28 +00001986 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregore8394862009-08-21 22:43:28 +00001987 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001988 StartLoc, NameInfo, T, TInfo,
Reid Kleckner0f764e52015-04-07 20:46:51 +00001989 Destructor->isInlineSpecified(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00001990 false);
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001991 Method->setRangeEnd(Destructor->getEndLoc());
Douglas Gregor05155d82009-08-21 23:19:43 +00001992 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001993 Method = CXXConversionDecl::Create(
1994 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
1995 Conversion->isInlineSpecified(), Conversion->isExplicit(),
1996 Conversion->isConstexpr(), Conversion->getEndLoc());
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001997 } else {
Rafael Espindola29cda592013-04-15 12:38:20 +00001998 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001999 Method = CXXMethodDecl::Create(SemaRef.Context, Record, StartLoc, NameInfo,
2000 T, TInfo, SC, D->isInlineSpecified(),
2001 D->isConstexpr(), D->getEndLoc());
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002002 }
Douglas Gregor97628d62009-08-21 00:16:32 +00002003
Richard Smithf3814ad2013-01-25 00:08:28 +00002004 if (D->isInlined())
2005 Method->setImplicitlyInline();
2006
Douglas Gregor14454802011-02-25 02:25:35 +00002007 if (QualifierLoc)
2008 Method->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +00002009
Douglas Gregore704c9d2009-08-27 16:57:43 +00002010 if (TemplateParams) {
2011 // Our resulting instantiation is actually a function template, since we
2012 // are substituting only the outer template parameters. For example, given
Mike Stump11289f42009-09-09 15:08:12 +00002013 //
Douglas Gregore704c9d2009-08-27 16:57:43 +00002014 // template<typename T>
2015 // struct X {
2016 // template<typename U> void f(T, U);
2017 // };
2018 //
2019 // X<int> x;
2020 //
2021 // We are instantiating the member template "f" within X<int>, which means
2022 // substituting int for T, but leaving "f" as a member function template.
2023 // Build the function template itself.
2024 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
2025 Method->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002026 Method->getDeclName(),
Douglas Gregore704c9d2009-08-27 16:57:43 +00002027 TemplateParams, Method);
John McCall2f88d7d2010-03-27 05:57:59 +00002028 if (isFriend) {
2029 FunctionTemplate->setLexicalDeclContext(Owner);
Richard Smith64017682013-07-17 23:53:16 +00002030 FunctionTemplate->setObjectOfFriendDecl();
John McCall2f88d7d2010-03-27 05:57:59 +00002031 } else if (D->isOutOfLine())
Mike Stump11289f42009-09-09 15:08:12 +00002032 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregore704c9d2009-08-27 16:57:43 +00002033 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002034 } else if (FunctionTemplate) {
2035 // Record this function template specialization.
Richard Smith47752e42013-05-03 23:46:09 +00002036 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregord5058122010-02-11 01:19:42 +00002037 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002038 TemplateArgumentList::CreateCopy(SemaRef.Context,
David Majnemer8b622692016-07-03 21:17:51 +00002039 Innermost),
Craig Topperc3ec1492014-05-26 06:22:03 +00002040 /*InsertPos=*/nullptr);
John McCall2f88d7d2010-03-27 05:57:59 +00002041 } else if (!isFriend) {
Douglas Gregorffe14e32009-11-14 01:20:54 +00002042 // Record that this is an instantiation of a member function.
Douglas Gregord801b062009-10-07 23:56:10 +00002043 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002044 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002045
Mike Stump11289f42009-09-09 15:08:12 +00002046 // If we are instantiating a member function defined
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002047 // out-of-line, the instantiation will have the same lexical
2048 // context (which will be a namespace scope) as the template.
John McCall2f88d7d2010-03-27 05:57:59 +00002049 if (isFriend) {
John McCalld0e23ec2010-10-19 02:26:41 +00002050 if (NumTempParamLists)
Benjamin Kramer9cc210652015-08-05 09:40:49 +00002051 Method->setTemplateParameterListsInfo(
2052 SemaRef.Context,
2053 llvm::makeArrayRef(TempParamLists.data(), NumTempParamLists));
John McCalld0e23ec2010-10-19 02:26:41 +00002054
John McCall2f88d7d2010-03-27 05:57:59 +00002055 Method->setLexicalDeclContext(Owner);
Richard Smith64017682013-07-17 23:53:16 +00002056 Method->setObjectOfFriendDecl();
John McCall2f88d7d2010-03-27 05:57:59 +00002057 } else if (D->isOutOfLine())
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002058 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +00002059
Douglas Gregor21342092009-03-24 00:38:23 +00002060 // Attach the parameters
2061 for (unsigned P = 0; P < Params.size(); ++P)
2062 Params[P]->setOwningFunction(Method);
David Blaikie9c70e042011-09-21 18:16:56 +00002063 Method->setParams(Params);
Douglas Gregor21342092009-03-24 00:38:23 +00002064
2065 if (InitMethodInstantiation(Method, D))
2066 Method->setInvalidDecl();
Douglas Gregorf4f296d2009-03-23 23:06:20 +00002067
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002068 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00002069 Sema::ForExternalRedeclaration);
Mike Stump11289f42009-09-09 15:08:12 +00002070
Richard Smith64095fc2019-01-11 01:59:33 +00002071 bool IsExplicitSpecialization = false;
2072
2073 // If the name of this function was written as a template-id, instantiate
2074 // the explicit template arguments.
2075 if (DependentFunctionTemplateSpecializationInfo *Info
2076 = D->getDependentSpecializationInfo()) {
2077 assert(isFriend && "non-friend has dependent specialization info?");
2078
2079 // Instantiate the explicit template arguments.
2080 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2081 Info->getRAngleLoc());
2082 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
2083 ExplicitArgs, TemplateArgs))
2084 return nullptr;
2085
2086 // Map the candidate templates to their instantiations.
2087 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
2088 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
2089 Info->getTemplate(I),
2090 TemplateArgs);
2091 if (!Temp) return nullptr;
2092
2093 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
2094 }
2095
2096 if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2097 &ExplicitArgs,
2098 Previous))
2099 Method->setInvalidDecl();
2100
2101 IsExplicitSpecialization = true;
2102 } else if (const ASTTemplateArgumentListInfo *Info =
2103 D->getTemplateSpecializationArgsAsWritten()) {
2104 SemaRef.LookupQualifiedName(Previous, DC);
2105
2106 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2107 Info->getRAngleLoc());
2108 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
2109 ExplicitArgs, TemplateArgs))
2110 return nullptr;
2111
2112 if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2113 &ExplicitArgs,
2114 Previous))
2115 Method->setInvalidDecl();
2116
2117 IsExplicitSpecialization = true;
2118 } else if (!FunctionTemplate || TemplateParams || isFriend) {
John McCall2f88d7d2010-03-27 05:57:59 +00002119 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump11289f42009-09-09 15:08:12 +00002120
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002121 // In C++, the previous declaration we find might be a tag type
2122 // (class or enum). In this case, the new declaration will hide the
2123 // tag type. Note that this does does not apply if we're declaring a
2124 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00002125 if (Previous.isSingleTagDecl())
2126 Previous.clear();
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002127 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00002128
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002129 if (!IsClassScopeSpecialization)
Richard Smith64095fc2019-01-11 01:59:33 +00002130 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous,
2131 IsExplicitSpecialization);
Douglas Gregor05155d82009-08-21 23:19:43 +00002132
Douglas Gregor21920e372009-12-01 17:24:26 +00002133 if (D->isPure())
2134 SemaRef.CheckPureMethod(Method, SourceRange());
2135
John McCalla0a96892012-08-10 03:15:35 +00002136 // Propagate access. For a non-friend declaration, the access is
2137 // whatever we're propagating from. For a friend, it should be the
2138 // previous declaration we just found.
2139 if (isFriend && Method->getPreviousDecl())
2140 Method->setAccess(Method->getPreviousDecl()->getAccess());
Fangrui Song6907ce22018-07-30 19:24:48 +00002141 else
John McCalla0a96892012-08-10 03:15:35 +00002142 Method->setAccess(D->getAccess());
2143 if (FunctionTemplate)
2144 FunctionTemplate->setAccess(Method->getAccess());
John McCall401982f2010-01-20 21:53:11 +00002145
Anders Carlsson7c812f52011-01-20 06:52:44 +00002146 SemaRef.CheckOverrideControl(Method);
2147
Eli Friedman41340732011-11-15 22:39:08 +00002148 // If a function is defined as defaulted or deleted, mark it as such now.
Richard Smith92f241f2012-12-08 02:53:02 +00002149 if (D->isExplicitlyDefaulted())
2150 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
Eli Friedman41340732011-11-15 22:39:08 +00002151 if (D->isDeletedAsWritten())
Richard Smith92f241f2012-12-08 02:53:02 +00002152 SemaRef.SetDeclDeleted(Method, Method->getLocation());
Eli Friedman41340732011-11-15 22:39:08 +00002153
John McCalla0a96892012-08-10 03:15:35 +00002154 // If there's a function template, let our caller handle it.
John McCall2f88d7d2010-03-27 05:57:59 +00002155 if (FunctionTemplate) {
John McCalla0a96892012-08-10 03:15:35 +00002156 // do nothing
2157
2158 // Don't hide a (potentially) valid declaration with an invalid one.
John McCall2f88d7d2010-03-27 05:57:59 +00002159 } else if (Method->isInvalidDecl() && !Previous.empty()) {
John McCalla0a96892012-08-10 03:15:35 +00002160 // do nothing
2161
2162 // Otherwise, check access to friends and make them visible.
2163 } else if (isFriend) {
2164 // We only need to re-check access for methods which we didn't
2165 // manage to match during parsing.
2166 if (!D->getPreviousDecl())
2167 SemaRef.CheckFriendAccess(Method);
2168
2169 Record->makeDeclVisibleInContext(Method);
2170
2171 // Otherwise, add the declaration. We don't need to do this for
2172 // class-scope specializations because we'll have matched them with
2173 // the appropriate template.
2174 } else if (!IsClassScopeSpecialization) {
2175 Owner->addDecl(Method);
John McCall2f88d7d2010-03-27 05:57:59 +00002176 }
Alexis Hunt1fb4e762011-05-23 21:07:59 +00002177
Douglas Gregorf4f296d2009-03-23 23:06:20 +00002178 return Method;
2179}
2180
Douglas Gregor4044d992009-03-24 16:43:20 +00002181Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002182 return VisitCXXMethodDecl(D);
Douglas Gregor4044d992009-03-24 16:43:20 +00002183}
2184
Douglas Gregor654b07e2009-03-24 00:15:49 +00002185Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregore8394862009-08-21 22:43:28 +00002186 return VisitCXXMethodDecl(D);
Douglas Gregor654b07e2009-03-24 00:15:49 +00002187}
2188
Douglas Gregor1880ba52009-03-25 00:34:44 +00002189Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002190 return VisitCXXMethodDecl(D);
Douglas Gregor1880ba52009-03-25 00:34:44 +00002191}
2192
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002193Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
David Blaikie7a30dc52013-02-21 01:47:18 +00002194 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
2195 /*ExpectParameterPack=*/ false);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00002196}
2197
John McCall87a44eb2009-08-20 01:44:21 +00002198Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
2199 TemplateTypeParmDecl *D) {
2200 // TODO: don't always clone when decls are refcounted.
Chandler Carruth08836322011-05-01 00:51:33 +00002201 assert(D->getTypeForDecl()->isTemplateTypeParmType());
Mike Stump11289f42009-09-09 15:08:12 +00002202
Richard Smithb4f96252017-02-21 06:30:38 +00002203 TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002204 SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(),
Richard Smithb4f96252017-02-21 06:30:38 +00002205 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
2206 D->getIdentifier(), D->wasDeclaredWithTypename(), D->isParameterPack());
Douglas Gregorfd7c2252011-03-04 17:52:15 +00002207 Inst->setAccess(AS_public);
John McCall87a44eb2009-08-20 01:44:21 +00002208
Richard Smith52933792015-06-16 21:57:05 +00002209 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
David Majnemer89189202013-08-28 23:48:32 +00002210 TypeSourceInfo *InstantiatedDefaultArg =
2211 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
2212 D->getDefaultArgumentLoc(), D->getDeclName());
2213 if (InstantiatedDefaultArg)
Richard Smith1469b912015-06-10 00:29:03 +00002214 Inst->setDefaultArgument(InstantiatedDefaultArg);
David Majnemer89189202013-08-28 23:48:32 +00002215 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002216
2217 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor954de172009-10-31 17:21:17 +00002218 // scope.
2219 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002220
John McCall87a44eb2009-08-20 01:44:21 +00002221 return Inst;
2222}
2223
Douglas Gregor6b815c82009-10-23 23:25:44 +00002224Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
2225 NonTypeTemplateParmDecl *D) {
2226 // Substitute into the type of the non-type template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002227 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002228 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
2229 SmallVector<QualType, 4> ExpandedParameterPackTypes;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002230 bool IsExpandedParameterPack = false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002231 TypeSourceInfo *DI;
Douglas Gregor6b815c82009-10-23 23:25:44 +00002232 QualType T;
Douglas Gregor6b815c82009-10-23 23:25:44 +00002233 bool Invalid = false;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002234
2235 if (D->isExpandedParameterPack()) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002236 // The non-type template parameter pack is an already-expanded pack
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002237 // expansion of types. Substitute into each of the expanded types.
2238 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
2239 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
2240 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
Richard Smith15361a22016-12-28 06:27:18 +00002241 TypeSourceInfo *NewDI =
2242 SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
2243 D->getLocation(), D->getDeclName());
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002244 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00002245 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002246
Richard Smith15361a22016-12-28 06:27:18 +00002247 QualType NewT =
2248 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002249 if (NewT.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00002250 return nullptr;
Richard Smith15361a22016-12-28 06:27:18 +00002251
2252 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002253 ExpandedParameterPackTypes.push_back(NewT);
2254 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002255
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002256 IsExpandedParameterPack = true;
2257 DI = D->getTypeSourceInfo();
2258 T = DI->getType();
Richard Smith1fde8ec2012-09-07 02:06:42 +00002259 } else if (D->isPackExpansion()) {
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002260 // The non-type template parameter pack's type is a pack expansion of types.
2261 // Determine whether we need to expand this parameter pack into separate
2262 // types.
David Blaikie6adc78e2013-02-18 22:06:02 +00002263 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002264 TypeLoc Pattern = Expansion.getPatternLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002265 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002266 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002267
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002268 // Determine whether the set of unexpanded parameter packs can and should
2269 // be expanded.
2270 bool Expand = true;
2271 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00002272 Optional<unsigned> OrigNumExpansions
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002273 = Expansion.getTypePtr()->getNumExpansions();
David Blaikie05785d12013-02-20 22:23:23 +00002274 Optional<unsigned> NumExpansions = OrigNumExpansions;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002275 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
2276 Pattern.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00002277 Unexpanded,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002278 TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002279 Expand, RetainExpansion,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002280 NumExpansions))
Craig Topperc3ec1492014-05-26 06:22:03 +00002281 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002282
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002283 if (Expand) {
2284 for (unsigned I = 0; I != *NumExpansions; ++I) {
2285 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2286 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002287 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002288 D->getDeclName());
2289 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00002290 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002291
Richard Smith15361a22016-12-28 06:27:18 +00002292 QualType NewT =
2293 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002294 if (NewT.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00002295 return nullptr;
Richard Smith15361a22016-12-28 06:27:18 +00002296
2297 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002298 ExpandedParameterPackTypes.push_back(NewT);
2299 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002300
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002301 // Note that we have an expanded parameter pack. The "type" of this
2302 // expanded parameter pack is the original expansion type, but callers
2303 // will end up using the expanded parameter pack types for type-checking.
2304 IsExpandedParameterPack = true;
2305 DI = D->getTypeSourceInfo();
2306 T = DI->getType();
2307 } else {
2308 // We cannot fully expand the pack expansion now, so substitute into the
2309 // pattern and create a new pack expansion type.
2310 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2311 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002312 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002313 D->getDeclName());
2314 if (!NewPattern)
Craig Topperc3ec1492014-05-26 06:22:03 +00002315 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002316
Richard Smith15361a22016-12-28 06:27:18 +00002317 SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002318 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
2319 NumExpansions);
2320 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00002321 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002322
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002323 T = DI->getType();
2324 }
2325 } else {
2326 // Simple case: substitution into a parameter that is not a parameter pack.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002327 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002328 D->getLocation(), D->getDeclName());
2329 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00002330 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002331
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002332 // Check that this type is acceptable for a non-type template parameter.
Richard Smith15361a22016-12-28 06:27:18 +00002333 T = SemaRef.CheckNonTypeTemplateParameterType(DI, D->getLocation());
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002334 if (T.isNull()) {
2335 T = SemaRef.Context.IntTy;
2336 Invalid = true;
2337 }
Douglas Gregor6b815c82009-10-23 23:25:44 +00002338 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002339
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002340 NonTypeTemplateParmDecl *Param;
2341 if (IsExpandedParameterPack)
David Majnemerdfecf1a2016-07-06 04:19:16 +00002342 Param = NonTypeTemplateParmDecl::Create(
2343 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
Richard Smithb4f96252017-02-21 06:30:38 +00002344 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2345 D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
David Majnemerdfecf1a2016-07-06 04:19:16 +00002346 ExpandedParameterPackTypesAsWritten);
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002347 else
Richard Smithb4f96252017-02-21 06:30:38 +00002348 Param = NonTypeTemplateParmDecl::Create(
2349 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2350 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2351 D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002352
Douglas Gregorfd7c2252011-03-04 17:52:15 +00002353 Param->setAccess(AS_public);
Douglas Gregor6b815c82009-10-23 23:25:44 +00002354 if (Invalid)
2355 Param->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002356
Richard Smith52933792015-06-16 21:57:05 +00002357 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
Faisal Valid143a0c2017-04-01 21:30:49 +00002358 EnterExpressionEvaluationContext ConstantEvaluated(
2359 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00002360 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
2361 if (!Value.isInvalid())
Richard Smith1469b912015-06-10 00:29:03 +00002362 Param->setDefaultArgument(Value.get());
David Majnemer89189202013-08-28 23:48:32 +00002363 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002364
2365 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor954de172009-10-31 17:21:17 +00002366 // scope.
2367 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor6b815c82009-10-23 23:25:44 +00002368 return Param;
2369}
2370
Richard Smith1fde8ec2012-09-07 02:06:42 +00002371static void collectUnexpandedParameterPacks(
2372 Sema &S,
2373 TemplateParameterList *Params,
2374 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
Davide Italiano18960b92015-07-02 19:20:11 +00002375 for (const auto &P : *Params) {
2376 if (P->isTemplateParameterPack())
Richard Smith1fde8ec2012-09-07 02:06:42 +00002377 continue;
Davide Italiano18960b92015-07-02 19:20:11 +00002378 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
Richard Smith1fde8ec2012-09-07 02:06:42 +00002379 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
2380 Unexpanded);
Davide Italiano18960b92015-07-02 19:20:11 +00002381 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
Richard Smith1fde8ec2012-09-07 02:06:42 +00002382 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
2383 Unexpanded);
2384 }
2385}
2386
Anders Carlsson4bd78752009-08-28 15:18:15 +00002387Decl *
Douglas Gregor38fee962009-11-11 16:58:32 +00002388TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
2389 TemplateTemplateParmDecl *D) {
2390 // Instantiate the template parameter list of the template template parameter.
2391 TemplateParameterList *TempParams = D->getTemplateParameters();
2392 TemplateParameterList *InstParams;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002393 SmallVector<TemplateParameterList*, 8> ExpandedParams;
2394
2395 bool IsExpandedParameterPack = false;
2396
2397 if (D->isExpandedParameterPack()) {
2398 // The template template parameter pack is an already-expanded pack
2399 // expansion of template parameters. Substitute into each of the expanded
2400 // parameters.
2401 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
2402 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2403 I != N; ++I) {
2404 LocalInstantiationScope Scope(SemaRef);
2405 TemplateParameterList *Expansion =
2406 SubstTemplateParams(D->getExpansionTemplateParameters(I));
2407 if (!Expansion)
Craig Topperc3ec1492014-05-26 06:22:03 +00002408 return nullptr;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002409 ExpandedParams.push_back(Expansion);
2410 }
2411
2412 IsExpandedParameterPack = true;
2413 InstParams = TempParams;
2414 } else if (D->isPackExpansion()) {
2415 // The template template parameter pack expands to a pack of template
2416 // template parameters. Determine whether we need to expand this parameter
2417 // pack into separate parameters.
2418 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2419 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
2420 Unexpanded);
2421
2422 // Determine whether the set of unexpanded parameter packs can and should
2423 // be expanded.
2424 bool Expand = true;
2425 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00002426 Optional<unsigned> NumExpansions;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002427 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
2428 TempParams->getSourceRange(),
2429 Unexpanded,
2430 TemplateArgs,
2431 Expand, RetainExpansion,
2432 NumExpansions))
Craig Topperc3ec1492014-05-26 06:22:03 +00002433 return nullptr;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002434
2435 if (Expand) {
2436 for (unsigned I = 0; I != *NumExpansions; ++I) {
2437 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2438 LocalInstantiationScope Scope(SemaRef);
2439 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
2440 if (!Expansion)
Craig Topperc3ec1492014-05-26 06:22:03 +00002441 return nullptr;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002442 ExpandedParams.push_back(Expansion);
2443 }
2444
2445 // Note that we have an expanded parameter pack. The "type" of this
2446 // expanded parameter pack is the original expansion type, but callers
2447 // will end up using the expanded parameter pack types for type-checking.
2448 IsExpandedParameterPack = true;
2449 InstParams = TempParams;
2450 } else {
2451 // We cannot fully expand the pack expansion now, so just substitute
2452 // into the pattern.
2453 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2454
2455 LocalInstantiationScope Scope(SemaRef);
2456 InstParams = SubstTemplateParams(TempParams);
2457 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00002458 return nullptr;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002459 }
2460 } else {
Douglas Gregor38fee962009-11-11 16:58:32 +00002461 // Perform the actual substitution of template parameters within a new,
2462 // local instantiation scope.
John McCall19c1bfd2010-08-25 05:32:35 +00002463 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor38fee962009-11-11 16:58:32 +00002464 InstParams = SubstTemplateParams(TempParams);
2465 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00002466 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002467 }
2468
Douglas Gregor38fee962009-11-11 16:58:32 +00002469 // Build the template template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002470 TemplateTemplateParmDecl *Param;
2471 if (IsExpandedParameterPack)
Richard Smithb4f96252017-02-21 06:30:38 +00002472 Param = TemplateTemplateParmDecl::Create(
2473 SemaRef.Context, Owner, D->getLocation(),
2474 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2475 D->getPosition(), D->getIdentifier(), InstParams, ExpandedParams);
Richard Smith1fde8ec2012-09-07 02:06:42 +00002476 else
Richard Smithb4f96252017-02-21 06:30:38 +00002477 Param = TemplateTemplateParmDecl::Create(
2478 SemaRef.Context, Owner, D->getLocation(),
2479 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2480 D->getPosition(), D->isParameterPack(), D->getIdentifier(), InstParams);
Richard Smith52933792015-06-16 21:57:05 +00002481 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
David Majnemer89189202013-08-28 23:48:32 +00002482 NestedNameSpecifierLoc QualifierLoc =
2483 D->getDefaultArgument().getTemplateQualifierLoc();
2484 QualifierLoc =
2485 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
2486 TemplateName TName = SemaRef.SubstTemplateName(
2487 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
2488 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
2489 if (!TName.isNull())
2490 Param->setDefaultArgument(
Richard Smith1469b912015-06-10 00:29:03 +00002491 SemaRef.Context,
David Majnemer89189202013-08-28 23:48:32 +00002492 TemplateArgumentLoc(TemplateArgument(TName),
2493 D->getDefaultArgument().getTemplateQualifierLoc(),
Richard Smith1469b912015-06-10 00:29:03 +00002494 D->getDefaultArgument().getTemplateNameLoc()));
David Majnemer89189202013-08-28 23:48:32 +00002495 }
Douglas Gregorfd7c2252011-03-04 17:52:15 +00002496 Param->setAccess(AS_public);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002497
2498 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor38fee962009-11-11 16:58:32 +00002499 // scope.
2500 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002501
Douglas Gregor38fee962009-11-11 16:58:32 +00002502 return Param;
2503}
2504
Douglas Gregore0b28662009-11-17 06:07:40 +00002505Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregor12441b32011-02-25 16:33:46 +00002506 // Using directives are never dependent (and never contain any types or
2507 // expressions), so they require no explicit instantiation work.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002508
Douglas Gregore0b28662009-11-17 06:07:40 +00002509 UsingDirectiveDecl *Inst
2510 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002511 D->getNamespaceKeyLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00002512 D->getQualifierLoc(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002513 D->getIdentLocation(),
2514 D->getNominatedNamespace(),
Douglas Gregore0b28662009-11-17 06:07:40 +00002515 D->getCommonAncestor());
Abramo Bagnara8843f9f2012-09-05 09:55:10 +00002516
2517 // Add the using directive to its declaration context
2518 // only if this is not a function or method.
2519 if (!Owner->isFunctionOrMethod())
2520 Owner->addDecl(Inst);
2521
Douglas Gregore0b28662009-11-17 06:07:40 +00002522 return Inst;
2523}
2524
John McCallb96ec562009-12-04 22:46:56 +00002525Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorac2e4302010-09-29 17:58:28 +00002526
2527 // The nested name specifier may be dependent, for example
2528 // template <typename T> struct t {
2529 // struct s1 { T f1(); };
2530 // struct s2 : s1 { using s1::f1; };
2531 // };
2532 // template struct t<int>;
2533 // Here, in using s1::f1, s1 refers to t<T>::s1;
2534 // we need to substitute for t<int>::s1.
Douglas Gregor0499ab62011-02-25 15:54:31 +00002535 NestedNameSpecifierLoc QualifierLoc
2536 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2537 TemplateArgs);
2538 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00002539 return nullptr;
Douglas Gregorac2e4302010-09-29 17:58:28 +00002540
Richard Smith5179eb72016-06-28 19:03:57 +00002541 // For an inheriting constructor declaration, the name of the using
2542 // declaration is the name of a constructor in this class, not in the
2543 // base class.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002544 DeclarationNameInfo NameInfo = D->getNameInfo();
Richard Smith5179eb72016-06-28 19:03:57 +00002545 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
2546 if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
2547 NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName(
2548 SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
John McCallb96ec562009-12-04 22:46:56 +00002549
John McCall84d87672009-12-10 09:41:52 +00002550 // We only need to do redeclaration lookups if we're in a class
2551 // scope (in fact, it's not really even possible in non-class
2552 // scopes).
2553 bool CheckRedeclaration = Owner->isRecord();
2554
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002555 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
Richard Smithbecb92d2017-10-10 22:33:17 +00002556 Sema::ForVisibleRedeclaration);
John McCall84d87672009-12-10 09:41:52 +00002557
John McCallb96ec562009-12-04 22:46:56 +00002558 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002559 D->getUsingLoc(),
Douglas Gregor0499ab62011-02-25 15:54:31 +00002560 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002561 NameInfo,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002562 D->hasTypename());
John McCallb96ec562009-12-04 22:46:56 +00002563
Douglas Gregor0499ab62011-02-25 15:54:31 +00002564 CXXScopeSpec SS;
2565 SS.Adopt(QualifierLoc);
John McCall84d87672009-12-10 09:41:52 +00002566 if (CheckRedeclaration) {
2567 Prev.setHideTags(false);
2568 SemaRef.LookupQualifiedName(Prev, Owner);
2569
2570 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002571 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
2572 D->hasTypename(), SS,
John McCall84d87672009-12-10 09:41:52 +00002573 D->getLocation(), Prev))
2574 NewUD->setInvalidDecl();
2575
2576 }
2577
2578 if (!NewUD->isInvalidDecl() &&
Richard Smithd8a9e372016-12-18 21:39:37 +00002579 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(),
2580 SS, NameInfo, D->getLocation()))
John McCallb96ec562009-12-04 22:46:56 +00002581 NewUD->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00002582
John McCallb96ec562009-12-04 22:46:56 +00002583 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2584 NewUD->setAccess(D->getAccess());
2585 Owner->addDecl(NewUD);
2586
John McCall84d87672009-12-10 09:41:52 +00002587 // Don't process the shadow decls for an invalid decl.
2588 if (NewUD->isInvalidDecl())
2589 return NewUD;
2590
Richard Smith5179eb72016-06-28 19:03:57 +00002591 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
Richard Smith09d5b3a2014-05-01 00:35:04 +00002592 SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
Richard Smith23d55872012-04-02 01:30:27 +00002593
John McCalla1d85502009-12-22 22:26:37 +00002594 bool isFunctionScope = Owner->isFunctionOrMethod();
2595
John McCall84d87672009-12-10 09:41:52 +00002596 // Process the shadow decls.
Aaron Ballman91cdc282014-03-13 18:07:29 +00002597 for (auto *Shadow : D->shadows()) {
Richard Smith5179eb72016-06-28 19:03:57 +00002598 // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
2599 // reconstruct it in the case where it matters.
2600 NamedDecl *OldTarget = Shadow->getTargetDecl();
2601 if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
2602 if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
2603 OldTarget = BaseShadow;
2604
John McCall84d87672009-12-10 09:41:52 +00002605 NamedDecl *InstTarget =
Richard Smithfd8634a2013-10-23 02:17:46 +00002606 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
Richard Smith5179eb72016-06-28 19:03:57 +00002607 Shadow->getLocation(), OldTarget, TemplateArgs));
Douglas Gregor55e6b312011-03-04 19:46:35 +00002608 if (!InstTarget)
Craig Topperc3ec1492014-05-26 06:22:03 +00002609 return nullptr;
John McCall84d87672009-12-10 09:41:52 +00002610
Craig Topperc3ec1492014-05-26 06:22:03 +00002611 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00002612 if (CheckRedeclaration) {
2613 if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl))
2614 continue;
Richard Smith41c79d92014-10-11 00:37:16 +00002615 } else if (UsingShadowDecl *OldPrev =
2616 getPreviousDeclForInstantiation(Shadow)) {
Richard Smithfd8634a2013-10-23 02:17:46 +00002617 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
2618 Shadow->getLocation(), OldPrev, TemplateArgs));
2619 }
John McCall84d87672009-12-10 09:41:52 +00002620
Richard Smithfd8634a2013-10-23 02:17:46 +00002621 UsingShadowDecl *InstShadow =
Craig Topperc3ec1492014-05-26 06:22:03 +00002622 SemaRef.BuildUsingShadowDecl(/*Scope*/nullptr, NewUD, InstTarget,
2623 PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00002624 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCalla1d85502009-12-22 22:26:37 +00002625
2626 if (isFunctionScope)
2627 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall84d87672009-12-10 09:41:52 +00002628 }
John McCallb96ec562009-12-04 22:46:56 +00002629
2630 return NewUD;
2631}
2632
2633Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall84d87672009-12-10 09:41:52 +00002634 // Ignore these; we handle them in bulk when processing the UsingDecl.
Craig Topperc3ec1492014-05-26 06:22:03 +00002635 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00002636}
2637
Richard Smith5179eb72016-06-28 19:03:57 +00002638Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
2639 ConstructorUsingShadowDecl *D) {
2640 // Ignore these; we handle them in bulk when processing the UsingDecl.
2641 return nullptr;
2642}
2643
Richard Smith151c4562016-12-20 21:35:28 +00002644template <typename T>
2645Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
2646 T *D, bool InstantiatingPackElement) {
2647 // If this is a pack expansion, expand it now.
2648 if (D->isPackExpansion() && !InstantiatingPackElement) {
2649 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2650 SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
2651 SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
2652
2653 // Determine whether the set of unexpanded parameter packs can and should
2654 // be expanded.
2655 bool Expand = true;
2656 bool RetainExpansion = false;
2657 Optional<unsigned> NumExpansions;
2658 if (SemaRef.CheckParameterPacksForExpansion(
2659 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
2660 Expand, RetainExpansion, NumExpansions))
2661 return nullptr;
2662
2663 // This declaration cannot appear within a function template signature,
2664 // so we can't have a partial argument list for a parameter pack.
2665 assert(!RetainExpansion &&
2666 "should never need to retain an expansion for UsingPackDecl");
2667
2668 if (!Expand) {
2669 // We cannot fully expand the pack expansion now, so substitute into the
2670 // pattern and create a new pack expansion.
2671 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2672 return instantiateUnresolvedUsingDecl(D, true);
2673 }
2674
2675 // Within a function, we don't have any normal way to check for conflicts
2676 // between shadow declarations from different using declarations in the
2677 // same pack expansion, but this is always ill-formed because all expansions
2678 // must produce (conflicting) enumerators.
2679 //
2680 // Sadly we can't just reject this in the template definition because it
2681 // could be valid if the pack is empty or has exactly one expansion.
2682 if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) {
2683 SemaRef.Diag(D->getEllipsisLoc(),
2684 diag::err_using_decl_redeclaration_expansion);
2685 return nullptr;
2686 }
2687
2688 // Instantiate the slices of this pack and build a UsingPackDecl.
2689 SmallVector<NamedDecl*, 8> Expansions;
2690 for (unsigned I = 0; I != *NumExpansions; ++I) {
2691 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2692 Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
2693 if (!Slice)
2694 return nullptr;
2695 // Note that we can still get unresolved using declarations here, if we
2696 // had arguments for all packs but the pattern also contained other
2697 // template arguments (this only happens during partial substitution, eg
2698 // into the body of a generic lambda in a function template).
2699 Expansions.push_back(cast<NamedDecl>(Slice));
2700 }
2701
2702 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
2703 if (isDeclWithinFunction(D))
2704 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
2705 return NewD;
2706 }
2707
2708 UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
2709 SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation();
2710
Douglas Gregor0499ab62011-02-25 15:54:31 +00002711 NestedNameSpecifierLoc QualifierLoc
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002712 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
Douglas Gregor0499ab62011-02-25 15:54:31 +00002713 TemplateArgs);
2714 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00002715 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002716
Anders Carlsson4bd78752009-08-28 15:18:15 +00002717 CXXScopeSpec SS;
Douglas Gregor0499ab62011-02-25 15:54:31 +00002718 SS.Adopt(QualifierLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002719
Daniel Jasper9949ead2016-12-19 10:09:25 +00002720 DeclarationNameInfo NameInfo
2721 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2722
Richard Smith151c4562016-12-20 21:35:28 +00002723 // Produce a pack expansion only if we're not instantiating a particular
2724 // slice of a pack expansion.
2725 bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
2726 SemaRef.ArgumentPackSubstitutionIndex != -1;
2727 SourceLocation EllipsisLoc =
2728 InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc();
2729
2730 NamedDecl *UD = SemaRef.BuildUsingDeclaration(
2731 /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
Erich Keanec480f302018-07-12 21:09:05 +00002732 /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
2733 ParsedAttributesView(),
Richard Smith151c4562016-12-20 21:35:28 +00002734 /*IsInstantiation*/ true);
Daniel Jasper9949ead2016-12-19 10:09:25 +00002735 if (UD)
2736 SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
2737
2738 return UD;
Richard Smith22a250c2016-12-19 04:08:53 +00002739}
2740
Richard Smith151c4562016-12-20 21:35:28 +00002741Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
2742 UnresolvedUsingTypenameDecl *D) {
2743 return instantiateUnresolvedUsingDecl(D);
2744}
2745
2746Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
2747 UnresolvedUsingValueDecl *D) {
2748 return instantiateUnresolvedUsingDecl(D);
2749}
2750
2751Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
2752 SmallVector<NamedDecl*, 8> Expansions;
2753 for (auto *UD : D->expansions()) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00002754 if (NamedDecl *NewUD =
Richard Smith151c4562016-12-20 21:35:28 +00002755 SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
George Burgess IV00f70bd2018-03-01 05:43:23 +00002756 Expansions.push_back(NewUD);
Richard Smith151c4562016-12-20 21:35:28 +00002757 else
2758 return nullptr;
2759 }
2760
2761 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
2762 if (isDeclWithinFunction(D))
2763 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
2764 return NewD;
2765}
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002766
2767Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
Richard Smith6e671422018-12-04 22:26:32 +00002768 ClassScopeFunctionSpecializationDecl *Decl) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002769 CXXMethodDecl *OldFD = Decl->getSpecialization();
Nick Lewycky0b727732015-01-02 01:33:12 +00002770 CXXMethodDecl *NewFD =
2771 cast_or_null<CXXMethodDecl>(VisitCXXMethodDecl(OldFD, nullptr, true));
2772 if (!NewFD)
2773 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002774
Richard Smith6e671422018-12-04 22:26:32 +00002775 TemplateArgumentListInfo ExplicitTemplateArgs;
2776 TemplateArgumentListInfo *ExplicitTemplateArgsPtr = nullptr;
Nico Weber7b5a7162012-06-25 17:21:05 +00002777 if (Decl->hasExplicitTemplateArgs()) {
Richard Smith6e671422018-12-04 22:26:32 +00002778 if (SemaRef.Subst(Decl->templateArgs().getArgumentArray(),
2779 Decl->templateArgs().size(), ExplicitTemplateArgs,
2780 TemplateArgs))
2781 return nullptr;
2782 ExplicitTemplateArgsPtr = &ExplicitTemplateArgs;
Nico Weber7b5a7162012-06-25 17:21:05 +00002783 }
2784
Richard Smith6e671422018-12-04 22:26:32 +00002785 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
2786 Sema::ForExternalRedeclaration);
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002787 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
Richard Smith6e671422018-12-04 22:26:32 +00002788 if (SemaRef.CheckFunctionTemplateSpecialization(
2789 NewFD, ExplicitTemplateArgsPtr, Previous)) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002790 NewFD->setInvalidDecl();
2791 return NewFD;
2792 }
2793
2794 // Associate the specialization with the pattern.
2795 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2796 assert(Specialization && "Class scope Specialization is null");
2797 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2798
Richard Smithc660c8f2018-03-16 13:36:56 +00002799 // FIXME: If this is a definition, check for redefinition errors!
2800
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002801 return NewFD;
2802}
2803
Alexey Bataeva769e072013-03-22 06:34:35 +00002804Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2805 OMPThreadPrivateDecl *D) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002806 SmallVector<Expr *, 5> Vars;
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002807 for (auto *I : D->varlists()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002808 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
Alexey Bataeva769e072013-03-22 06:34:35 +00002809 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002810 Vars.push_back(Var);
Alexey Bataeva769e072013-03-22 06:34:35 +00002811 }
2812
2813 OMPThreadPrivateDecl *TD =
2814 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2815
Alexey Bataevd3db6ac2014-03-07 09:46:29 +00002816 TD->setAccess(AS_public);
2817 Owner->addDecl(TD);
2818
Alexey Bataeva769e072013-03-22 06:34:35 +00002819 return TD;
2820}
2821
Kelvin Li1408f912018-09-26 04:28:39 +00002822Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
2823 llvm_unreachable(
2824 "Requires directive cannot be instantiated within a dependent context");
2825}
2826
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002827Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
2828 OMPDeclareReductionDecl *D) {
2829 // Instantiate type and check if it is allowed.
Alexey Bataeve6aa4692018-09-13 16:54:05 +00002830 const bool RequiresInstantiation =
2831 D->getType()->isDependentType() ||
2832 D->getType()->isInstantiationDependentType() ||
2833 D->getType()->containsUnexpandedParameterPack();
2834 QualType SubstReductionType;
2835 if (RequiresInstantiation) {
2836 SubstReductionType = SemaRef.ActOnOpenMPDeclareReductionType(
2837 D->getLocation(),
2838 ParsedType::make(SemaRef.SubstType(
2839 D->getType(), TemplateArgs, D->getLocation(), DeclarationName())));
2840 } else {
2841 SubstReductionType = D->getType();
2842 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002843 if (SubstReductionType.isNull())
2844 return nullptr;
2845 bool IsCorrect = !SubstReductionType.isNull();
2846 // Create instantiated copy.
2847 std::pair<QualType, SourceLocation> ReductionTypes[] = {
2848 std::make_pair(SubstReductionType, D->getLocation())};
2849 auto *PrevDeclInScope = D->getPrevDeclInScope();
2850 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
2851 PrevDeclInScope = cast<OMPDeclareReductionDecl>(
2852 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
2853 ->get<Decl *>());
2854 }
2855 auto DRD = SemaRef.ActOnOpenMPDeclareReductionDirectiveStart(
2856 /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
2857 PrevDeclInScope);
2858 auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
Alexey Bataeve6aa4692018-09-13 16:54:05 +00002859 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
2860 if (!RequiresInstantiation) {
2861 if (Expr *Combiner = D->getCombiner()) {
2862 NewDRD->setCombinerData(D->getCombinerIn(), D->getCombinerOut());
2863 NewDRD->setCombiner(Combiner);
2864 if (Expr *Init = D->getInitializer()) {
2865 NewDRD->setInitializerData(D->getInitOrig(), D->getInitPriv());
2866 NewDRD->setInitializer(Init, D->getInitializerKind());
2867 }
2868 }
2869 (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(
2870 /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl());
2871 return NewDRD;
2872 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002873 Expr *SubstCombiner = nullptr;
2874 Expr *SubstInitializer = nullptr;
2875 // Combiners instantiation sequence.
2876 if (D->getCombiner()) {
2877 SemaRef.ActOnOpenMPDeclareReductionCombinerStart(
2878 /*S=*/nullptr, NewDRD);
Alexey Bataeve6aa4692018-09-13 16:54:05 +00002879 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
2880 cast<DeclRefExpr>(D->getCombinerIn())->getDecl(),
2881 cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl());
2882 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
2883 cast<DeclRefExpr>(D->getCombinerOut())->getDecl(),
2884 cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl());
2885 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00002886 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
Alexey Bataeve6aa4692018-09-13 16:54:05 +00002887 ThisContext);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002888 SubstCombiner = SemaRef.SubstExpr(D->getCombiner(), TemplateArgs).get();
2889 SemaRef.ActOnOpenMPDeclareReductionCombinerEnd(NewDRD, SubstCombiner);
2890 // Initializers instantiation sequence.
2891 if (D->getInitializer()) {
Alexey Bataev070f43a2017-09-06 14:49:58 +00002892 VarDecl *OmpPrivParm =
2893 SemaRef.ActOnOpenMPDeclareReductionInitializerStart(
2894 /*S=*/nullptr, NewDRD);
Alexey Bataeve6aa4692018-09-13 16:54:05 +00002895 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
2896 cast<DeclRefExpr>(D->getInitOrig())->getDecl(),
2897 cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl());
2898 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
2899 cast<DeclRefExpr>(D->getInitPriv())->getDecl(),
2900 cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl());
Alexey Bataev070f43a2017-09-06 14:49:58 +00002901 if (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit) {
2902 SubstInitializer =
2903 SemaRef.SubstExpr(D->getInitializer(), TemplateArgs).get();
2904 } else {
2905 IsCorrect = IsCorrect && OmpPrivParm->hasInit();
2906 }
2907 SemaRef.ActOnOpenMPDeclareReductionInitializerEnd(
2908 NewDRD, SubstInitializer, OmpPrivParm);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002909 }
Alexey Bataev070f43a2017-09-06 14:49:58 +00002910 IsCorrect =
2911 IsCorrect && SubstCombiner &&
2912 (!D->getInitializer() ||
2913 (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit &&
2914 SubstInitializer) ||
2915 (D->getInitializerKind() != OMPDeclareReductionDecl::CallInit &&
2916 !SubstInitializer && !SubstInitializer));
Alexey Bataeve6aa4692018-09-13 16:54:05 +00002917 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002918 IsCorrect = false;
Alexey Bataeve6aa4692018-09-13 16:54:05 +00002919 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002920
2921 (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(/*S=*/nullptr, DRD,
2922 IsCorrect);
2923
2924 return NewDRD;
2925}
2926
Michael Kruse251e1482019-02-01 20:25:04 +00002927Decl *
2928TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
2929 // Instantiate type and check if it is allowed.
2930 const bool RequiresInstantiation =
2931 D->getType()->isDependentType() ||
2932 D->getType()->isInstantiationDependentType() ||
2933 D->getType()->containsUnexpandedParameterPack();
2934 QualType SubstMapperTy;
2935 DeclarationName VN = D->getVarName();
2936 if (RequiresInstantiation) {
2937 SubstMapperTy = SemaRef.ActOnOpenMPDeclareMapperType(
2938 D->getLocation(),
2939 ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
2940 D->getLocation(), VN)));
2941 } else {
2942 SubstMapperTy = D->getType();
2943 }
2944 if (SubstMapperTy.isNull())
2945 return nullptr;
2946 // Create an instantiated copy of mapper.
2947 auto *PrevDeclInScope = D->getPrevDeclInScope();
2948 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
2949 PrevDeclInScope = cast<OMPDeclareMapperDecl>(
2950 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
2951 ->get<Decl *>());
2952 }
2953 OMPDeclareMapperDecl *NewDMD = SemaRef.ActOnOpenMPDeclareMapperDirectiveStart(
2954 /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(),
2955 VN, D->getAccess(), PrevDeclInScope);
2956 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD);
2957 SmallVector<OMPClause *, 6> Clauses;
2958 bool IsCorrect = true;
2959 if (!RequiresInstantiation) {
2960 // Copy the mapper variable.
2961 NewDMD->setMapperVarRef(D->getMapperVarRef());
2962 // Copy map clauses from the original mapper.
2963 for (OMPClause *C : D->clauselists())
2964 Clauses.push_back(C);
2965 } else {
2966 // Instantiate the mapper variable.
2967 DeclarationNameInfo DirName;
2968 SemaRef.StartOpenMPDSABlock(OMPD_declare_mapper, DirName, /*S=*/nullptr,
2969 (*D->clauselist_begin())->getBeginLoc());
2970 SemaRef.ActOnOpenMPDeclareMapperDirectiveVarDecl(
2971 NewDMD, /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN);
2972 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
2973 cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(),
2974 cast<DeclRefExpr>(NewDMD->getMapperVarRef())->getDecl());
2975 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
2976 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
2977 ThisContext);
2978 // Instantiate map clauses.
2979 for (OMPClause *C : D->clauselists()) {
2980 auto *OldC = cast<OMPMapClause>(C);
2981 SmallVector<Expr *, 4> NewVars;
2982 for (Expr *OE : OldC->varlists()) {
2983 Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get();
2984 if (!NE) {
2985 IsCorrect = false;
2986 break;
2987 }
2988 NewVars.push_back(NE);
2989 }
2990 if (!IsCorrect)
2991 break;
Michael Kruse4304e9d2019-02-19 16:38:20 +00002992 NestedNameSpecifierLoc NewQualifierLoc =
2993 SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(),
2994 TemplateArgs);
2995 CXXScopeSpec SS;
2996 SS.Adopt(NewQualifierLoc);
2997 DeclarationNameInfo NewNameInfo = SemaRef.SubstDeclarationNameInfo(
2998 OldC->getMapperIdInfo(), TemplateArgs);
2999 OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(),
3000 OldC->getEndLoc());
Michael Kruse251e1482019-02-01 20:25:04 +00003001 OMPClause *NewC = SemaRef.ActOnOpenMPMapClause(
Michael Kruse4304e9d2019-02-19 16:38:20 +00003002 OldC->getMapTypeModifiers(), OldC->getMapTypeModifiersLoc(), SS,
3003 NewNameInfo, OldC->getMapType(), OldC->isImplicitMapType(),
3004 OldC->getMapLoc(), OldC->getColonLoc(), NewVars, Locs);
Michael Kruse251e1482019-02-01 20:25:04 +00003005 Clauses.push_back(NewC);
3006 }
3007 SemaRef.EndOpenMPDSABlock(nullptr);
3008 }
3009 (void)SemaRef.ActOnOpenMPDeclareMapperDirectiveEnd(NewDMD, /*S=*/nullptr,
3010 Clauses);
3011 if (!IsCorrect)
3012 return nullptr;
3013 return NewDMD;
3014}
3015
Alexey Bataev4244be22016-02-11 05:35:55 +00003016Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
3017 OMPCapturedExprDecl * /*D*/) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00003018 llvm_unreachable("Should not be met in templates");
3019}
3020
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00003021Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003022 return VisitFunctionDecl(D, nullptr);
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00003023}
3024
Richard Smithbc491202017-02-17 20:05:37 +00003025Decl *
3026TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
Richard Smith2600c632018-05-30 20:24:10 +00003027 Decl *Inst = VisitFunctionDecl(D, nullptr);
3028 if (Inst && !D->getDescribedFunctionTemplate())
3029 Owner->addDecl(Inst);
3030 return Inst;
Richard Smithbc491202017-02-17 20:05:37 +00003031}
3032
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00003033Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003034 return VisitCXXMethodDecl(D, nullptr);
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00003035}
3036
3037Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
3038 llvm_unreachable("There are only CXXRecordDecls in C++");
3039}
3040
3041Decl *
3042TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
3043 ClassTemplateSpecializationDecl *D) {
Richard Smith8a0dde72013-12-14 01:04:22 +00003044 // As a MS extension, we permit class-scope explicit specialization
3045 // of member class templates.
3046 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
3047 assert(ClassTemplate->getDeclContext()->isRecord() &&
3048 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3049 "can only instantiate an explicit specialization "
3050 "for a member class template");
3051
3052 // Lookup the already-instantiated declaration in the instantiation
3053 // of the class template. FIXME: Diagnose or assert if this fails?
3054 DeclContext::lookup_result Found
3055 = Owner->lookup(ClassTemplate->getDeclName());
3056 if (Found.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +00003057 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00003058 ClassTemplateDecl *InstClassTemplate
3059 = dyn_cast<ClassTemplateDecl>(Found.front());
3060 if (!InstClassTemplate)
Craig Topperc3ec1492014-05-26 06:22:03 +00003061 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00003062
3063 // Substitute into the template arguments of the class template explicit
3064 // specialization.
3065 TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
3066 castAs<TemplateSpecializationTypeLoc>();
3067 TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
3068 Loc.getRAngleLoc());
3069 SmallVector<TemplateArgumentLoc, 4> ArgLocs;
3070 for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
3071 ArgLocs.push_back(Loc.getArgLoc(I));
3072 if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(),
3073 InstTemplateArgs, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00003074 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00003075
3076 // Check that the template argument list is well-formed for this
3077 // class template.
3078 SmallVector<TemplateArgument, 4> Converted;
3079 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
3080 D->getLocation(),
3081 InstTemplateArgs,
3082 false,
3083 Converted))
Craig Topperc3ec1492014-05-26 06:22:03 +00003084 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00003085
3086 // Figure out where to insert this class template explicit specialization
3087 // in the member template's set of class template explicit specializations.
Craig Topperc3ec1492014-05-26 06:22:03 +00003088 void *InsertPos = nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00003089 ClassTemplateSpecializationDecl *PrevDecl =
Craig Topper7e0daca2014-06-26 04:58:53 +00003090 InstClassTemplate->findSpecialization(Converted, InsertPos);
Richard Smith8a0dde72013-12-14 01:04:22 +00003091
3092 // Check whether we've already seen a conflicting instantiation of this
3093 // declaration (for instance, if there was a prior implicit instantiation).
3094 bool Ignored;
3095 if (PrevDecl &&
3096 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
3097 D->getSpecializationKind(),
3098 PrevDecl,
3099 PrevDecl->getSpecializationKind(),
3100 PrevDecl->getPointOfInstantiation(),
3101 Ignored))
Craig Topperc3ec1492014-05-26 06:22:03 +00003102 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00003103
3104 // If PrevDecl was a definition and D is also a definition, diagnose.
3105 // This happens in cases like:
3106 //
3107 // template<typename T, typename U>
3108 // struct Outer {
3109 // template<typename X> struct Inner;
3110 // template<> struct Inner<T> {};
3111 // template<> struct Inner<U> {};
3112 // };
3113 //
3114 // Outer<int, int> outer; // error: the explicit specializations of Inner
3115 // // have the same signature.
3116 if (PrevDecl && PrevDecl->getDefinition() &&
3117 D->isThisDeclarationADefinition()) {
3118 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
3119 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
3120 diag::note_previous_definition);
Craig Topperc3ec1492014-05-26 06:22:03 +00003121 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00003122 }
3123
3124 // Create the class template partial specialization declaration.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003125 ClassTemplateSpecializationDecl *InstD =
3126 ClassTemplateSpecializationDecl::Create(
3127 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
3128 D->getLocation(), InstClassTemplate, Converted, PrevDecl);
Richard Smith8a0dde72013-12-14 01:04:22 +00003129
3130 // Add this partial specialization to the set of class template partial
3131 // specializations.
3132 if (!PrevDecl)
3133 InstClassTemplate->AddSpecialization(InstD, InsertPos);
3134
3135 // Substitute the nested name specifier, if any.
3136 if (SubstQualifier(D, InstD))
Craig Topperc3ec1492014-05-26 06:22:03 +00003137 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00003138
3139 // Build the canonical type that describes the converted template
3140 // arguments of the class template explicit specialization.
3141 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00003142 TemplateName(InstClassTemplate), Converted,
Richard Smith8a0dde72013-12-14 01:04:22 +00003143 SemaRef.Context.getRecordType(InstD));
3144
3145 // Build the fully-sugared type for this class template
3146 // specialization as the user wrote in the specialization
3147 // itself. This means that we'll pretty-print the type retrieved
3148 // from the specialization's declaration the way that the user
3149 // actually wrote the specialization, rather than formatting the
3150 // name based on the "canonical" representation used to store the
3151 // template arguments in the specialization.
3152 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
3153 TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
3154 CanonType);
3155
3156 InstD->setAccess(D->getAccess());
3157 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
3158 InstD->setSpecializationKind(D->getSpecializationKind());
3159 InstD->setTypeAsWritten(WrittenTy);
3160 InstD->setExternLoc(D->getExternLoc());
3161 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
3162
3163 Owner->addDecl(InstD);
3164
3165 // Instantiate the members of the class-scope explicit specialization eagerly.
3166 // We don't have support for lazy instantiation of an explicit specialization
3167 // yet, and MSVC eagerly instantiates in this case.
3168 if (D->isThisDeclarationADefinition() &&
3169 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
3170 TSK_ImplicitInstantiation,
3171 /*Complain=*/true))
Craig Topperc3ec1492014-05-26 06:22:03 +00003172 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00003173
3174 return InstD;
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00003175}
3176
Larisse Voufo39a1e502013-08-06 01:03:05 +00003177Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3178 VarTemplateSpecializationDecl *D) {
3179
3180 TemplateArgumentListInfo VarTemplateArgsInfo;
3181 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
3182 assert(VarTemplate &&
3183 "A template specialization without specialized template?");
3184
3185 // Substitute the current template arguments.
3186 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
3187 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
3188 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
3189
3190 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
3191 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00003192 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003193
3194 // Check that the template argument list is well-formed for this template.
3195 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003196 if (SemaRef.CheckTemplateArgumentList(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003197 VarTemplate, VarTemplate->getBeginLoc(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00003198 const_cast<TemplateArgumentListInfo &>(VarTemplateArgsInfo), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00003199 Converted))
Craig Topperc3ec1492014-05-26 06:22:03 +00003200 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003201
3202 // Find the variable template specialization declaration that
3203 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00003204 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003205 if (VarTemplateSpecializationDecl *VarSpec = VarTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +00003206 Converted, InsertPos))
Larisse Voufo39a1e502013-08-06 01:03:05 +00003207 // If we already have a variable template specialization, return it.
3208 return VarSpec;
3209
3210 return VisitVarTemplateSpecializationDecl(VarTemplate, D, InsertPos,
3211 VarTemplateArgsInfo, Converted);
3212}
3213
3214Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3215 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
3216 const TemplateArgumentListInfo &TemplateArgsInfo,
Craig Topper00bbdcf2014-06-28 23:22:23 +00003217 ArrayRef<TemplateArgument> Converted) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003218
Larisse Voufo39a1e502013-08-06 01:03:05 +00003219 // Do substitution on the type of the declaration
3220 TypeSourceInfo *DI =
3221 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
3222 D->getTypeSpecStartLoc(), D->getDeclName());
3223 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00003224 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003225
3226 if (DI->getType()->isFunctionType()) {
3227 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
3228 << D->isStaticDataMember() << DI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00003229 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003230 }
3231
3232 // Build the instantiated declaration
3233 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
3234 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
David Majnemer8b622692016-07-03 21:17:51 +00003235 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003236 Var->setTemplateArgsInfo(TemplateArgsInfo);
Richard Smith8809a0c2013-09-27 20:14:12 +00003237 if (InsertPos)
3238 VarTemplate->AddSpecialization(Var, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003239
3240 // Substitute the nested name specifier, if any.
3241 if (SubstQualifier(D, Var))
Craig Topperc3ec1492014-05-26 06:22:03 +00003242 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003243
3244 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs,
Richard Smith541b38b2013-09-20 01:15:31 +00003245 Owner, StartingScope);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003246
3247 return Var;
3248}
3249
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00003250Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
3251 llvm_unreachable("@defs is not supported in Objective-C++");
3252}
3253
3254Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
3255 // FIXME: We need to be able to instantiate FriendTemplateDecls.
3256 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
3257 DiagnosticsEngine::Error,
3258 "cannot instantiate %0 yet");
3259 SemaRef.Diag(D->getLocation(), DiagID)
3260 << D->getDeclKindName();
3261
Craig Topperc3ec1492014-05-26 06:22:03 +00003262 return nullptr;
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00003263}
3264
3265Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
3266 llvm_unreachable("Unexpected decl");
3267}
3268
John McCall76d824f2009-08-25 22:02:44 +00003269Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregor01afeef2009-08-28 20:31:08 +00003270 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregord002c7b2009-05-11 23:53:27 +00003271 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor71ad4772010-02-16 19:28:15 +00003272 if (D->isInvalidDecl())
Craig Topperc3ec1492014-05-26 06:22:03 +00003273 return nullptr;
Douglas Gregor71ad4772010-02-16 19:28:15 +00003274
Douglas Gregord7e7a512009-03-17 21:15:40 +00003275 return Instantiator.Visit(D);
3276}
3277
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003278/// Instantiates a nested template parameter list in the current
John McCall87a44eb2009-08-20 01:44:21 +00003279/// instantiation context.
3280///
3281/// \param L The parameter list to instantiate
3282///
3283/// \returns NULL if there was an error
3284TemplateParameterList *
John McCall76d824f2009-08-25 22:02:44 +00003285TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCall87a44eb2009-08-20 01:44:21 +00003286 // Get errors for all the parameters before bailing out.
3287 bool Invalid = false;
3288
3289 unsigned N = L->size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003290 typedef SmallVector<NamedDecl *, 8> ParamVector;
John McCall87a44eb2009-08-20 01:44:21 +00003291 ParamVector Params;
3292 Params.reserve(N);
Davide Italiano18960b92015-07-02 19:20:11 +00003293 for (auto &P : *L) {
3294 NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
John McCall87a44eb2009-08-20 01:44:21 +00003295 Params.push_back(D);
Douglas Gregore62e6a02009-11-11 19:13:48 +00003296 Invalid = Invalid || !D || D->isInvalidDecl();
John McCall87a44eb2009-08-20 01:44:21 +00003297 }
3298
3299 // Clean up if we had an error.
Douglas Gregorb412e172010-07-25 18:17:45 +00003300 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +00003301 return nullptr;
John McCall87a44eb2009-08-20 01:44:21 +00003302
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00003303 // Note: we substitute into associated constraints later
3304 Expr *const UninstantiatedRequiresClause = L->getRequiresClause();
3305
John McCall87a44eb2009-08-20 01:44:21 +00003306 TemplateParameterList *InstL
3307 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
David Majnemer902f8c62015-12-27 07:16:27 +00003308 L->getLAngleLoc(), Params,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00003309 L->getRAngleLoc(),
3310 UninstantiatedRequiresClause);
John McCall87a44eb2009-08-20 01:44:21 +00003311 return InstL;
Mike Stump11289f42009-09-09 15:08:12 +00003312}
John McCall87a44eb2009-08-20 01:44:21 +00003313
Richard Smith5d331022018-03-08 01:07:33 +00003314TemplateParameterList *
3315Sema::SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
3316 const MultiLevelTemplateArgumentList &TemplateArgs) {
3317 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
3318 return Instantiator.SubstTemplateParams(Params);
3319}
3320
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003321/// Instantiate the declaration of a class template partial
Douglas Gregor21610382009-10-29 00:04:11 +00003322/// specialization.
3323///
3324/// \param ClassTemplate the (instantiated) class template that is partially
3325// specialized by the instantiation of \p PartialSpec.
3326///
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003327/// \param PartialSpec the (uninstantiated) class template partial
Douglas Gregor21610382009-10-29 00:04:11 +00003328/// specialization that we are instantiating.
3329///
Douglas Gregor869853e2010-11-10 19:44:59 +00003330/// \returns The instantiated partial specialization, if successful; otherwise,
3331/// NULL to indicate an error.
3332ClassTemplatePartialSpecializationDecl *
Douglas Gregor21610382009-10-29 00:04:11 +00003333TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
3334 ClassTemplateDecl *ClassTemplate,
3335 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor954de172009-10-31 17:21:17 +00003336 // Create a local instantiation scope for this class template partial
3337 // specialization, which will contain the instantiations of the template
3338 // parameters.
John McCall19c1bfd2010-08-25 05:32:35 +00003339 LocalInstantiationScope Scope(SemaRef);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003340
Douglas Gregor21610382009-10-29 00:04:11 +00003341 // Substitute into the template parameters of the class template partial
3342 // specialization.
3343 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
3344 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
3345 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00003346 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003347
Douglas Gregor21610382009-10-29 00:04:11 +00003348 // Substitute into the template arguments of the class template partial
3349 // specialization.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00003350 const ASTTemplateArgumentListInfo *TemplArgInfo
3351 = PartialSpec->getTemplateArgsAsWritten();
3352 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
3353 TemplArgInfo->RAngleLoc);
3354 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
3355 TemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00003356 InstTemplateArgs, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00003357 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003358
Douglas Gregor21610382009-10-29 00:04:11 +00003359 // Check that the template argument list is well-formed for this
3360 // class template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003361 SmallVector<TemplateArgument, 4> Converted;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003362 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
Douglas Gregor21610382009-10-29 00:04:11 +00003363 PartialSpec->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003364 InstTemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00003365 false,
3366 Converted))
Craig Topperc3ec1492014-05-26 06:22:03 +00003367 return nullptr;
Douglas Gregor21610382009-10-29 00:04:11 +00003368
Richard Smith57aae072016-12-28 02:37:25 +00003369 // Check these arguments are valid for a template partial specialization.
3370 if (SemaRef.CheckTemplatePartialSpecializationArgs(
3371 PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
3372 Converted))
3373 return nullptr;
3374
Douglas Gregor21610382009-10-29 00:04:11 +00003375 // Figure out where to insert this class template partial specialization
3376 // in the member template's set of class template partial specializations.
Craig Topperc3ec1492014-05-26 06:22:03 +00003377 void *InsertPos = nullptr;
Douglas Gregor21610382009-10-29 00:04:11 +00003378 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00003379 = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003380
Douglas Gregor21610382009-10-29 00:04:11 +00003381 // Build the canonical type that describes the converted template
3382 // arguments of the class template partial specialization.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003383 QualType CanonType
Douglas Gregor21610382009-10-29 00:04:11 +00003384 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
David Majnemer6fbeee32016-07-07 04:43:07 +00003385 Converted);
Douglas Gregor21610382009-10-29 00:04:11 +00003386
3387 // Build the fully-sugared type for this class template
3388 // specialization as the user wrote in the specialization
3389 // itself. This means that we'll pretty-print the type retrieved
3390 // from the specialization's declaration the way that the user
3391 // actually wrote the specialization, rather than formatting the
3392 // name based on the "canonical" representation used to store the
3393 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00003394 TypeSourceInfo *WrittenTy
3395 = SemaRef.Context.getTemplateSpecializationTypeInfo(
3396 TemplateName(ClassTemplate),
3397 PartialSpec->getLocation(),
John McCall6b51f282009-11-23 01:53:49 +00003398 InstTemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00003399 CanonType);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003400
Douglas Gregor21610382009-10-29 00:04:11 +00003401 if (PrevDecl) {
3402 // We've already seen a partial specialization with the same template
3403 // parameters and template arguments. This can happen, for example, when
3404 // substituting the outer template arguments ends up causing two
3405 // class template partial specializations of a member class template
3406 // to have identical forms, e.g.,
3407 //
3408 // template<typename T, typename U>
3409 // struct Outer {
3410 // template<typename X, typename Y> struct Inner;
3411 // template<typename Y> struct Inner<T, Y>;
3412 // template<typename Y> struct Inner<U, Y>;
3413 // };
3414 //
3415 // Outer<int, int> outer; // error: the partial specializations of Inner
3416 // // have the same signature.
3417 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregor869853e2010-11-10 19:44:59 +00003418 << WrittenTy->getType();
Douglas Gregor21610382009-10-29 00:04:11 +00003419 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
3420 << SemaRef.Context.getTypeDeclType(PrevDecl);
Craig Topperc3ec1492014-05-26 06:22:03 +00003421 return nullptr;
Douglas Gregor21610382009-10-29 00:04:11 +00003422 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003423
3424
Douglas Gregor21610382009-10-29 00:04:11 +00003425 // Create the class template partial specialization declaration.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003426 ClassTemplatePartialSpecializationDecl *InstPartialSpec =
3427 ClassTemplatePartialSpecializationDecl::Create(
3428 SemaRef.Context, PartialSpec->getTagKind(), Owner,
3429 PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
3430 ClassTemplate, Converted, InstTemplateArgs, CanonType, nullptr);
John McCall3e11ebe2010-03-15 10:12:16 +00003431 // Substitute the nested name specifier, if any.
3432 if (SubstQualifier(PartialSpec, InstPartialSpec))
Craig Topperc3ec1492014-05-26 06:22:03 +00003433 return nullptr;
John McCall3e11ebe2010-03-15 10:12:16 +00003434
Douglas Gregor21610382009-10-29 00:04:11 +00003435 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor6044d692010-05-19 17:02:24 +00003436 InstPartialSpec->setTypeAsWritten(WrittenTy);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003437
Richard Smith57aae072016-12-28 02:37:25 +00003438 // Check the completed partial specialization.
3439 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
3440
Douglas Gregor21610382009-10-29 00:04:11 +00003441 // Add this partial specialization to the set of class template partial
3442 // specializations.
Craig Topperc3ec1492014-05-26 06:22:03 +00003443 ClassTemplate->AddPartialSpecialization(InstPartialSpec,
3444 /*InsertPos=*/nullptr);
Douglas Gregor869853e2010-11-10 19:44:59 +00003445 return InstPartialSpec;
Douglas Gregor21610382009-10-29 00:04:11 +00003446}
3447
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003448/// Instantiate the declaration of a variable template partial
Larisse Voufo39a1e502013-08-06 01:03:05 +00003449/// specialization.
3450///
3451/// \param VarTemplate the (instantiated) variable template that is partially
3452/// specialized by the instantiation of \p PartialSpec.
3453///
3454/// \param PartialSpec the (uninstantiated) variable template partial
3455/// specialization that we are instantiating.
3456///
3457/// \returns The instantiated partial specialization, if successful; otherwise,
3458/// NULL to indicate an error.
3459VarTemplatePartialSpecializationDecl *
3460TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
3461 VarTemplateDecl *VarTemplate,
3462 VarTemplatePartialSpecializationDecl *PartialSpec) {
3463 // Create a local instantiation scope for this variable template partial
3464 // specialization, which will contain the instantiations of the template
3465 // parameters.
3466 LocalInstantiationScope Scope(SemaRef);
3467
3468 // Substitute into the template parameters of the variable template partial
3469 // specialization.
3470 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
3471 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
3472 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00003473 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003474
3475 // Substitute into the template arguments of the variable template partial
3476 // specialization.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00003477 const ASTTemplateArgumentListInfo *TemplArgInfo
3478 = PartialSpec->getTemplateArgsAsWritten();
3479 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
3480 TemplArgInfo->RAngleLoc);
3481 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
3482 TemplArgInfo->NumTemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00003483 InstTemplateArgs, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00003484 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003485
3486 // Check that the template argument list is well-formed for this
3487 // class template.
3488 SmallVector<TemplateArgument, 4> Converted;
3489 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
3490 InstTemplateArgs, false, Converted))
Craig Topperc3ec1492014-05-26 06:22:03 +00003491 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003492
Richard Smith57aae072016-12-28 02:37:25 +00003493 // Check these arguments are valid for a template partial specialization.
3494 if (SemaRef.CheckTemplatePartialSpecializationArgs(
3495 PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
3496 Converted))
3497 return nullptr;
3498
Larisse Voufo39a1e502013-08-06 01:03:05 +00003499 // Figure out where to insert this variable template partial specialization
3500 // in the member template's set of variable template partial specializations.
Craig Topperc3ec1492014-05-26 06:22:03 +00003501 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003502 VarTemplateSpecializationDecl *PrevDecl =
Craig Topper7e0daca2014-06-26 04:58:53 +00003503 VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003504
3505 // Build the canonical type that describes the converted template
3506 // arguments of the variable template partial specialization.
3507 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00003508 TemplateName(VarTemplate), Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003509
3510 // Build the fully-sugared type for this variable template
3511 // specialization as the user wrote in the specialization
3512 // itself. This means that we'll pretty-print the type retrieved
3513 // from the specialization's declaration the way that the user
3514 // actually wrote the specialization, rather than formatting the
3515 // name based on the "canonical" representation used to store the
3516 // template arguments in the specialization.
3517 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
3518 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
3519 CanonType);
3520
3521 if (PrevDecl) {
3522 // We've already seen a partial specialization with the same template
3523 // parameters and template arguments. This can happen, for example, when
3524 // substituting the outer template arguments ends up causing two
3525 // variable template partial specializations of a member variable template
3526 // to have identical forms, e.g.,
3527 //
3528 // template<typename T, typename U>
3529 // struct Outer {
3530 // template<typename X, typename Y> pair<X,Y> p;
3531 // template<typename Y> pair<T, Y> p;
3532 // template<typename Y> pair<U, Y> p;
3533 // };
3534 //
3535 // Outer<int, int> outer; // error: the partial specializations of Inner
3536 // // have the same signature.
3537 SemaRef.Diag(PartialSpec->getLocation(),
3538 diag::err_var_partial_spec_redeclared)
3539 << WrittenTy->getType();
3540 SemaRef.Diag(PrevDecl->getLocation(),
3541 diag::note_var_prev_partial_spec_here);
Craig Topperc3ec1492014-05-26 06:22:03 +00003542 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003543 }
3544
3545 // Do substitution on the type of the declaration
3546 TypeSourceInfo *DI = SemaRef.SubstType(
3547 PartialSpec->getTypeSourceInfo(), TemplateArgs,
3548 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
3549 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00003550 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003551
3552 if (DI->getType()->isFunctionType()) {
3553 SemaRef.Diag(PartialSpec->getLocation(),
3554 diag::err_variable_instantiates_to_function)
3555 << PartialSpec->isStaticDataMember() << DI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00003556 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003557 }
3558
3559 // Create the variable template partial specialization declaration.
3560 VarTemplatePartialSpecializationDecl *InstPartialSpec =
3561 VarTemplatePartialSpecializationDecl::Create(
3562 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
3563 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
David Majnemer8b622692016-07-03 21:17:51 +00003564 DI, PartialSpec->getStorageClass(), Converted, InstTemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003565
3566 // Substitute the nested name specifier, if any.
3567 if (SubstQualifier(PartialSpec, InstPartialSpec))
Craig Topperc3ec1492014-05-26 06:22:03 +00003568 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003569
3570 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
3571 InstPartialSpec->setTypeAsWritten(WrittenTy);
3572
Richard Smith57aae072016-12-28 02:37:25 +00003573 // Check the completed partial specialization.
3574 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
3575
Larisse Voufo39a1e502013-08-06 01:03:05 +00003576 // Add this partial specialization to the set of variable template partial
3577 // specializations. The instantiation of the initializer is not necessary.
Craig Topperc3ec1492014-05-26 06:22:03 +00003578 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
Larisse Voufo4cda4612013-08-22 00:28:27 +00003579
Larisse Voufo4cda4612013-08-22 00:28:27 +00003580 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
Richard Smith541b38b2013-09-20 01:15:31 +00003581 LateAttrs, Owner, StartingScope);
Larisse Voufo4cda4612013-08-22 00:28:27 +00003582
Larisse Voufo39a1e502013-08-06 01:03:05 +00003583 return InstPartialSpec;
3584}
3585
John McCall58f10c32010-03-11 09:03:00 +00003586TypeSourceInfo*
John McCall76d824f2009-08-25 22:02:44 +00003587TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003588 SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall58f10c32010-03-11 09:03:00 +00003589 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
3590 assert(OldTInfo && "substituting function without type source info");
3591 assert(Params.empty() && "parameter vector is non-empty at start");
Craig Topperc3ec1492014-05-26 06:22:03 +00003592
3593 CXXRecordDecl *ThisContext = nullptr;
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00003594 Qualifiers ThisTypeQuals;
Douglas Gregor3024f072012-04-16 07:05:22 +00003595 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Richard Smithc3d2ebb2013-06-07 02:33:37 +00003596 ThisContext = cast<CXXRecordDecl>(Owner);
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00003597 ThisTypeQuals = Method->getMethodQualifiers();
Douglas Gregor3024f072012-04-16 07:05:22 +00003598 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003599
John McCallb29f78f2010-04-09 17:38:44 +00003600 TypeSourceInfo *NewTInfo
3601 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
3602 D->getTypeSpecStartLoc(),
Douglas Gregor3024f072012-04-16 07:05:22 +00003603 D->getDeclName(),
3604 ThisContext, ThisTypeQuals);
John McCall58f10c32010-03-11 09:03:00 +00003605 if (!NewTInfo)
Craig Topperc3ec1492014-05-26 06:22:03 +00003606 return nullptr;
Douglas Gregor21342092009-03-24 00:38:23 +00003607
Reid Klecknera09e44c2013-07-31 21:00:18 +00003608 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
3609 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
3610 if (NewTInfo != OldTInfo) {
3611 // Get parameters from the new type info.
Abramo Bagnaraa44c9022010-12-13 22:27:55 +00003612 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +00003613 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
Richard Smith198223b2012-07-18 01:29:05 +00003614 unsigned NewIdx = 0;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003615 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
Douglas Gregorf3010112011-01-07 16:43:16 +00003616 OldIdx != NumOldParams; ++OldIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003617 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
Richard Smith198223b2012-07-18 01:29:05 +00003618 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
3619
David Blaikie05785d12013-02-20 22:23:23 +00003620 Optional<unsigned> NumArgumentsInExpansion;
Richard Smith198223b2012-07-18 01:29:05 +00003621 if (OldParam->isParameterPack())
3622 NumArgumentsInExpansion =
3623 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
3624 TemplateArgs);
3625 if (!NumArgumentsInExpansion) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003626 // Simple case: normal parameter, or a parameter pack that's
Douglas Gregorf3010112011-01-07 16:43:16 +00003627 // instantiated to a (still-dependent) parameter pack.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003628 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
Douglas Gregorf3010112011-01-07 16:43:16 +00003629 Params.push_back(NewParam);
Richard Smith198223b2012-07-18 01:29:05 +00003630 Scope->InstantiatedLocal(OldParam, NewParam);
3631 } else {
3632 // Parameter pack expansion: make the instantiation an argument pack.
3633 Scope->MakeInstantiatedLocalArgPack(OldParam);
3634 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003635 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
Richard Smith198223b2012-07-18 01:29:05 +00003636 Params.push_back(NewParam);
3637 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
3638 }
Douglas Gregorf3010112011-01-07 16:43:16 +00003639 }
Douglas Gregor95c70ec2010-05-03 15:32:18 +00003640 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00003641 } else {
3642 // The function type itself was not dependent and therefore no
3643 // substitution occurred. However, we still need to instantiate
3644 // the function parameters themselves.
3645 const FunctionProtoType *OldProto =
3646 cast<FunctionProtoType>(OldProtoLoc.getType());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003647 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
3648 ++i) {
3649 ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
Reid Klecknera09e44c2013-07-31 21:00:18 +00003650 if (!OldParam) {
3651 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
Alp Toker9cacbab2014-01-20 20:26:09 +00003652 D, D->getLocation(), OldProto->getParamType(i)));
Reid Klecknera09e44c2013-07-31 21:00:18 +00003653 continue;
3654 }
3655
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00003656 ParmVarDecl *Parm =
Reid Klecknera09e44c2013-07-31 21:00:18 +00003657 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
Douglas Gregor95c70ec2010-05-03 15:32:18 +00003658 if (!Parm)
Craig Topperc3ec1492014-05-26 06:22:03 +00003659 return nullptr;
Douglas Gregor95c70ec2010-05-03 15:32:18 +00003660 Params.push_back(Parm);
3661 }
Douglas Gregor940bca72010-04-12 07:48:19 +00003662 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00003663 } else {
3664 // If the type of this function, after ignoring parentheses, is not
3665 // *directly* a function type, then we're instantiating a function that
3666 // was declared via a typedef or with attributes, e.g.,
3667 //
3668 // typedef int functype(int, int);
3669 // functype func;
3670 // int __cdecl meth(int, int);
3671 //
3672 // In this case, we'll just go instantiate the ParmVarDecls that we
3673 // synthesized in the method declaration.
3674 SmallVector<QualType, 4> ParamTypes;
John McCallc8e321d2016-03-01 02:09:25 +00003675 Sema::ExtParameterInfoBuilder ExtParamInfos;
David Majnemer59f77922016-06-24 04:05:48 +00003676 if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
3677 TemplateArgs, ParamTypes, &Params,
3678 ExtParamInfos))
Craig Topperc3ec1492014-05-26 06:22:03 +00003679 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00003680 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00003681
John McCall58f10c32010-03-11 09:03:00 +00003682 return NewTInfo;
Douglas Gregor21342092009-03-24 00:38:23 +00003683}
3684
Richard Smithf623c962012-04-17 00:58:00 +00003685/// Introduce the instantiated function parameters into the local
3686/// instantiation scope, and set the parameter names to those used
3687/// in the template.
Richard Smith2e321552014-11-12 02:00:47 +00003688static bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
Richard Smithf623c962012-04-17 00:58:00 +00003689 const FunctionDecl *PatternDecl,
3690 LocalInstantiationScope &Scope,
3691 const MultiLevelTemplateArgumentList &TemplateArgs) {
3692 unsigned FParamIdx = 0;
3693 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
3694 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
3695 if (!PatternParam->isParameterPack()) {
3696 // Simple case: not a parameter pack.
3697 assert(FParamIdx < Function->getNumParams());
3698 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
Richard Smith2e321552014-11-12 02:00:47 +00003699 FunctionParam->setDeclName(PatternParam->getDeclName());
Richard Smithaae40582014-03-13 00:28:45 +00003700 // If the parameter's type is not dependent, update it to match the type
3701 // in the pattern. They can differ in top-level cv-qualifiers, and we want
3702 // the pattern's type here. If the type is dependent, they can't differ,
Richard Smith2e321552014-11-12 02:00:47 +00003703 // per core issue 1668. Substitute into the type from the pattern, in case
3704 // it's instantiation-dependent.
Richard Smithaae40582014-03-13 00:28:45 +00003705 // FIXME: Updating the type to work around this is at best fragile.
Richard Smith2e321552014-11-12 02:00:47 +00003706 if (!PatternDecl->getType()->isDependentType()) {
3707 QualType T = S.SubstType(PatternParam->getType(), TemplateArgs,
3708 FunctionParam->getLocation(),
3709 FunctionParam->getDeclName());
3710 if (T.isNull())
3711 return true;
3712 FunctionParam->setType(T);
3713 }
Richard Smithaae40582014-03-13 00:28:45 +00003714
Richard Smithf623c962012-04-17 00:58:00 +00003715 Scope.InstantiatedLocal(PatternParam, FunctionParam);
3716 ++FParamIdx;
3717 continue;
3718 }
3719
3720 // Expand the parameter pack.
3721 Scope.MakeInstantiatedLocalArgPack(PatternParam);
David Blaikie05785d12013-02-20 22:23:23 +00003722 Optional<unsigned> NumArgumentsInExpansion
Richard Smithf623c962012-04-17 00:58:00 +00003723 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
Richard Smith198223b2012-07-18 01:29:05 +00003724 assert(NumArgumentsInExpansion &&
3725 "should only be called when all template arguments are known");
Richard Smith2e321552014-11-12 02:00:47 +00003726 QualType PatternType =
3727 PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
Richard Smith198223b2012-07-18 01:29:05 +00003728 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
Richard Smithf623c962012-04-17 00:58:00 +00003729 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
NAKAMURA Takumi23224152014-10-17 12:48:37 +00003730 FunctionParam->setDeclName(PatternParam->getDeclName());
Richard Smith2e321552014-11-12 02:00:47 +00003731 if (!PatternDecl->getType()->isDependentType()) {
3732 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg);
3733 QualType T = S.SubstType(PatternType, TemplateArgs,
3734 FunctionParam->getLocation(),
3735 FunctionParam->getDeclName());
3736 if (T.isNull())
3737 return true;
3738 FunctionParam->setType(T);
3739 }
3740
Richard Smithf623c962012-04-17 00:58:00 +00003741 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
3742 ++FParamIdx;
3743 }
3744 }
Richard Smithf623c962012-04-17 00:58:00 +00003745
Richard Smith2e321552014-11-12 02:00:47 +00003746 return false;
Richard Smithf623c962012-04-17 00:58:00 +00003747}
3748
3749void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
3750 FunctionDecl *Decl) {
Richard Smithd3729422012-04-19 00:08:28 +00003751 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
3752 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
Richard Smithf623c962012-04-17 00:58:00 +00003753 return;
3754
3755 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
3756 InstantiatingTemplate::ExceptionSpecification());
Alp Tokerd4a72d52013-10-08 08:09:04 +00003757 if (Inst.isInvalid()) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003758 // We hit the instantiation depth limit. Clear the exception specification
3759 // so that our callers don't have to cope with EST_Uninstantiated.
Richard Smith8acb4282014-07-31 21:57:55 +00003760 UpdateExceptionSpec(Decl, EST_None);
Richard Smithf623c962012-04-17 00:58:00 +00003761 return;
Richard Smithd3b5c9082012-07-27 04:22:15 +00003762 }
Richard Smith54f18e82016-08-31 02:15:21 +00003763 if (Inst.isAlreadyInstantiating()) {
3764 // This exception specification indirectly depends on itself. Reject.
3765 // FIXME: Corresponding rule in the standard?
3766 Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
3767 UpdateExceptionSpec(Decl, EST_None);
3768 return;
3769 }
Richard Smithf623c962012-04-17 00:58:00 +00003770
3771 // Enter the scope of this instantiation. We don't use
3772 // PushDeclContext because we don't have a scope.
3773 Sema::ContextRAII savedContext(*this, Decl);
3774 LocalInstantiationScope Scope(*this);
3775
3776 MultiLevelTemplateArgumentList TemplateArgs =
Craig Topperc3ec1492014-05-26 06:22:03 +00003777 getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true);
Richard Smithf623c962012-04-17 00:58:00 +00003778
Richard Smithd3729422012-04-19 00:08:28 +00003779 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
Richard Smith2e321552014-11-12 02:00:47 +00003780 if (addInstantiatedParametersToScope(*this, Decl, Template, Scope,
3781 TemplateArgs)) {
3782 UpdateExceptionSpec(Decl, EST_None);
3783 return;
3784 }
Richard Smithf623c962012-04-17 00:58:00 +00003785
Richard Smith2e321552014-11-12 02:00:47 +00003786 SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
3787 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +00003788}
3789
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003790/// Initializes the common fields of an instantiation function
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003791/// declaration (New) from the corresponding fields of its template (Tmpl).
3792///
3793/// \returns true if there was an error
Mike Stump11289f42009-09-09 15:08:12 +00003794bool
3795TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003796 FunctionDecl *Tmpl) {
David Blaikie5a0956e2012-07-16 18:50:45 +00003797 if (Tmpl->isDeleted())
Alexis Hunt4a8ea102011-05-06 20:44:56 +00003798 New->setDeletedAsWritten();
Mike Stump11289f42009-09-09 15:08:12 +00003799
Richard Smith32918772017-02-14 00:25:28 +00003800 New->setImplicit(Tmpl->isImplicit());
3801
David Majnemerdbc0c8f2013-12-04 09:01:55 +00003802 // Forward the mangling number from the template to the instantiated decl.
3803 SemaRef.Context.setManglingNumber(New,
3804 SemaRef.Context.getManglingNumber(Tmpl));
3805
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003806 // If we are performing substituting explicitly-specified template arguments
3807 // or deduced template arguments into a function template and we reach this
3808 // point, we are now past the point where SFINAE applies and have committed
Mike Stump11289f42009-09-09 15:08:12 +00003809 // to keeping the new function template specialization. We therefore
3810 // convert the active template instantiation for the function template
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003811 // into a template instantiation for this specific function template
3812 // specialization, which is not a SFINAE context, so that we diagnose any
3813 // further errors in the declaration itself.
Richard Smith696e3122017-02-23 01:43:54 +00003814 typedef Sema::CodeSynthesisContext ActiveInstType;
3815 ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003816 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
3817 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump11289f42009-09-09 15:08:12 +00003818 if (FunctionTemplateDecl *FunTmpl
Nick Lewyckycc8990f2012-11-16 08:40:59 +00003819 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
Mike Stump11289f42009-09-09 15:08:12 +00003820 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003821 "Deduction from the wrong function template?");
Daniel Dunbar54c59642009-07-16 22:10:11 +00003822 (void) FunTmpl;
Gabor Horvath207e7b12018-02-10 14:04:45 +00003823 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003824 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
Nick Lewyckycc8990f2012-11-16 08:40:59 +00003825 ActiveInst.Entity = New;
Gabor Horvath207e7b12018-02-10 14:04:45 +00003826 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003827 }
3828 }
Mike Stump11289f42009-09-09 15:08:12 +00003829
Douglas Gregor049bdca2009-12-08 17:45:32 +00003830 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
3831 assert(Proto && "Function template without prototype?");
3832
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003833 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
John McCalldb40c7f2010-12-14 08:05:40 +00003834 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00003835
Richard Smithf623c962012-04-17 00:58:00 +00003836 // DR1330: In C++11, defer instantiation of a non-trivial
3837 // exception specification.
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003838 // DR1484: Local classes and their members are instantiated along with the
3839 // containing function.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003840 if (SemaRef.getLangOpts().CPlusPlus11 &&
Richard Smith8acb4282014-07-31 21:57:55 +00003841 EPI.ExceptionSpec.Type != EST_None &&
3842 EPI.ExceptionSpec.Type != EST_DynamicNone &&
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003843 EPI.ExceptionSpec.Type != EST_BasicNoexcept &&
Serge Pavlov73c6a242015-08-23 10:22:28 +00003844 !Tmpl->isLexicallyWithinFunctionOrMethod()) {
Richard Smithd3729422012-04-19 00:08:28 +00003845 FunctionDecl *ExceptionSpecTemplate = Tmpl;
Richard Smith8acb4282014-07-31 21:57:55 +00003846 if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
3847 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
Richard Smith185be182013-04-10 05:48:59 +00003848 ExceptionSpecificationType NewEST = EST_Uninstantiated;
Richard Smith8acb4282014-07-31 21:57:55 +00003849 if (EPI.ExceptionSpec.Type == EST_Unevaluated)
Richard Smith185be182013-04-10 05:48:59 +00003850 NewEST = EST_Unevaluated;
Richard Smithd3729422012-04-19 00:08:28 +00003851
Richard Smithf623c962012-04-17 00:58:00 +00003852 // Mark the function has having an uninstantiated exception specification.
3853 const FunctionProtoType *NewProto
3854 = New->getType()->getAs<FunctionProtoType>();
3855 assert(NewProto && "Template instantiation without function prototype?");
3856 EPI = NewProto->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00003857 EPI.ExceptionSpec.Type = NewEST;
3858 EPI.ExceptionSpec.SourceDecl = New;
3859 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
Reid Kleckner896b32f2013-06-10 20:51:09 +00003860 New->setType(SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003861 NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
Richard Smithf623c962012-04-17 00:58:00 +00003862 } else {
Faisal Vali40fd4ce2017-05-09 04:17:15 +00003863 Sema::ContextRAII SwitchContext(SemaRef, New);
Richard Smith2e321552014-11-12 02:00:47 +00003864 SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +00003865 }
Douglas Gregor049bdca2009-12-08 17:45:32 +00003866 }
3867
Rafael Espindolaba195cf2011-07-06 15:46:09 +00003868 // Get the definition. Leaves the variable unchanged if undefined.
Richard Smithf623c962012-04-17 00:58:00 +00003869 const FunctionDecl *Definition = Tmpl;
Rafael Espindolaba195cf2011-07-06 15:46:09 +00003870 Tmpl->isDefined(Definition);
3871
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00003872 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
3873 LateAttrs, StartingScope);
Douglas Gregor08329632010-06-15 17:05:35 +00003874
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003875 return false;
3876}
3877
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003878/// Initializes common fields of an instantiated method
Douglas Gregor21342092009-03-24 00:38:23 +00003879/// declaration (New) from the corresponding fields of its template
3880/// (Tmpl).
3881///
3882/// \returns true if there was an error
Mike Stump11289f42009-09-09 15:08:12 +00003883bool
3884TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor21342092009-03-24 00:38:23 +00003885 CXXMethodDecl *Tmpl) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003886 if (InitFunctionInstantiation(New, Tmpl))
3887 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003888
Richard Smith5159bbad2018-09-05 22:30:37 +00003889 if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11)
3890 SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New));
3891
Douglas Gregor21342092009-03-24 00:38:23 +00003892 New->setAccess(Tmpl->getAccess());
Fariborz Jahanian6dfc1972009-12-03 18:44:40 +00003893 if (Tmpl->isVirtualAsWritten())
Douglas Gregor11c024b2010-09-28 20:50:54 +00003894 New->setVirtualAsWritten(true);
Douglas Gregor21342092009-03-24 00:38:23 +00003895
Douglas Gregor21342092009-03-24 00:38:23 +00003896 // FIXME: New needs a pointer to Tmpl
3897 return false;
3898}
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003899
Richard Smith50e291e2018-01-02 23:52:42 +00003900/// Instantiate (or find existing instantiation of) a function template with a
3901/// given set of template arguments.
3902///
3903/// Usually this should not be used, and template argument deduction should be
3904/// used in its place.
3905FunctionDecl *
3906Sema::InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
3907 const TemplateArgumentList *Args,
3908 SourceLocation Loc) {
3909 FunctionDecl *FD = FTD->getTemplatedDecl();
3910
3911 sema::TemplateDeductionInfo Info(Loc);
3912 InstantiatingTemplate Inst(
3913 *this, Loc, FTD, Args->asArray(),
3914 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
3915 if (Inst.isInvalid())
3916 return nullptr;
3917
3918 ContextRAII SavedContext(*this, FD);
3919 MultiLevelTemplateArgumentList MArgs(*Args);
3920
3921 return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs));
3922}
3923
Reid Kleckner61195e12017-01-05 01:08:22 +00003924/// In the MS ABI, we need to instantiate default arguments of dllexported
3925/// default constructors along with the constructor definition. This allows IR
3926/// gen to emit a constructor closure which calls the default constructor with
3927/// its default arguments.
3928static void InstantiateDefaultCtorDefaultArgs(Sema &S,
3929 CXXConstructorDecl *Ctor) {
3930 assert(S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
3931 Ctor->isDefaultConstructor());
3932 unsigned NumParams = Ctor->getNumParams();
3933 if (NumParams == 0)
3934 return;
3935 DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>();
3936 if (!Attr)
3937 return;
3938 for (unsigned I = 0; I != NumParams; ++I) {
3939 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), Ctor,
3940 Ctor->getParamDecl(I));
3941 S.DiscardCleanupsInEvaluationContext();
3942 }
3943}
3944
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003945/// Instantiate the definition of the given function from its
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003946/// template.
3947///
Douglas Gregordda7ced2009-06-30 17:20:14 +00003948/// \param PointOfInstantiation the point at which the instantiation was
3949/// required. Note that this is not precisely a "point of instantiation"
3950/// for the function, but it's close.
3951///
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003952/// \param Function the already-instantiated declaration of a
Douglas Gregordda7ced2009-06-30 17:20:14 +00003953/// function template specialization or member function of a class template
3954/// specialization.
3955///
3956/// \param Recursive if true, recursively instantiates any functions that
3957/// are required by this instantiation.
Douglas Gregora8b89d22009-10-15 14:05:49 +00003958///
3959/// \param DefinitionRequired if true, then we are performing an explicit
3960/// instantiation where the body of the function is required. Complain if
3961/// there is no such body.
Douglas Gregor85673582009-05-18 17:01:57 +00003962void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregordda7ced2009-06-30 17:20:14 +00003963 FunctionDecl *Function,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003964 bool Recursive,
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00003965 bool DefinitionRequired,
3966 bool AtEndOfTU) {
Richard Smithcb189572017-10-28 01:15:00 +00003967 if (Function->isInvalidDecl() || Function->isDefined() ||
3968 isa<CXXDeductionGuideDecl>(Function))
Douglas Gregorb4850462009-05-14 23:26:13 +00003969 return;
3970
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003971 // Never instantiate an explicit specialization except if it is a class scope
3972 // explicit specialization.
Vassil Vassilevb21ee082016-08-18 22:01:25 +00003973 TemplateSpecializationKind TSK = Function->getTemplateSpecializationKind();
3974 if (TSK == TSK_ExplicitSpecialization &&
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003975 !Function->getClassScopeSpecializationPattern())
Douglas Gregor86d142a2009-10-08 07:24:58 +00003976 return;
Douglas Gregor69f6a362010-05-17 17:34:56 +00003977
Douglas Gregor24c332b2009-05-14 21:06:31 +00003978 // Find the function body that we'll be substituting.
Douglas Gregorafca3b42009-10-27 20:53:28 +00003979 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Alexis Hunt23f6b832011-05-27 20:00:14 +00003980 assert(PatternDecl && "instantiating a non-template");
3981
Richard Smith6f4e2e02016-08-23 19:41:39 +00003982 const FunctionDecl *PatternDef = PatternDecl->getDefinition();
Richard Smith3f6865a82016-08-23 21:12:54 +00003983 Stmt *Pattern = nullptr;
3984 if (PatternDef) {
3985 Pattern = PatternDef->getBody(PatternDef);
Richard Smith6f4e2e02016-08-23 19:41:39 +00003986 PatternDecl = PatternDef;
Richard Smith6c7161162017-08-12 01:46:03 +00003987 if (PatternDef->willHaveBody())
3988 PatternDef = nullptr;
Richard Smith3f6865a82016-08-23 21:12:54 +00003989 }
Douglas Gregor24c332b2009-05-14 21:06:31 +00003990
Vassil Vassilevb21ee082016-08-18 22:01:25 +00003991 // FIXME: We need to track the instantiation stack in order to know which
3992 // definitions should be visible within this instantiation.
3993 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function,
3994 Function->getInstantiatedFromMemberFunction(),
Richard Smith6f4e2e02016-08-23 19:41:39 +00003995 PatternDecl, PatternDef, TSK,
3996 /*Complain*/DefinitionRequired)) {
3997 if (DefinitionRequired)
3998 Function->setInvalidDecl();
3999 else if (TSK == TSK_ExplicitInstantiationDefinition) {
4000 // Try again at the end of the translation unit (at which point a
4001 // definition will be required).
4002 assert(!Recursive);
Sunil Srivastava15ed2922017-06-20 22:08:44 +00004003 Function->setInstantiationIsPending(true);
Richard Smith6f4e2e02016-08-23 19:41:39 +00004004 PendingInstantiations.push_back(
4005 std::make_pair(Function, PointOfInstantiation));
4006 } else if (TSK == TSK_ImplicitInstantiation) {
Nick Lewycky2adab1b2018-01-02 19:10:12 +00004007 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004008 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
Richard Smith6f4e2e02016-08-23 19:41:39 +00004009 Diag(PointOfInstantiation, diag::warn_func_template_missing)
4010 << Function;
4011 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
4012 if (getLangOpts().CPlusPlus11)
4013 Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
4014 << Function;
4015 }
4016 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +00004017
Richard Smith6f4e2e02016-08-23 19:41:39 +00004018 return;
4019 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +00004020
Francois Pichet1c229c02011-04-22 22:18:13 +00004021 // Postpone late parsed template instantiations.
Alexis Hunt23f6b832011-05-27 20:00:14 +00004022 if (PatternDecl->isLateTemplateParsed() &&
Nick Lewycky610128e2011-05-12 03:51:24 +00004023 !LateTemplateParser) {
Sunil Srivastava15ed2922017-06-20 22:08:44 +00004024 Function->setInstantiationIsPending(true);
Reid Kleckner24bd88c2018-03-26 18:22:47 +00004025 LateParsedInstantiations.push_back(
4026 std::make_pair(Function, PointOfInstantiation));
Francois Pichet1c229c02011-04-22 22:18:13 +00004027 return;
4028 }
4029
Nico Weberae4bb8c2014-08-15 23:21:41 +00004030 // If we're performing recursive template instantiation, create our own
4031 // queue of pending implicit instantiations that we will instantiate later,
4032 // while we're still within our own instantiation context.
4033 // This has to happen before LateTemplateParser below is called, so that
4034 // it marks vtables used in late parsed templates as used.
Richard Smith4f3e3812017-05-20 01:36:41 +00004035 GlobalEagerInstantiationScope GlobalInstantiations(*this,
4036 /*Enabled=*/Recursive);
4037 LocalEagerInstantiationScope LocalInstantiations(*this);
Nico Weberae4bb8c2014-08-15 23:21:41 +00004038
David Majnemerf0a84f22013-08-16 08:29:13 +00004039 // Call the LateTemplateParser callback if there is a need to late parse
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004040 // a templated function definition.
Alexis Hunt23f6b832011-05-27 20:00:14 +00004041 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
Francois Pichet1c229c02011-04-22 22:18:13 +00004042 LateTemplateParser) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00004043 // FIXME: Optimize to allow individual templates to be deserialized.
4044 if (PatternDecl->isFromASTFile())
4045 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
4046
Justin Lebar28f09c52016-10-10 16:26:08 +00004047 auto LPTIter = LateParsedTemplateMap.find(PatternDecl);
4048 assert(LPTIter != LateParsedTemplateMap.end() &&
4049 "missing LateParsedTemplate");
4050 LateTemplateParser(OpaqueParser, *LPTIter->second);
Francois Pichet1c229c02011-04-22 22:18:13 +00004051 Pattern = PatternDecl->getBody(PatternDecl);
4052 }
4053
Richard Smith6f4e2e02016-08-23 19:41:39 +00004054 // Note, we should never try to instantiate a deleted function template.
Ilya Biryukova27eca22017-12-20 14:32:38 +00004055 assert((Pattern || PatternDecl->isDefaulted() ||
4056 PatternDecl->hasSkippedBody()) &&
Richard Smith6f4e2e02016-08-23 19:41:39 +00004057 "unexpected kind of function template definition");
Douglas Gregor24c332b2009-05-14 21:06:31 +00004058
Richard Smith2a7d4812013-05-04 07:00:32 +00004059 // C++1y [temp.explicit]p10:
4060 // Except for inline functions, declarations with types deduced from their
4061 // initializer or return value, and class template specializations, other
4062 // explicit instantiation declarations have the effect of suppressing the
4063 // implicit instantiation of the entity to which they refer.
Vassil Vassilevb21ee082016-08-18 22:01:25 +00004064 if (TSK == TSK_ExplicitInstantiationDeclaration &&
Richard Smith2a7d4812013-05-04 07:00:32 +00004065 !PatternDecl->isInlined() &&
Alp Toker314cc812014-01-25 16:55:45 +00004066 !PatternDecl->getReturnType()->getContainedAutoType())
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00004067 return;
Mike Stump11289f42009-09-09 15:08:12 +00004068
Richard Smith195d8ef2014-05-29 03:15:31 +00004069 if (PatternDecl->isInlined()) {
4070 // Function, and all later redeclarations of it (from imported modules,
4071 // for instance), are now implicitly inline.
4072 for (auto *D = Function->getMostRecentDecl(); /**/;
4073 D = D->getPreviousDecl()) {
4074 D->setImplicitlyInline();
4075 if (D == Function)
4076 break;
4077 }
4078 }
Richard Smithf3814ad2013-01-25 00:08:28 +00004079
Douglas Gregor85673582009-05-18 17:01:57 +00004080 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
Richard Smith54f18e82016-08-31 02:15:21 +00004081 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004082 return;
Jordan Rose1e879d82018-03-23 00:07:18 +00004083 PrettyDeclStackTraceEntry CrashInfo(Context, Function, SourceLocation(),
Richard Smithe19b95d2016-05-26 20:23:13 +00004084 "instantiating function definition");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004085
Vassil Vassilevb21ee082016-08-18 22:01:25 +00004086 // The instantiation is visible here, even if it was first declared in an
4087 // unimported module.
Richard Smith90dc5252017-06-23 01:04:34 +00004088 Function->setVisibleDespiteOwningModule();
Vassil Vassilevb21ee082016-08-18 22:01:25 +00004089
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00004090 // Copy the inner loc start from the pattern.
4091 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
4092
Faisal Valid143a0c2017-04-01 21:30:49 +00004093 EnterExpressionEvaluationContext EvalContext(
4094 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
Douglas Gregor67da0d92009-05-15 17:59:04 +00004095
Douglas Gregorb4850462009-05-14 23:26:13 +00004096 // Introduce a new scope where local variable instantiations will be
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004097 // recorded, unless we're actually a member function within a local
4098 // class, in which case we need to merge our results with the parent
4099 // scope (of the enclosing function).
4100 bool MergeWithParentScope = false;
4101 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
4102 MergeWithParentScope = Rec->isLocalClass();
4103
4104 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump11289f42009-09-09 15:08:12 +00004105
Richard Smithbd305122012-12-11 01:14:52 +00004106 if (PatternDecl->isDefaulted())
Alexis Hunt61ae8d32011-05-23 23:14:04 +00004107 SetDeclDefaulted(Function, PatternDecl->getLocation());
Richard Smithbd305122012-12-11 01:14:52 +00004108 else {
Richard Smithcc928662014-10-17 20:37:29 +00004109 MultiLevelTemplateArgumentList TemplateArgs =
4110 getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl);
4111
4112 // Substitute into the qualifier; we can get a substitution failure here
4113 // through evil use of alias templates.
4114 // FIXME: Is CurContext correct for this? Should we go to the (instantiation
4115 // of the) lexical context of the pattern?
4116 SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
4117
Craig Topperc3ec1492014-05-26 06:22:03 +00004118 ActOnStartOfFunctionDef(nullptr, Function);
Richard Smithbd305122012-12-11 01:14:52 +00004119
4120 // Enter the scope of this instantiation. We don't use
4121 // PushDeclContext because we don't have a scope.
4122 Sema::ContextRAII savedContext(*this, Function);
4123
Richard Smith2e321552014-11-12 02:00:47 +00004124 if (addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
4125 TemplateArgs))
4126 return;
Richard Smithbd305122012-12-11 01:14:52 +00004127
Ilya Biryukov0ee4a082018-03-14 13:18:30 +00004128 StmtResult Body;
Ilya Biryukova27eca22017-12-20 14:32:38 +00004129 if (PatternDecl->hasSkippedBody()) {
4130 ActOnSkippedFunctionBody(Function);
Ilya Biryukov0ee4a082018-03-14 13:18:30 +00004131 Body = nullptr;
Ilya Biryukova27eca22017-12-20 14:32:38 +00004132 } else {
Ilya Biryukov95f0d322017-12-28 13:05:46 +00004133 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) {
4134 // If this is a constructor, instantiate the member initializers.
4135 InstantiateMemInitializers(Ctor, cast<CXXConstructorDecl>(PatternDecl),
4136 TemplateArgs);
4137
4138 // If this is an MS ABI dllexport default constructor, instantiate any
4139 // default arguments.
4140 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4141 Ctor->isDefaultConstructor()) {
4142 InstantiateDefaultCtorDefaultArgs(*this, Ctor);
4143 }
4144 }
4145
Ilya Biryukova27eca22017-12-20 14:32:38 +00004146 // Instantiate the function body.
Ilya Biryukov0ee4a082018-03-14 13:18:30 +00004147 Body = SubstStmt(Pattern, TemplateArgs);
Alexis Hunt61ae8d32011-05-23 23:14:04 +00004148
Ilya Biryukova27eca22017-12-20 14:32:38 +00004149 if (Body.isInvalid())
4150 Function->setInvalidDecl();
Ilya Biryukova27eca22017-12-20 14:32:38 +00004151 }
Ilya Biryukov0ee4a082018-03-14 13:18:30 +00004152 // FIXME: finishing the function body while in an expression evaluation
4153 // context seems wrong. Investigate more.
4154 ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true);
Richard Smithbd305122012-12-11 01:14:52 +00004155
4156 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
4157
Richard Smithd28ac5b2014-03-22 23:33:22 +00004158 if (auto *Listener = getASTMutationListener())
4159 Listener->FunctionDefinitionInstantiated(Function);
Richard Smith0ac1b8f2014-03-22 01:43:32 +00004160
Richard Smithbd305122012-12-11 01:14:52 +00004161 savedContext.pop();
Mike Stump11289f42009-09-09 15:08:12 +00004162 }
4163
Douglas Gregor28ad4b52009-05-26 20:50:29 +00004164 DeclGroupRef DG(Function);
4165 Consumer.HandleTopLevelDecl(DG);
Mike Stump11289f42009-09-09 15:08:12 +00004166
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004167 // This class may have local implicit instantiations that need to be
4168 // instantiation within this scope.
Richard Smith4f3e3812017-05-20 01:36:41 +00004169 LocalInstantiations.perform();
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004170 Scope.Exit();
Richard Smith4f3e3812017-05-20 01:36:41 +00004171 GlobalInstantiations.perform();
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00004172}
4173
Larisse Voufo39a1e502013-08-06 01:03:05 +00004174VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
4175 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
4176 const TemplateArgumentList &TemplateArgList,
4177 const TemplateArgumentListInfo &TemplateArgsInfo,
4178 SmallVectorImpl<TemplateArgument> &Converted,
4179 SourceLocation PointOfInstantiation, void *InsertPos,
4180 LateInstantiatedAttrVec *LateAttrs,
4181 LocalInstantiationScope *StartingScope) {
4182 if (FromVar->isInvalidDecl())
Craig Topperc3ec1492014-05-26 06:22:03 +00004183 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004184
4185 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
Alp Tokerd4a72d52013-10-08 08:09:04 +00004186 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00004187 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004188
4189 MultiLevelTemplateArgumentList TemplateArgLists;
4190 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
4191
Richard Smith8809a0c2013-09-27 20:14:12 +00004192 // Instantiate the first declaration of the variable template: for a partial
4193 // specialization of a static data member template, the first declaration may
4194 // or may not be the declaration in the class; if it's in the class, we want
4195 // to instantiate a member in the class (a declaration), and if it's outside,
4196 // we want to instantiate a definition.
Richard Smithbeef3452014-01-16 23:39:20 +00004197 //
4198 // If we're instantiating an explicitly-specialized member template or member
4199 // partial specialization, don't do this. The member specialization completely
4200 // replaces the original declaration in this case.
4201 bool IsMemberSpec = false;
4202 if (VarTemplatePartialSpecializationDecl *PartialSpec =
4203 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar))
4204 IsMemberSpec = PartialSpec->isMemberSpecialization();
4205 else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate())
4206 IsMemberSpec = FromTemplate->isMemberSpecialization();
4207 if (!IsMemberSpec)
4208 FromVar = FromVar->getFirstDecl();
Richard Smith8809a0c2013-09-27 20:14:12 +00004209
Manuel Klimek5843add2013-09-30 13:29:01 +00004210 MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
4211 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
4212 MultiLevelList);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004213
4214 // TODO: Set LateAttrs and StartingScope ...
4215
4216 return cast_or_null<VarTemplateSpecializationDecl>(
4217 Instantiator.VisitVarTemplateSpecializationDecl(
4218 VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
4219}
4220
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004221/// Instantiates a variable template specialization by completing it
Larisse Voufo39a1e502013-08-06 01:03:05 +00004222/// with appropriate type information and initializer.
4223VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
4224 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
4225 const MultiLevelTemplateArgumentList &TemplateArgs) {
Richard Smith435e6472017-12-02 02:48:42 +00004226 assert(PatternDecl->isThisDeclarationADefinition() &&
4227 "don't have a definition to instantiate from");
Larisse Voufo39a1e502013-08-06 01:03:05 +00004228
4229 // Do substitution on the type of the declaration
4230 TypeSourceInfo *DI =
Richard Smith8809a0c2013-09-27 20:14:12 +00004231 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00004232 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
4233 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00004234 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004235
4236 // Update the type of this variable template specialization.
4237 VarSpec->setType(DI->getType());
4238
Richard Smith435e6472017-12-02 02:48:42 +00004239 // Convert the declaration into a definition now.
4240 VarSpec->setCompleteDefinition();
4241
Larisse Voufo39a1e502013-08-06 01:03:05 +00004242 // Instantiate the initializer.
4243 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
4244
4245 return VarSpec;
4246}
4247
4248/// BuildVariableInstantiation - Used after a new variable has been created.
4249/// Sets basic variable data and decides whether to postpone the
4250/// variable instantiation.
4251void Sema::BuildVariableInstantiation(
4252 VarDecl *NewVar, VarDecl *OldVar,
4253 const MultiLevelTemplateArgumentList &TemplateArgs,
Richard Smith541b38b2013-09-20 01:15:31 +00004254 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
4255 LocalInstantiationScope *StartingScope,
Larisse Voufo72caf2b2013-08-22 00:59:14 +00004256 bool InstantiatingVarTemplate) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004257
Richard Smith541b38b2013-09-20 01:15:31 +00004258 // If we are instantiating a local extern declaration, the
4259 // instantiation belongs lexically to the containing function.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004260 // If we are instantiating a static data member defined
4261 // out-of-line, the instantiation will have the same lexical
4262 // context (which will be a namespace scope) as the template.
Richard Smith541b38b2013-09-20 01:15:31 +00004263 if (OldVar->isLocalExternDecl()) {
4264 NewVar->setLocalExternDecl();
4265 NewVar->setLexicalDeclContext(Owner);
4266 } else if (OldVar->isOutOfLine())
Larisse Voufo39a1e502013-08-06 01:03:05 +00004267 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
4268 NewVar->setTSCSpec(OldVar->getTSCSpec());
4269 NewVar->setInitStyle(OldVar->getInitStyle());
4270 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
George Karpenkovec38cf72018-03-29 00:56:24 +00004271 NewVar->setObjCForDecl(OldVar->isObjCForDecl());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004272 NewVar->setConstexpr(OldVar->isConstexpr());
Richard Smithbb13c9a2013-09-28 04:02:39 +00004273 NewVar->setInitCapture(OldVar->isInitCapture());
Richard Smith1c34fb72013-08-13 18:18:50 +00004274 NewVar->setPreviousDeclInSameBlockScope(
4275 OldVar->isPreviousDeclInSameBlockScope());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004276 NewVar->setAccess(OldVar->getAccess());
4277
Richard Smith0b551192013-09-23 23:12:22 +00004278 if (!OldVar->isStaticDataMember()) {
Rafael Espindolae4865d22013-10-23 16:46:34 +00004279 if (OldVar->isUsed(false))
4280 NewVar->setIsUsed();
Larisse Voufo39a1e502013-08-06 01:03:05 +00004281 NewVar->setReferenced(OldVar->isReferenced());
4282 }
4283
4284 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
4285
Richard Smith541b38b2013-09-20 01:15:31 +00004286 LookupResult Previous(
4287 *this, NewVar->getDeclName(), NewVar->getLocation(),
4288 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
4289 : Sema::LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00004290 NewVar->isLocalExternDecl() ? Sema::ForExternalRedeclaration
4291 : forRedeclarationInCurContext());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004292
Argyrios Kyrtzidis91486222013-11-27 08:34:14 +00004293 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
4294 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
4295 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
Richard Smith1c34fb72013-08-13 18:18:50 +00004296 // We have a previous declaration. Use that one, so we merge with the
4297 // right type.
4298 if (NamedDecl *NewPrev = FindInstantiatedDecl(
4299 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
4300 Previous.addDecl(NewPrev);
4301 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
4302 OldVar->hasLinkage())
Larisse Voufo39a1e502013-08-06 01:03:05 +00004303 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
Larisse Voufo72caf2b2013-08-22 00:59:14 +00004304 CheckVariableDeclaration(NewVar, Previous);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004305
Richard Smith541b38b2013-09-20 01:15:31 +00004306 if (!InstantiatingVarTemplate) {
4307 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
4308 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
Larisse Voufo39a1e502013-08-06 01:03:05 +00004309 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
Richard Smith541b38b2013-09-20 01:15:31 +00004310 }
4311
4312 if (!OldVar->isOutOfLine()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004313 if (NewVar->getDeclContext()->isFunctionOrMethod())
4314 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
4315 }
4316
4317 // Link instantiations of static data members back to the template from
4318 // which they were instantiated.
Larisse Voufo72caf2b2013-08-22 00:59:14 +00004319 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate)
Larisse Voufo39a1e502013-08-06 01:03:05 +00004320 NewVar->setInstantiationOfStaticDataMember(OldVar,
4321 TSK_ImplicitInstantiation);
4322
David Majnemerdbc0c8f2013-12-04 09:01:55 +00004323 // Forward the mangling number from the template to the instantiated decl.
4324 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
David Majnemer2206bf52014-03-05 08:57:59 +00004325 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
David Majnemerdbc0c8f2013-12-04 09:01:55 +00004326
Richard Smith62f19e72016-06-25 00:15:56 +00004327 // Delay instantiation of the initializer for variable templates or inline
4328 // static data members until a definition of the variable is needed. We need
4329 // it right away if the type contains 'auto'.
Richard Smithd292b242014-03-16 01:00:40 +00004330 if ((!isa<VarTemplateSpecializationDecl>(NewVar) &&
Richard Smith62f19e72016-06-25 00:15:56 +00004331 !InstantiatingVarTemplate &&
Richard Smith93ee9ca2018-01-10 23:08:26 +00004332 !(OldVar->isInline() && OldVar->isThisDeclarationADefinition() &&
4333 !NewVar->isThisDeclarationADefinition())) ||
Richard Smithd292b242014-03-16 01:00:40 +00004334 NewVar->getType()->isUndeducedType())
Larisse Voufo39a1e502013-08-06 01:03:05 +00004335 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
4336
4337 // Diagnose unused local variables with dependent types, where the diagnostic
4338 // will have been deferred.
4339 if (!NewVar->isInvalidDecl() &&
Nico Weber72889432014-09-06 01:25:55 +00004340 NewVar->getDeclContext()->isFunctionOrMethod() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004341 OldVar->getType()->isDependentType())
4342 DiagnoseUnusedDecl(NewVar);
4343}
4344
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004345/// Instantiate the initializer of a variable.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004346void Sema::InstantiateVariableInitializer(
4347 VarDecl *Var, VarDecl *OldVar,
4348 const MultiLevelTemplateArgumentList &TemplateArgs) {
Richard Smith891fc7f2017-12-05 01:31:47 +00004349 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
4350 L->VariableDefinitionInstantiated(Var);
4351
Richard Smith62f19e72016-06-25 00:15:56 +00004352 // We propagate the 'inline' flag with the initializer, because it
4353 // would otherwise imply that the variable is a definition for a
4354 // non-static data member.
4355 if (OldVar->isInlineSpecified())
4356 Var->setInlineSpecified();
4357 else if (OldVar->isInline())
4358 Var->setImplicitlyInline();
Larisse Voufo39a1e502013-08-06 01:03:05 +00004359
Larisse Voufo39a1e502013-08-06 01:03:05 +00004360 if (OldVar->getInit()) {
Richard Smithc95d2c52017-09-22 04:25:05 +00004361 EnterExpressionEvaluationContext Evaluated(
4362 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, Var);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004363
4364 // Instantiate the initializer.
Akira Hatanakab87faff2016-04-28 23:50:12 +00004365 ExprResult Init;
4366
4367 {
4368 ContextRAII SwitchContext(*this, Var->getDeclContext());
4369 Init = SubstInitializer(OldVar->getInit(), TemplateArgs,
4370 OldVar->getInitStyle() == VarDecl::CallInit);
4371 }
4372
Larisse Voufo39a1e502013-08-06 01:03:05 +00004373 if (!Init.isInvalid()) {
Hans Wennborg91ebe6e2014-06-10 00:55:51 +00004374 Expr *InitExpr = Init.get();
4375
Richard Smith95b83e92014-07-10 20:53:43 +00004376 if (Var->hasAttr<DLLImportAttr>() &&
4377 (!InitExpr ||
4378 !InitExpr->isConstantInitializer(getASTContext(), false))) {
Hans Wennborg91ebe6e2014-06-10 00:55:51 +00004379 // Do not dynamically initialize dllimport variables.
Hans Wennborg91ebe6e2014-06-10 00:55:51 +00004380 } else if (InitExpr) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004381 bool DirectInit = OldVar->isDirectInit();
Richard Smith3beb7c62017-01-12 02:27:38 +00004382 AddInitializerToDecl(Var, InitExpr, DirectInit);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004383 } else
Richard Smith3beb7c62017-01-12 02:27:38 +00004384 ActOnUninitializedDecl(Var);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004385 } else {
4386 // FIXME: Not too happy about invalidating the declaration
4387 // because of a bogus initializer.
4388 Var->setInvalidDecl();
4389 }
Richard Smith54f18e82016-08-31 02:15:21 +00004390 } else {
George Burgess IV18b28a82018-03-20 03:27:44 +00004391 // `inline` variables are a definition and declaration all in one; we won't
4392 // pick up an initializer from anywhere else.
4393 if (Var->isStaticDataMember() && !Var->isInline()) {
Richard Smith54f18e82016-08-31 02:15:21 +00004394 if (!Var->isOutOfLine())
4395 return;
4396
4397 // If the declaration inside the class had an initializer, don't add
4398 // another one to the out-of-line definition.
4399 if (OldVar->getFirstDecl()->hasInit())
4400 return;
4401 }
4402
4403 // We'll add an initializer to a for-range declaration later.
George Karpenkovec38cf72018-03-29 00:56:24 +00004404 if (Var->isCXXForRangeDecl() || Var->isObjCForDecl())
Richard Smith54f18e82016-08-31 02:15:21 +00004405 return;
4406
Richard Smith3beb7c62017-01-12 02:27:38 +00004407 ActOnUninitializedDecl(Var);
Richard Smith54f18e82016-08-31 02:15:21 +00004408 }
Artem Beleviche9fa53a2018-06-06 22:37:25 +00004409
4410 if (getLangOpts().CUDA)
4411 checkAllowedCUDAInitializer(Var);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004412}
4413
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004414/// Instantiate the definition of the given variable from its
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00004415/// template.
4416///
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004417/// \param PointOfInstantiation the point at which the instantiation was
4418/// required. Note that this is not precisely a "point of instantiation"
Richard Smith891fc7f2017-12-05 01:31:47 +00004419/// for the variable, but it's close.
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004420///
Richard Smith891fc7f2017-12-05 01:31:47 +00004421/// \param Var the already-instantiated declaration of a templated variable.
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004422///
4423/// \param Recursive if true, recursively instantiates any functions that
4424/// are required by this instantiation.
Douglas Gregora8b89d22009-10-15 14:05:49 +00004425///
4426/// \param DefinitionRequired if true, then we are performing an explicit
Richard Smith891fc7f2017-12-05 01:31:47 +00004427/// instantiation where a definition of the variable is required. Complain
4428/// if there is no such definition.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004429void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
4430 VarDecl *Var, bool Recursive,
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00004431 bool DefinitionRequired, bool AtEndOfTU) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004432 if (Var->isInvalidDecl())
4433 return;
Mike Stump11289f42009-09-09 15:08:12 +00004434
Larisse Voufo39a1e502013-08-06 01:03:05 +00004435 VarTemplateSpecializationDecl *VarSpec =
4436 dyn_cast<VarTemplateSpecializationDecl>(Var);
Craig Topperc3ec1492014-05-26 06:22:03 +00004437 VarDecl *PatternDecl = nullptr, *Def = nullptr;
Richard Smith8809a0c2013-09-27 20:14:12 +00004438 MultiLevelTemplateArgumentList TemplateArgs =
4439 getTemplateInstantiationArgs(Var);
Mike Stump11289f42009-09-09 15:08:12 +00004440
Larisse Voufo39a1e502013-08-06 01:03:05 +00004441 if (VarSpec) {
Richard Smith8809a0c2013-09-27 20:14:12 +00004442 // If this is a variable template specialization, make sure that it is
4443 // non-dependent, then find its instantiation pattern.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004444 bool InstantiationDependent = false;
4445 assert(!TemplateSpecializationType::anyDependentTemplateArguments(
4446 VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
4447 "Only instantiate variable template specializations that are "
4448 "not type-dependent");
Larisse Voufo4154f462013-08-06 03:57:41 +00004449 (void)InstantiationDependent;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004450
Richard Smith8809a0c2013-09-27 20:14:12 +00004451 // Find the variable initialization that we'll be substituting. If the
4452 // pattern was instantiated from a member template, look back further to
4453 // find the real pattern.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004454 assert(VarSpec->getSpecializedTemplate() &&
4455 "Specialization without specialized template?");
4456 llvm::PointerUnion<VarTemplateDecl *,
4457 VarTemplatePartialSpecializationDecl *> PatternPtr =
4458 VarSpec->getSpecializedTemplateOrPartial();
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00004459 if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00004460 VarTemplatePartialSpecializationDecl *Tmpl =
4461 PatternPtr.get<VarTemplatePartialSpecializationDecl *>();
4462 while (VarTemplatePartialSpecializationDecl *From =
4463 Tmpl->getInstantiatedFromMember()) {
4464 if (Tmpl->isMemberSpecialization())
4465 break;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00004466
Richard Smith8809a0c2013-09-27 20:14:12 +00004467 Tmpl = From;
4468 }
4469 PatternDecl = Tmpl;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00004470 } else {
Richard Smith8809a0c2013-09-27 20:14:12 +00004471 VarTemplateDecl *Tmpl = PatternPtr.get<VarTemplateDecl *>();
4472 while (VarTemplateDecl *From =
4473 Tmpl->getInstantiatedFromMemberTemplate()) {
4474 if (Tmpl->isMemberSpecialization())
4475 break;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00004476
Richard Smith8809a0c2013-09-27 20:14:12 +00004477 Tmpl = From;
4478 }
4479 PatternDecl = Tmpl->getTemplatedDecl();
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00004480 }
Richard Smith8809a0c2013-09-27 20:14:12 +00004481
4482 // If this is a static data member template, there might be an
4483 // uninstantiated initializer on the declaration. If so, instantiate
4484 // it now.
Richard Smith891fc7f2017-12-05 01:31:47 +00004485 //
4486 // FIXME: This largely duplicates what we would do below. The difference
4487 // is that along this path we may instantiate an initializer from an
4488 // in-class declaration of the template and instantiate the definition
4489 // from a separate out-of-class definition.
Richard Smith8809a0c2013-09-27 20:14:12 +00004490 if (PatternDecl->isStaticDataMember() &&
Rafael Espindola8db352d2013-10-17 15:37:26 +00004491 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
Richard Smith8809a0c2013-09-27 20:14:12 +00004492 !Var->hasInit()) {
4493 // FIXME: Factor out the duplicated instantiation context setup/tear down
4494 // code here.
4495 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
Richard Smith54f18e82016-08-31 02:15:21 +00004496 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
Richard Smith8809a0c2013-09-27 20:14:12 +00004497 return;
Jordan Rose1e879d82018-03-23 00:07:18 +00004498 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
Richard Smithe19b95d2016-05-26 20:23:13 +00004499 "instantiating variable initializer");
Richard Smith8809a0c2013-09-27 20:14:12 +00004500
Richard Smithedbc6e92016-10-14 21:41:24 +00004501 // The instantiation is visible here, even if it was first declared in an
4502 // unimported module.
Richard Smith90dc5252017-06-23 01:04:34 +00004503 Var->setVisibleDespiteOwningModule();
Richard Smithedbc6e92016-10-14 21:41:24 +00004504
Richard Smith8809a0c2013-09-27 20:14:12 +00004505 // If we're performing recursive template instantiation, create our own
4506 // queue of pending implicit instantiations that we will instantiate
4507 // later, while we're still within our own instantiation context.
Richard Smith4f3e3812017-05-20 01:36:41 +00004508 GlobalEagerInstantiationScope GlobalInstantiations(*this,
4509 /*Enabled=*/Recursive);
Richard Smith8809a0c2013-09-27 20:14:12 +00004510 LocalInstantiationScope Local(*this);
Richard Smith4f3e3812017-05-20 01:36:41 +00004511 LocalEagerInstantiationScope LocalInstantiations(*this);
Richard Smith8809a0c2013-09-27 20:14:12 +00004512
4513 // Enter the scope of this instantiation. We don't use
4514 // PushDeclContext because we don't have a scope.
4515 ContextRAII PreviousContext(*this, Var->getDeclContext());
4516 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
4517 PreviousContext.pop();
4518
Richard Smith8809a0c2013-09-27 20:14:12 +00004519 // This variable may have local implicit instantiations that need to be
4520 // instantiated within this scope.
Richard Smith4f3e3812017-05-20 01:36:41 +00004521 LocalInstantiations.perform();
Richard Smith8809a0c2013-09-27 20:14:12 +00004522 Local.Exit();
Richard Smith4f3e3812017-05-20 01:36:41 +00004523 GlobalInstantiations.perform();
Richard Smith8809a0c2013-09-27 20:14:12 +00004524 }
4525
4526 // Find actual definition
4527 Def = PatternDecl->getDefinition(getASTContext());
4528 } else {
4529 // If this is a static data member, find its out-of-line definition.
4530 assert(Var->isStaticDataMember() && "not a static data member?");
4531 PatternDecl = Var->getInstantiatedFromStaticDataMember();
4532
4533 assert(PatternDecl && "data member was not instantiated from a template?");
4534 assert(PatternDecl->isStaticDataMember() && "not a static data member?");
Richard Smith62f19e72016-06-25 00:15:56 +00004535 Def = PatternDecl->getDefinition();
Larisse Voufo39a1e502013-08-06 01:03:05 +00004536 }
4537
Richard Smithedbc6e92016-10-14 21:41:24 +00004538 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
Richard Smith6739a102016-05-05 00:56:12 +00004539
Richard Smith8809a0c2013-09-27 20:14:12 +00004540 // If we don't have a definition of the variable template, we won't perform
4541 // any instantiation. Rather, we rely on the user to instantiate this
4542 // definition (or provide a specialization for it) in another translation
4543 // unit.
Richard Smithedbc6e92016-10-14 21:41:24 +00004544 if (!Def && !DefinitionRequired) {
4545 if (TSK == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth54080172010-08-25 08:44:16 +00004546 PendingInstantiations.push_back(
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004547 std::make_pair(Var, PointOfInstantiation));
Richard Smithedbc6e92016-10-14 21:41:24 +00004548 } else if (TSK == TSK_ImplicitInstantiation) {
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00004549 // Warn about missing definition at the end of translation unit.
Nick Lewycky2adab1b2018-01-02 19:10:12 +00004550 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004551 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00004552 Diag(PointOfInstantiation, diag::warn_var_template_missing)
4553 << Var;
4554 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
4555 if (getLangOpts().CPlusPlus11)
4556 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
4557 }
Richard Smithedbc6e92016-10-14 21:41:24 +00004558 return;
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004559 }
4560
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004561 }
4562
Richard Smithedbc6e92016-10-14 21:41:24 +00004563 // FIXME: We need to track the instantiation stack in order to know which
4564 // definitions should be visible within this instantiation.
4565 // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
4566 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var,
4567 /*InstantiatedFromMember*/false,
4568 PatternDecl, Def, TSK,
4569 /*Complain*/DefinitionRequired))
4570 return;
4571
Rafael Espindola189fa742012-03-05 10:54:55 +00004572
Douglas Gregor86d142a2009-10-08 07:24:58 +00004573 // Never instantiate an explicit specialization.
Rafael Espindola189fa742012-03-05 10:54:55 +00004574 if (TSK == TSK_ExplicitSpecialization)
Douglas Gregor86d142a2009-10-08 07:24:58 +00004575 return;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004576
Larisse Voufo39a1e502013-08-06 01:03:05 +00004577 // C++11 [temp.explicit]p10:
Richard Smith4309b662017-10-18 22:45:01 +00004578 // Except for inline functions, const variables of literal types, variables
4579 // of reference types, [...] explicit instantiation declarations
Larisse Voufo39a1e502013-08-06 01:03:05 +00004580 // have the effect of suppressing the implicit instantiation of the entity
4581 // to which they refer.
Richard Smith4309b662017-10-18 22:45:01 +00004582 if (TSK == TSK_ExplicitInstantiationDeclaration &&
4583 !Var->isUsableInConstantExpressions(getASTContext()))
Douglas Gregor86d142a2009-10-08 07:24:58 +00004584 return;
Mike Stump11289f42009-09-09 15:08:12 +00004585
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00004586 // Make sure to pass the instantiated variable to the consumer at the end.
4587 struct PassToConsumerRAII {
4588 ASTConsumer &Consumer;
4589 VarDecl *Var;
4590
4591 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
4592 : Consumer(Consumer), Var(Var) { }
4593
4594 ~PassToConsumerRAII() {
Richard Smith8809a0c2013-09-27 20:14:12 +00004595 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00004596 }
4597 } PassToConsumerRAII(Consumer, Var);
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00004598
Reid Klecknere07140e2015-04-15 01:08:06 +00004599 // If we already have a definition, we're done.
4600 if (VarDecl *Def = Var->getDefinition()) {
4601 // We may be explicitly instantiating something we've already implicitly
4602 // instantiated.
4603 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
4604 PointOfInstantiation);
Richard Smith8809a0c2013-09-27 20:14:12 +00004605 return;
Reid Klecknere07140e2015-04-15 01:08:06 +00004606 }
Douglas Gregor57d4f972011-06-03 03:35:07 +00004607
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004608 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
Richard Smith54f18e82016-08-31 02:15:21 +00004609 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004610 return;
Jordan Rose1e879d82018-03-23 00:07:18 +00004611 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
Richard Smithe19b95d2016-05-26 20:23:13 +00004612 "instantiating variable definition");
Mike Stump11289f42009-09-09 15:08:12 +00004613
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004614 // If we're performing recursive template instantiation, create our own
4615 // queue of pending implicit instantiations that we will instantiate later,
4616 // while we're still within our own instantiation context.
Richard Smith4f3e3812017-05-20 01:36:41 +00004617 GlobalEagerInstantiationScope GlobalInstantiations(*this,
4618 /*Enabled=*/Recursive);
Mike Stump11289f42009-09-09 15:08:12 +00004619
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004620 // Enter the scope of this instantiation. We don't use
4621 // PushDeclContext because we don't have a scope.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004622 ContextRAII PreviousContext(*this, Var->getDeclContext());
Douglas Gregora86bc002012-02-16 21:36:18 +00004623 LocalInstantiationScope Local(*this);
John McCall2957e3e2011-02-14 20:37:25 +00004624
Richard Smith4f3e3812017-05-20 01:36:41 +00004625 LocalEagerInstantiationScope LocalInstantiations(*this);
4626
Larisse Voufo39a1e502013-08-06 01:03:05 +00004627 VarDecl *OldVar = Var;
Richard Smith62f19e72016-06-25 00:15:56 +00004628 if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
4629 // We're instantiating an inline static data member whose definition was
4630 // provided inside the class.
Richard Smith62f19e72016-06-25 00:15:56 +00004631 InstantiateVariableInitializer(Var, Def, TemplateArgs);
4632 } else if (!VarSpec) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004633 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Richard Smith8809a0c2013-09-27 20:14:12 +00004634 TemplateArgs));
Richard Smith62f19e72016-06-25 00:15:56 +00004635 } else if (Var->isStaticDataMember() &&
4636 Var->getLexicalDeclContext()->isRecord()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00004637 // We need to instantiate the definition of a static data member template,
4638 // and all we have is the in-class declaration of it. Instantiate a separate
4639 // declaration of the definition.
4640 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
4641 TemplateArgs);
4642 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
Craig Topperc3ec1492014-05-26 06:22:03 +00004643 VarSpec->getSpecializedTemplate(), Def, nullptr,
Richard Smith8809a0c2013-09-27 20:14:12 +00004644 VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
4645 if (Var) {
4646 llvm::PointerUnion<VarTemplateDecl *,
4647 VarTemplatePartialSpecializationDecl *> PatternPtr =
4648 VarSpec->getSpecializedTemplateOrPartial();
4649 if (VarTemplatePartialSpecializationDecl *Partial =
4650 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
4651 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
4652 Partial, &VarSpec->getTemplateInstantiationArgs());
4653
4654 // Merge the definition with the declaration.
4655 LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
Richard Smithbecb92d2017-10-10 22:33:17 +00004656 LookupOrdinaryName, forRedeclarationInCurContext());
Richard Smith8809a0c2013-09-27 20:14:12 +00004657 R.addDecl(OldVar);
4658 MergeVarDecl(Var, R);
4659
4660 // Attach the initializer.
4661 InstantiateVariableInitializer(Var, Def, TemplateArgs);
4662 }
4663 } else
4664 // Complete the existing variable's definition with an appropriately
4665 // substituted type and initializer.
4666 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004667
4668 PreviousContext.pop();
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004669
4670 if (Var) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004671 PassToConsumerRAII.Var = Var;
Richard Smith8809a0c2013-09-27 20:14:12 +00004672 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
4673 OldVar->getPointOfInstantiation());
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004674 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004675
4676 // This variable may have local implicit instantiations that need to be
4677 // instantiated within this scope.
Richard Smith4f3e3812017-05-20 01:36:41 +00004678 LocalInstantiations.perform();
Douglas Gregora86bc002012-02-16 21:36:18 +00004679 Local.Exit();
Richard Smith4f3e3812017-05-20 01:36:41 +00004680 GlobalInstantiations.perform();
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00004681}
Douglas Gregor51783312009-05-27 05:35:12 +00004682
Anders Carlsson70553942009-08-29 05:16:22 +00004683void
4684Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
4685 const CXXConstructorDecl *Tmpl,
4686 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00004687
Richard Trieu9becef62011-09-09 03:18:59 +00004688 SmallVector<CXXCtorInitializer*, 4> NewInits;
Richard Smith60f2e1e2012-09-25 00:23:05 +00004689 bool AnyErrors = Tmpl->isInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004690
Anders Carlsson70553942009-08-29 05:16:22 +00004691 // Instantiate all the initializers.
Aaron Ballman0ad78302014-03-13 17:34:31 +00004692 for (const auto *Init : Tmpl->inits()) {
Chandler Carruthf92bd8c2010-09-03 21:54:20 +00004693 // Only instantiate written initializers, let Sema re-construct implicit
4694 // ones.
4695 if (!Init->isWritten())
4696 continue;
4697
Douglas Gregor44e7df62011-01-04 00:32:56 +00004698 SourceLocation EllipsisLoc;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004699
Douglas Gregor44e7df62011-01-04 00:32:56 +00004700 if (Init->isPackExpansion()) {
4701 // This is a pack expansion. We should expand it now.
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004702 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
Nick Lewycky2c308502013-06-13 00:45:47 +00004703 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
Douglas Gregor44e7df62011-01-04 00:32:56 +00004704 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
Nick Lewycky2c308502013-06-13 00:45:47 +00004705 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
Douglas Gregor44e7df62011-01-04 00:32:56 +00004706 bool ShouldExpand = false;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00004707 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00004708 Optional<unsigned> NumExpansions;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004709 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004710 BaseTL.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00004711 Unexpanded,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004712 TemplateArgs, ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00004713 RetainExpansion,
Douglas Gregor44e7df62011-01-04 00:32:56 +00004714 NumExpansions)) {
4715 AnyErrors = true;
4716 New->setInvalidDecl();
4717 continue;
4718 }
4719 assert(ShouldExpand && "Partial instantiation of base initializer?");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004720
4721 // Loop over all of the arguments in the argument pack(s),
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004722 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00004723 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
4724
4725 // Instantiate the initializer.
Sebastian Redla9351792012-02-11 23:51:47 +00004726 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4727 /*CXXDirectInit=*/true);
4728 if (TempInit.isInvalid()) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00004729 AnyErrors = true;
4730 break;
4731 }
4732
4733 // Instantiate the base type.
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004734 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004735 TemplateArgs,
4736 Init->getSourceLocation(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004737 New->getDeclName());
4738 if (!BaseTInfo) {
4739 AnyErrors = true;
4740 break;
4741 }
4742
4743 // Build the initializer.
Sebastian Redla74948d2011-09-24 17:48:25 +00004744 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004745 BaseTInfo, TempInit.get(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004746 New->getParent(),
4747 SourceLocation());
4748 if (NewInit.isInvalid()) {
4749 AnyErrors = true;
4750 break;
4751 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004752
Douglas Gregor44e7df62011-01-04 00:32:56 +00004753 NewInits.push_back(NewInit.get());
Douglas Gregor44e7df62011-01-04 00:32:56 +00004754 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004755
Douglas Gregor44e7df62011-01-04 00:32:56 +00004756 continue;
4757 }
4758
Douglas Gregorb30f22b2010-03-02 07:38:39 +00004759 // Instantiate the initializer.
Sebastian Redla9351792012-02-11 23:51:47 +00004760 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4761 /*CXXDirectInit=*/true);
4762 if (TempInit.isInvalid()) {
Douglas Gregorb30f22b2010-03-02 07:38:39 +00004763 AnyErrors = true;
4764 continue;
Anders Carlsson70553942009-08-29 05:16:22 +00004765 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004766
Anders Carlsson70553942009-08-29 05:16:22 +00004767 MemInitResult NewInit;
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004768 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
4769 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
4770 TemplateArgs,
4771 Init->getSourceLocation(),
4772 New->getDeclName());
4773 if (!TInfo) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004774 AnyErrors = true;
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00004775 New->setInvalidDecl();
4776 continue;
4777 }
Sebastian Redla74948d2011-09-24 17:48:25 +00004778
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004779 if (Init->isBaseInitializer())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004780 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004781 New->getParent(), EllipsisLoc);
4782 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004783 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004784 cast<CXXRecordDecl>(CurContext->getParent()));
Anders Carlsson70553942009-08-29 05:16:22 +00004785 } else if (Init->isMemberInitializer()) {
Douglas Gregor55e6b312011-03-04 19:46:35 +00004786 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
Francois Pichetd583da02010-12-04 09:14:42 +00004787 Init->getMemberLocation(),
4788 Init->getMember(),
4789 TemplateArgs));
Douglas Gregor55e6b312011-03-04 19:46:35 +00004790 if (!Member) {
4791 AnyErrors = true;
4792 New->setInvalidDecl();
4793 continue;
4794 }
Mike Stump11289f42009-09-09 15:08:12 +00004795
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004796 NewInit = BuildMemberInitializer(Member, TempInit.get(),
Sebastian Redla74948d2011-09-24 17:48:25 +00004797 Init->getSourceLocation());
Francois Pichetd583da02010-12-04 09:14:42 +00004798 } else if (Init->isIndirectMemberInitializer()) {
4799 IndirectFieldDecl *IndirectMember =
Douglas Gregor55e6b312011-03-04 19:46:35 +00004800 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
Francois Pichetd583da02010-12-04 09:14:42 +00004801 Init->getMemberLocation(),
4802 Init->getIndirectMember(), TemplateArgs));
4803
Douglas Gregor55e6b312011-03-04 19:46:35 +00004804 if (!IndirectMember) {
4805 AnyErrors = true;
4806 New->setInvalidDecl();
Sebastian Redla74948d2011-09-24 17:48:25 +00004807 continue;
Douglas Gregor55e6b312011-03-04 19:46:35 +00004808 }
Sebastian Redla74948d2011-09-24 17:48:25 +00004809
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004810 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
Sebastian Redla74948d2011-09-24 17:48:25 +00004811 Init->getSourceLocation());
Anders Carlsson70553942009-08-29 05:16:22 +00004812 }
4813
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004814 if (NewInit.isInvalid()) {
4815 AnyErrors = true;
Anders Carlsson70553942009-08-29 05:16:22 +00004816 New->setInvalidDecl();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004817 } else {
Richard Trieu9becef62011-09-09 03:18:59 +00004818 NewInits.push_back(NewInit.get());
Anders Carlsson70553942009-08-29 05:16:22 +00004819 }
4820 }
Mike Stump11289f42009-09-09 15:08:12 +00004821
Anders Carlsson70553942009-08-29 05:16:22 +00004822 // Assign all the initializers to the new constructor.
John McCall48871652010-08-21 09:40:31 +00004823 ActOnMemInitializers(New,
Anders Carlsson70553942009-08-29 05:16:22 +00004824 /*FIXME: ColonLoc */
4825 SourceLocation(),
David Blaikie3fc2f912013-01-17 05:26:25 +00004826 NewInits,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004827 AnyErrors);
Anders Carlsson70553942009-08-29 05:16:22 +00004828}
4829
John McCall59660882009-08-29 08:11:13 +00004830// TODO: this could be templated if the various decl types used the
4831// same method name.
4832static bool isInstantiationOf(ClassTemplateDecl *Pattern,
4833 ClassTemplateDecl *Instance) {
4834 Pattern = Pattern->getCanonicalDecl();
4835
4836 do {
4837 Instance = Instance->getCanonicalDecl();
4838 if (Pattern == Instance) return true;
4839 Instance = Instance->getInstantiatedFromMemberTemplate();
4840 } while (Instance);
4841
4842 return false;
4843}
4844
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004845static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
4846 FunctionTemplateDecl *Instance) {
4847 Pattern = Pattern->getCanonicalDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004848
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004849 do {
4850 Instance = Instance->getCanonicalDecl();
4851 if (Pattern == Instance) return true;
4852 Instance = Instance->getInstantiatedFromMemberTemplate();
4853 } while (Instance);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004854
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004855 return false;
4856}
4857
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004858static bool
Douglas Gregor21610382009-10-29 00:04:11 +00004859isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
4860 ClassTemplatePartialSpecializationDecl *Instance) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004861 Pattern
Douglas Gregor21610382009-10-29 00:04:11 +00004862 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
4863 do {
4864 Instance = cast<ClassTemplatePartialSpecializationDecl>(
4865 Instance->getCanonicalDecl());
4866 if (Pattern == Instance)
4867 return true;
4868 Instance = Instance->getInstantiatedFromMember();
4869 } while (Instance);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004870
Douglas Gregor21610382009-10-29 00:04:11 +00004871 return false;
4872}
4873
John McCall59660882009-08-29 08:11:13 +00004874static bool isInstantiationOf(CXXRecordDecl *Pattern,
4875 CXXRecordDecl *Instance) {
4876 Pattern = Pattern->getCanonicalDecl();
4877
4878 do {
4879 Instance = Instance->getCanonicalDecl();
4880 if (Pattern == Instance) return true;
4881 Instance = Instance->getInstantiatedFromMemberClass();
4882 } while (Instance);
4883
4884 return false;
4885}
4886
4887static bool isInstantiationOf(FunctionDecl *Pattern,
4888 FunctionDecl *Instance) {
4889 Pattern = Pattern->getCanonicalDecl();
4890
4891 do {
4892 Instance = Instance->getCanonicalDecl();
4893 if (Pattern == Instance) return true;
4894 Instance = Instance->getInstantiatedFromMemberFunction();
4895 } while (Instance);
4896
4897 return false;
4898}
4899
4900static bool isInstantiationOf(EnumDecl *Pattern,
4901 EnumDecl *Instance) {
4902 Pattern = Pattern->getCanonicalDecl();
4903
4904 do {
4905 Instance = Instance->getCanonicalDecl();
4906 if (Pattern == Instance) return true;
4907 Instance = Instance->getInstantiatedFromMemberEnum();
4908 } while (Instance);
4909
4910 return false;
4911}
4912
John McCallb96ec562009-12-04 22:46:56 +00004913static bool isInstantiationOf(UsingShadowDecl *Pattern,
4914 UsingShadowDecl *Instance,
4915 ASTContext &C) {
Richard Smith32952e12014-10-14 02:00:47 +00004916 return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
4917 Pattern);
John McCallb96ec562009-12-04 22:46:56 +00004918}
4919
Richard Smith151c4562016-12-20 21:35:28 +00004920static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance,
John McCallb96ec562009-12-04 22:46:56 +00004921 ASTContext &C) {
Richard Smith32952e12014-10-14 02:00:47 +00004922 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
John McCallb96ec562009-12-04 22:46:56 +00004923}
4924
Richard Smith151c4562016-12-20 21:35:28 +00004925template<typename T>
4926static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other,
4927 ASTContext &Ctx) {
4928 // An unresolved using declaration can instantiate to an unresolved using
4929 // declaration, or to a using declaration or a using declaration pack.
4930 //
4931 // Multiple declarations can claim to be instantiated from an unresolved
4932 // using declaration if it's a pack expansion. We want the UsingPackDecl
4933 // in that case, not the individual UsingDecls within the pack.
4934 bool OtherIsPackExpansion;
4935 NamedDecl *OtherFrom;
4936 if (auto *OtherUUD = dyn_cast<T>(Other)) {
4937 OtherIsPackExpansion = OtherUUD->isPackExpansion();
4938 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD);
4939 } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) {
4940 OtherIsPackExpansion = true;
4941 OtherFrom = OtherUPD->getInstantiatedFromUsingDecl();
4942 } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) {
4943 OtherIsPackExpansion = false;
4944 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD);
4945 } else {
4946 return false;
4947 }
4948 return Pattern->isPackExpansion() == OtherIsPackExpansion &&
4949 declaresSameEntity(OtherFrom, Pattern);
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004950}
4951
John McCall59660882009-08-29 08:11:13 +00004952static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
4953 VarDecl *Instance) {
4954 assert(Instance->isStaticDataMember());
4955
4956 Pattern = Pattern->getCanonicalDecl();
4957
4958 do {
4959 Instance = Instance->getCanonicalDecl();
4960 if (Pattern == Instance) return true;
4961 Instance = Instance->getInstantiatedFromStaticDataMember();
4962 } while (Instance);
4963
4964 return false;
4965}
4966
John McCallb96ec562009-12-04 22:46:56 +00004967// Other is the prospective instantiation
4968// D is the prospective pattern
Douglas Gregor51783312009-05-27 05:35:12 +00004969static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Richard Smith151c4562016-12-20 21:35:28 +00004970 if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D))
4971 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
John McCalle61f2ba2009-11-18 02:36:19 +00004972
Richard Smith151c4562016-12-20 21:35:28 +00004973 if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D))
4974 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
Douglas Gregor51783312009-05-27 05:35:12 +00004975
Richard Smith151c4562016-12-20 21:35:28 +00004976 if (D->getKind() != Other->getKind())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004977 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004978
Richard Smithd8a9e372016-12-18 21:39:37 +00004979 if (auto *Record = dyn_cast<CXXRecordDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00004980 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump11289f42009-09-09 15:08:12 +00004981
Richard Smithd8a9e372016-12-18 21:39:37 +00004982 if (auto *Function = dyn_cast<FunctionDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00004983 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor51783312009-05-27 05:35:12 +00004984
Richard Smithd8a9e372016-12-18 21:39:37 +00004985 if (auto *Enum = dyn_cast<EnumDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00004986 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor51783312009-05-27 05:35:12 +00004987
Richard Smithd8a9e372016-12-18 21:39:37 +00004988 if (auto *Var = dyn_cast<VarDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00004989 if (Var->isStaticDataMember())
4990 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
4991
Richard Smithd8a9e372016-12-18 21:39:37 +00004992 if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00004993 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregorf3db0032009-08-28 22:03:51 +00004994
Richard Smithd8a9e372016-12-18 21:39:37 +00004995 if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other))
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004996 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
4997
Richard Smithd8a9e372016-12-18 21:39:37 +00004998 if (auto *PartialSpec =
4999 dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
Douglas Gregor21610382009-10-29 00:04:11 +00005000 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
5001 PartialSpec);
5002
Richard Smithd8a9e372016-12-18 21:39:37 +00005003 if (auto *Field = dyn_cast<FieldDecl>(Other)) {
Anders Carlsson5da84842009-09-01 04:26:58 +00005004 if (!Field->getDeclName()) {
5005 // This is an unnamed field.
Richard Smith32952e12014-10-14 02:00:47 +00005006 return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field),
5007 cast<FieldDecl>(D));
Anders Carlsson5da84842009-09-01 04:26:58 +00005008 }
5009 }
Mike Stump11289f42009-09-09 15:08:12 +00005010
Richard Smithd8a9e372016-12-18 21:39:37 +00005011 if (auto *Using = dyn_cast<UsingDecl>(Other))
John McCallb96ec562009-12-04 22:46:56 +00005012 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
5013
Richard Smithd8a9e372016-12-18 21:39:37 +00005014 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other))
John McCallb96ec562009-12-04 22:46:56 +00005015 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
5016
Richard Smithd8a9e372016-12-18 21:39:37 +00005017 return D->getDeclName() &&
5018 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
Douglas Gregor51783312009-05-27 05:35:12 +00005019}
5020
5021template<typename ForwardIterator>
Mike Stump11289f42009-09-09 15:08:12 +00005022static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor51783312009-05-27 05:35:12 +00005023 NamedDecl *D,
5024 ForwardIterator first,
5025 ForwardIterator last) {
5026 for (; first != last; ++first)
5027 if (isInstantiationOf(Ctx, D, *first))
5028 return cast<NamedDecl>(*first);
5029
Craig Topperc3ec1492014-05-26 06:22:03 +00005030 return nullptr;
Douglas Gregor51783312009-05-27 05:35:12 +00005031}
5032
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005033/// Finds the instantiation of the given declaration context
John McCallaa74a0c2009-08-28 07:59:38 +00005034/// within the current instantiation.
5035///
5036/// \returns NULL if there was an error
Douglas Gregora04f2ca2010-03-01 15:56:25 +00005037DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregor64621e62009-09-16 18:34:49 +00005038 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCallaa74a0c2009-08-28 07:59:38 +00005039 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Richard Smith4f440e32017-06-08 01:08:50 +00005040 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true);
John McCallaa74a0c2009-08-28 07:59:38 +00005041 return cast_or_null<DeclContext>(ID);
5042 } else return DC;
5043}
5044
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005045/// Find the instantiation of the given declaration within the
Douglas Gregorcd3a0972009-05-27 17:54:46 +00005046/// current instantiation.
Douglas Gregor51783312009-05-27 05:35:12 +00005047///
5048/// This routine is intended to be used when \p D is a declaration
5049/// referenced from within a template, that needs to mapped into the
5050/// corresponding declaration within an instantiation. For example,
5051/// given:
5052///
5053/// \code
5054/// template<typename T>
5055/// struct X {
5056/// enum Kind {
5057/// KnownValue = sizeof(T)
5058/// };
5059///
5060/// bool getKind() const { return KnownValue; }
5061/// };
5062///
5063/// template struct X<int>;
5064/// \endcode
5065///
Serge Pavloved5fe902013-07-10 04:59:14 +00005066/// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
5067/// \p EnumConstantDecl for \p KnownValue (which refers to
5068/// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
5069/// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
5070/// this mapping from within the instantiation of <tt>X<int></tt>.
Douglas Gregora04f2ca2010-03-01 15:56:25 +00005071NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Richard Smith4f440e32017-06-08 01:08:50 +00005072 const MultiLevelTemplateArgumentList &TemplateArgs,
5073 bool FindingInstantiatedContext) {
Douglas Gregor51783312009-05-27 05:35:12 +00005074 DeclContext *ParentDC = D->getDeclContext();
Fangrui Song6907ce22018-07-30 19:24:48 +00005075 // FIXME: Parmeters of pointer to functions (y below) that are themselves
Faisal Vali2cba1332013-10-23 06:44:28 +00005076 // parameters (p below) can have their ParentDC set to the translation-unit
Fangrui Song6907ce22018-07-30 19:24:48 +00005077 // - thus we can not consistently check if the ParentDC of such a parameter
Faisal Vali2cba1332013-10-23 06:44:28 +00005078 // is Dependent or/and a FunctionOrMethod.
Fangrui Song6907ce22018-07-30 19:24:48 +00005079 // For e.g. this code, during Template argument deduction tries to
Faisal Vali2cba1332013-10-23 06:44:28 +00005080 // find an instantiated decl for (T y) when the ParentDC for y is
Fangrui Song6907ce22018-07-30 19:24:48 +00005081 // the translation unit.
5082 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
Aaron Ballman36a53502014-01-16 13:03:14 +00005083 // float baz(float(*)()) { return 0.0; }
Faisal Vali2cba1332013-10-23 06:44:28 +00005084 // Foo(baz);
5085 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
5086 // it gets here, always has a FunctionOrMethod as its ParentDC??
5087 // For now:
5088 // - as long as we have a ParmVarDecl whose parent is non-dependent and
5089 // whose type is not instantiation dependent, do nothing to the decl
5090 // - otherwise find its instantiated decl.
5091 if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() &&
5092 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
5093 return D;
Rafael Espindola09b00e32013-10-23 04:12:23 +00005094 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregorb93971082010-02-05 19:54:12 +00005095 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Alexey Bataeve6aa4692018-09-13 16:54:05 +00005096 ((ParentDC->isFunctionOrMethod() ||
Michael Kruse251e1482019-02-01 20:25:04 +00005097 isa<OMPDeclareReductionDecl>(ParentDC) ||
5098 isa<OMPDeclareMapperDecl>(ParentDC)) &&
Alexey Bataeve6aa4692018-09-13 16:54:05 +00005099 ParentDC->isDependentContext()) ||
Douglas Gregora86bc002012-02-16 21:36:18 +00005100 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
Douglas Gregorf98d9b62009-05-27 17:07:49 +00005101 // D is a local of some kind. Look into the map of local
5102 // declarations to their instantiations.
Alexey Samsonov2c0aac22014-09-03 18:45:45 +00005103 if (CurrentInstantiationScope) {
5104 if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
5105 if (Decl *FD = Found->dyn_cast<Decl *>())
5106 return cast<NamedDecl>(FD);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005107
Alexey Samsonov2c0aac22014-09-03 18:45:45 +00005108 int PackIdx = ArgumentPackSubstitutionIndex;
5109 assert(PackIdx != -1 &&
5110 "found declaration pack but not pack expanding");
5111 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
5112 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
5113 }
Chris Lattnercab02a62011-02-17 20:34:02 +00005114 }
5115
Serge Pavlov7cd8f602013-07-15 06:14:07 +00005116 // If we're performing a partial substitution during template argument
5117 // deduction, we may not have values for template parameters yet. They
5118 // just map to themselves.
5119 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
5120 isa<TemplateTemplateParmDecl>(D))
5121 return D;
5122
Serge Pavlov074a5182013-08-10 12:00:21 +00005123 if (D->isInvalidDecl())
Craig Topperc3ec1492014-05-26 06:22:03 +00005124 return nullptr;
Serge Pavlov074a5182013-08-10 12:00:21 +00005125
Serge Pavlove7ad8312015-05-15 10:10:28 +00005126 // Normally this function only searches for already instantiated declaration
5127 // however we have to make an exclusion for local types used before
5128 // definition as in the code:
5129 //
5130 // template<typename T> void f1() {
5131 // void g1(struct x1);
5132 // struct x1 {};
5133 // }
5134 //
5135 // In this case instantiation of the type of 'g1' requires definition of
5136 // 'x1', which is defined later. Error recovery may produce an enum used
5137 // before definition. In these cases we need to instantiate relevant
5138 // declarations here.
5139 bool NeedInstantiate = false;
5140 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5141 NeedInstantiate = RD->isLocalClass();
5142 else
5143 NeedInstantiate = isa<EnumDecl>(D);
5144 if (NeedInstantiate) {
Serge Pavlov4c511742015-05-04 16:44:39 +00005145 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
5146 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
5147 return cast<TypeDecl>(Inst);
5148 }
5149
Chris Lattnercab02a62011-02-17 20:34:02 +00005150 // If we didn't find the decl, then we must have a label decl that hasn't
5151 // been found yet. Lazily instantiate it and return it now.
5152 assert(isa<LabelDecl>(D));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005153
Chris Lattnercab02a62011-02-17 20:34:02 +00005154 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
5155 assert(Inst && "Failed to instantiate label??");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005156
Chris Lattnercab02a62011-02-17 20:34:02 +00005157 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
5158 return cast<LabelDecl>(Inst);
Douglas Gregorf98d9b62009-05-27 17:07:49 +00005159 }
Douglas Gregor51783312009-05-27 05:35:12 +00005160
Larisse Voufo39a1e502013-08-06 01:03:05 +00005161 // For variable template specializations, update those that are still
5162 // type-dependent.
5163 if (VarTemplateSpecializationDecl *VarSpec =
5164 dyn_cast<VarTemplateSpecializationDecl>(D)) {
5165 bool InstantiationDependent = false;
5166 const TemplateArgumentListInfo &VarTemplateArgs =
5167 VarSpec->getTemplateArgsInfo();
5168 if (TemplateSpecializationType::anyDependentTemplateArguments(
5169 VarTemplateArgs, InstantiationDependent))
5170 D = cast<NamedDecl>(
5171 SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs));
5172 return D;
5173 }
5174
Douglas Gregor64621e62009-09-16 18:34:49 +00005175 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
5176 if (!Record->isDependentContext())
5177 return D;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005178
Douglas Gregor4109afa2011-11-07 17:43:18 +00005179 // Determine whether this record is the "templated" declaration describing
5180 // a class template or class template partial specialization.
Douglas Gregor64621e62009-09-16 18:34:49 +00005181 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
Douglas Gregor4109afa2011-11-07 17:43:18 +00005182 if (ClassTemplate)
5183 ClassTemplate = ClassTemplate->getCanonicalDecl();
5184 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5185 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
5186 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
Larisse Voufo39a1e502013-08-06 01:03:05 +00005187
Douglas Gregor4109afa2011-11-07 17:43:18 +00005188 // Walk the current context to find either the record or an instantiation of
5189 // it.
5190 DeclContext *DC = CurContext;
5191 while (!DC->isFileContext()) {
5192 // If we're performing substitution while we're inside the template
5193 // definition, we'll find our own context. We're done.
5194 if (DC->Equals(Record))
5195 return Record;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005196
Douglas Gregor4109afa2011-11-07 17:43:18 +00005197 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
5198 // Check whether we're in the process of instantiating a class template
5199 // specialization of the template we're mapping.
5200 if (ClassTemplateSpecializationDecl *InstSpec
5201 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
5202 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
5203 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
5204 return InstRecord;
5205 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00005206
Douglas Gregor4109afa2011-11-07 17:43:18 +00005207 // Check whether we're in the process of instantiating a member class.
5208 if (isInstantiationOf(Record, InstRecord))
5209 return InstRecord;
Douglas Gregor64621e62009-09-16 18:34:49 +00005210 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00005211
Douglas Gregor4109afa2011-11-07 17:43:18 +00005212 // Move to the outer template scope.
5213 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
5214 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
5215 DC = FD->getLexicalDeclContext();
5216 continue;
5217 }
Richard Smith32918772017-02-14 00:25:28 +00005218 // An implicit deduction guide acts as if it's within the class template
5219 // specialization described by its name and first N template params.
Richard Smithbc491202017-02-17 20:05:37 +00005220 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD);
5221 if (Guide && Guide->isImplicit()) {
5222 TemplateDecl *TD = Guide->getDeducedTemplate();
Richard Smith0cd9c042017-02-21 08:42:39 +00005223 // Convert the arguments to an "as-written" list.
Richard Smith32918772017-02-14 00:25:28 +00005224 TemplateArgumentListInfo Args(Loc, Loc);
Richard Smith0cd9c042017-02-21 08:42:39 +00005225 for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front(
5226 TD->getTemplateParameters()->size())) {
5227 ArrayRef<TemplateArgument> Unpacked(Arg);
5228 if (Arg.getKind() == TemplateArgument::Pack)
5229 Unpacked = Arg.pack_elements();
5230 for (TemplateArgument UnpackedArg : Unpacked)
5231 Args.addArgument(
5232 getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc));
5233 }
Richard Smith32918772017-02-14 00:25:28 +00005234 QualType T = CheckTemplateIdType(TemplateName(TD), Loc, Args);
5235 if (T.isNull())
5236 return nullptr;
Richard Smithe6d4b772017-06-07 02:42:27 +00005237 auto *SubstRecord = T->getAsCXXRecordDecl();
5238 assert(SubstRecord && "class template id not a class type?");
5239 // Check that this template-id names the primary template and not a
5240 // partial or explicit specialization. (In the latter cases, it's
5241 // meaningless to attempt to find an instantiation of D within the
5242 // specialization.)
5243 // FIXME: The standard doesn't say what should happen here.
Richard Smith4f440e32017-06-08 01:08:50 +00005244 if (FindingInstantiatedContext &&
5245 usesPartialOrExplicitSpecialization(
5246 Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) {
Richard Smithe6d4b772017-06-07 02:42:27 +00005247 Diag(Loc, diag::err_specialization_not_primary_template)
5248 << T << (SubstRecord->getTemplateSpecializationKind() ==
5249 TSK_ExplicitSpecialization);
5250 return nullptr;
5251 }
5252 DC = SubstRecord;
Richard Smith32918772017-02-14 00:25:28 +00005253 continue;
5254 }
John McCall59660882009-08-29 08:11:13 +00005255 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00005256
Douglas Gregor4109afa2011-11-07 17:43:18 +00005257 DC = DC->getParent();
John McCall59660882009-08-29 08:11:13 +00005258 }
Douglas Gregord225fa02010-02-05 22:40:03 +00005259
Douglas Gregor64621e62009-09-16 18:34:49 +00005260 // Fall through to deal with other dependent record types (e.g.,
5261 // anonymous unions in class templates).
5262 }
John McCall59660882009-08-29 08:11:13 +00005263
Douglas Gregor64621e62009-09-16 18:34:49 +00005264 if (!ParentDC->isDependentContext())
5265 return D;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005266
Douglas Gregora04f2ca2010-03-01 15:56:25 +00005267 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00005268 if (!ParentDC)
Craig Topperc3ec1492014-05-26 06:22:03 +00005269 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005270
Douglas Gregor51783312009-05-27 05:35:12 +00005271 if (ParentDC != D->getDeclContext()) {
5272 // We performed some kind of instantiation in the parent context,
5273 // so now we need to look into the instantiated parent context to
5274 // find the instantiation of the declaration D.
Douglas Gregora04f2ca2010-03-01 15:56:25 +00005275
John McCalle78aac42010-03-10 03:28:59 +00005276 // If our context used to be dependent, we may need to instantiate
5277 // it before performing lookup into that context.
Douglas Gregor528ad932011-03-06 20:12:45 +00005278 bool IsBeingInstantiated = false;
John McCalle78aac42010-03-10 03:28:59 +00005279 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00005280 if (!Spec->isDependentContext()) {
5281 QualType T = Context.getTypeDeclType(Spec);
John McCalle78aac42010-03-10 03:28:59 +00005282 const RecordType *Tag = T->getAs<RecordType>();
5283 assert(Tag && "type of non-dependent record is not a RecordType");
Douglas Gregor528ad932011-03-06 20:12:45 +00005284 if (Tag->isBeingDefined())
5285 IsBeingInstantiated = true;
John McCalle78aac42010-03-10 03:28:59 +00005286 if (!Tag->isBeingDefined() &&
5287 RequireCompleteType(Loc, T, diag::err_incomplete_type))
Craig Topperc3ec1492014-05-26 06:22:03 +00005288 return nullptr;
Douglas Gregor25edf432010-11-05 23:22:45 +00005289
5290 ParentDC = Tag->getDecl();
Douglas Gregora04f2ca2010-03-01 15:56:25 +00005291 }
5292 }
5293
Craig Topperc3ec1492014-05-26 06:22:03 +00005294 NamedDecl *Result = nullptr;
Richard Smith151c4562016-12-20 21:35:28 +00005295 // FIXME: If the name is a dependent name, this lookup won't necessarily
5296 // find it. Does that ever matter?
Akira Hatanaka59e3b432017-01-31 19:53:32 +00005297 if (auto Name = D->getDeclName()) {
5298 DeclarationNameInfo NameInfo(Name, D->getLocation());
5299 Name = SubstDeclarationNameInfo(NameInfo, TemplateArgs).getName();
5300 if (!Name)
5301 return nullptr;
5302 DeclContext::lookup_result Found = ParentDC->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00005303 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
Douglas Gregor51783312009-05-27 05:35:12 +00005304 } else {
5305 // Since we don't have a name for the entity we're looking for,
5306 // our only option is to walk through all of the declarations to
5307 // find that name. This will occur in a few cases:
5308 //
5309 // - anonymous struct/union within a template
5310 // - unnamed class/struct/union/enum within a template
5311 //
5312 // FIXME: Find a better way to find these instantiations!
Mike Stump11289f42009-09-09 15:08:12 +00005313 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005314 ParentDC->decls_begin(),
5315 ParentDC->decls_end());
Douglas Gregor51783312009-05-27 05:35:12 +00005316 }
Mike Stump11289f42009-09-09 15:08:12 +00005317
Douglas Gregor528ad932011-03-06 20:12:45 +00005318 if (!Result) {
5319 if (isa<UsingShadowDecl>(D)) {
5320 // UsingShadowDecls can instantiate to nothing because of using hiding.
5321 } else if (Diags.hasErrorOccurred()) {
5322 // We've already complained about something, so most likely this
5323 // declaration failed to instantiate. There's no point in complaining
5324 // further, since this is normal in invalid code.
5325 } else if (IsBeingInstantiated) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005326 // The class in which this member exists is currently being
Douglas Gregor528ad932011-03-06 20:12:45 +00005327 // instantiated, and we haven't gotten around to instantiating this
5328 // member yet. This can happen when the code uses forward declarations
5329 // of member classes, and introduces ordering dependencies via
5330 // template instantiation.
5331 Diag(Loc, diag::err_member_not_yet_instantiated)
5332 << D->getDeclName()
5333 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
5334 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
Richard Smith169f2192012-03-26 20:28:16 +00005335 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
5336 // This enumeration constant was found when the template was defined,
5337 // but can't be found in the instantiation. This can happen if an
5338 // unscoped enumeration member is explicitly specialized.
5339 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
5340 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
5341 TemplateArgs));
5342 assert(Spec->getTemplateSpecializationKind() ==
5343 TSK_ExplicitSpecialization);
5344 Diag(Loc, diag::err_enumerator_does_not_exist)
5345 << D->getDeclName()
5346 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
5347 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
5348 << Context.getTypeDeclType(Spec);
Douglas Gregor528ad932011-03-06 20:12:45 +00005349 } else {
5350 // We should have found something, but didn't.
5351 llvm_unreachable("Unable to find instantiation of declaration!");
5352 }
5353 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005354
Douglas Gregor51783312009-05-27 05:35:12 +00005355 D = Result;
5356 }
5357
Douglas Gregor51783312009-05-27 05:35:12 +00005358 return D;
5359}
Douglas Gregor77b50e12009-06-22 23:06:13 +00005360
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005361/// Performs template instantiation for all implicit template
Douglas Gregor77b50e12009-06-22 23:06:13 +00005362/// instantiations we have seen until this point.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00005363void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregor7f792cf2010-01-16 22:29:39 +00005364 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth54080172010-08-25 08:44:16 +00005365 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor7f792cf2010-01-16 22:29:39 +00005366 PendingImplicitInstantiation Inst;
5367
5368 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth54080172010-08-25 08:44:16 +00005369 Inst = PendingInstantiations.front();
5370 PendingInstantiations.pop_front();
Douglas Gregor7f792cf2010-01-16 22:29:39 +00005371 } else {
5372 Inst = PendingLocalImplicitInstantiations.front();
5373 PendingLocalImplicitInstantiations.pop_front();
5374 }
Mike Stump11289f42009-09-09 15:08:12 +00005375
Douglas Gregora6ef8f02009-07-24 20:34:43 +00005376 // Instantiate function definitions
5377 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Chandler Carruthcfe41db2010-08-25 08:27:02 +00005378 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
5379 TSK_ExplicitInstantiationDefinition;
Erich Keane0fb16482018-08-13 18:33:20 +00005380 if (Function->isMultiVersion()) {
5381 getASTContext().forEachMultiversionedFunctionVersion(
5382 Function, [this, Inst, DefinitionRequired](FunctionDecl *CurFD) {
5383 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, CurFD, true,
5384 DefinitionRequired, true);
5385 if (CurFD->isDefined())
5386 CurFD->setInstantiationIsPending(false);
5387 });
5388 } else {
5389 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, Function, true,
5390 DefinitionRequired, true);
5391 if (Function->isDefined())
5392 Function->setInstantiationIsPending(false);
5393 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00005394 continue;
5395 }
Mike Stump11289f42009-09-09 15:08:12 +00005396
Larisse Voufo39a1e502013-08-06 01:03:05 +00005397 // Instantiate variable definitions
Douglas Gregora6ef8f02009-07-24 20:34:43 +00005398 VarDecl *Var = cast<VarDecl>(Inst.first);
Larisse Voufo39a1e502013-08-06 01:03:05 +00005399
5400 assert((Var->isStaticDataMember() ||
5401 isa<VarTemplateSpecializationDecl>(Var)) &&
5402 "Not a static data member, nor a variable template"
5403 " specialization?");
Anders Carlsson62215c42009-09-01 05:12:24 +00005404
Chandler Carruth6b4756a2010-02-13 10:17:50 +00005405 // Don't try to instantiate declarations if the most recent redeclaration
5406 // is invalid.
Douglas Gregorec9fd132012-01-14 16:38:05 +00005407 if (Var->getMostRecentDecl()->isInvalidDecl())
Chandler Carruth6b4756a2010-02-13 10:17:50 +00005408 continue;
5409
5410 // Check if the most recent declaration has changed the specialization kind
5411 // and removed the need for implicit instantiation.
Douglas Gregorec9fd132012-01-14 16:38:05 +00005412 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
Chandler Carruth6b4756a2010-02-13 10:17:50 +00005413 case TSK_Undeclared:
David Blaikie83d382b2011-09-23 05:06:16 +00005414 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
Chandler Carruth6b4756a2010-02-13 10:17:50 +00005415 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth6b4756a2010-02-13 10:17:50 +00005416 case TSK_ExplicitSpecialization:
Chandler Carruthcfe41db2010-08-25 08:27:02 +00005417 continue; // No longer need to instantiate this type.
5418 case TSK_ExplicitInstantiationDefinition:
5419 // We only need an instantiation if the pending instantiation *is* the
5420 // explicit instantiation.
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00005421 if (Var != Var->getMostRecentDecl())
5422 continue;
5423 break;
Chandler Carruth6b4756a2010-02-13 10:17:50 +00005424 case TSK_ImplicitInstantiation:
5425 break;
5426 }
5427
Jordan Rose1e879d82018-03-23 00:07:18 +00005428 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00005429 "instantiating variable definition");
Chandler Carruthcfe41db2010-08-25 08:27:02 +00005430 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
5431 TSK_ExplicitInstantiationDefinition;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005432
5433 // Instantiate static data member definitions or variable template
5434 // specializations.
5435 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00005436 DefinitionRequired, true);
Douglas Gregor77b50e12009-06-22 23:06:13 +00005437 }
5438}
John McCallc62bb642010-03-24 05:22:00 +00005439
5440void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
5441 const MultiLevelTemplateArgumentList &TemplateArgs) {
Aaron Ballmanb105e492014-03-07 14:09:15 +00005442 for (auto DD : Pattern->ddiags()) {
John McCallc62bb642010-03-24 05:22:00 +00005443 switch (DD->getKind()) {
5444 case DependentDiagnostic::Access:
5445 HandleDependentAccessCheck(*DD, TemplateArgs);
5446 break;
5447 }
5448 }
5449}