blob: 58d1d209044a2041565d884a53e212ec4010e484 [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
Alexey Bataev4244be22016-02-11 05:35:55 +00002927Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
2928 OMPCapturedExprDecl * /*D*/) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00002929 llvm_unreachable("Should not be met in templates");
2930}
2931
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002932Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002933 return VisitFunctionDecl(D, nullptr);
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002934}
2935
Richard Smithbc491202017-02-17 20:05:37 +00002936Decl *
2937TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
Richard Smith2600c632018-05-30 20:24:10 +00002938 Decl *Inst = VisitFunctionDecl(D, nullptr);
2939 if (Inst && !D->getDescribedFunctionTemplate())
2940 Owner->addDecl(Inst);
2941 return Inst;
Richard Smithbc491202017-02-17 20:05:37 +00002942}
2943
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002944Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002945 return VisitCXXMethodDecl(D, nullptr);
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002946}
2947
2948Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
2949 llvm_unreachable("There are only CXXRecordDecls in C++");
2950}
2951
2952Decl *
2953TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
2954 ClassTemplateSpecializationDecl *D) {
Richard Smith8a0dde72013-12-14 01:04:22 +00002955 // As a MS extension, we permit class-scope explicit specialization
2956 // of member class templates.
2957 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
2958 assert(ClassTemplate->getDeclContext()->isRecord() &&
2959 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2960 "can only instantiate an explicit specialization "
2961 "for a member class template");
2962
2963 // Lookup the already-instantiated declaration in the instantiation
2964 // of the class template. FIXME: Diagnose or assert if this fails?
2965 DeclContext::lookup_result Found
2966 = Owner->lookup(ClassTemplate->getDeclName());
2967 if (Found.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +00002968 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002969 ClassTemplateDecl *InstClassTemplate
2970 = dyn_cast<ClassTemplateDecl>(Found.front());
2971 if (!InstClassTemplate)
Craig Topperc3ec1492014-05-26 06:22:03 +00002972 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002973
2974 // Substitute into the template arguments of the class template explicit
2975 // specialization.
2976 TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
2977 castAs<TemplateSpecializationTypeLoc>();
2978 TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
2979 Loc.getRAngleLoc());
2980 SmallVector<TemplateArgumentLoc, 4> ArgLocs;
2981 for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
2982 ArgLocs.push_back(Loc.getArgLoc(I));
2983 if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(),
2984 InstTemplateArgs, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00002985 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002986
2987 // Check that the template argument list is well-formed for this
2988 // class template.
2989 SmallVector<TemplateArgument, 4> Converted;
2990 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
2991 D->getLocation(),
2992 InstTemplateArgs,
2993 false,
2994 Converted))
Craig Topperc3ec1492014-05-26 06:22:03 +00002995 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002996
2997 // Figure out where to insert this class template explicit specialization
2998 // in the member template's set of class template explicit specializations.
Craig Topperc3ec1492014-05-26 06:22:03 +00002999 void *InsertPos = nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00003000 ClassTemplateSpecializationDecl *PrevDecl =
Craig Topper7e0daca2014-06-26 04:58:53 +00003001 InstClassTemplate->findSpecialization(Converted, InsertPos);
Richard Smith8a0dde72013-12-14 01:04:22 +00003002
3003 // Check whether we've already seen a conflicting instantiation of this
3004 // declaration (for instance, if there was a prior implicit instantiation).
3005 bool Ignored;
3006 if (PrevDecl &&
3007 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
3008 D->getSpecializationKind(),
3009 PrevDecl,
3010 PrevDecl->getSpecializationKind(),
3011 PrevDecl->getPointOfInstantiation(),
3012 Ignored))
Craig Topperc3ec1492014-05-26 06:22:03 +00003013 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00003014
3015 // If PrevDecl was a definition and D is also a definition, diagnose.
3016 // This happens in cases like:
3017 //
3018 // template<typename T, typename U>
3019 // struct Outer {
3020 // template<typename X> struct Inner;
3021 // template<> struct Inner<T> {};
3022 // template<> struct Inner<U> {};
3023 // };
3024 //
3025 // Outer<int, int> outer; // error: the explicit specializations of Inner
3026 // // have the same signature.
3027 if (PrevDecl && PrevDecl->getDefinition() &&
3028 D->isThisDeclarationADefinition()) {
3029 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
3030 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
3031 diag::note_previous_definition);
Craig Topperc3ec1492014-05-26 06:22:03 +00003032 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00003033 }
3034
3035 // Create the class template partial specialization declaration.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003036 ClassTemplateSpecializationDecl *InstD =
3037 ClassTemplateSpecializationDecl::Create(
3038 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
3039 D->getLocation(), InstClassTemplate, Converted, PrevDecl);
Richard Smith8a0dde72013-12-14 01:04:22 +00003040
3041 // Add this partial specialization to the set of class template partial
3042 // specializations.
3043 if (!PrevDecl)
3044 InstClassTemplate->AddSpecialization(InstD, InsertPos);
3045
3046 // Substitute the nested name specifier, if any.
3047 if (SubstQualifier(D, InstD))
Craig Topperc3ec1492014-05-26 06:22:03 +00003048 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00003049
3050 // Build the canonical type that describes the converted template
3051 // arguments of the class template explicit specialization.
3052 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00003053 TemplateName(InstClassTemplate), Converted,
Richard Smith8a0dde72013-12-14 01:04:22 +00003054 SemaRef.Context.getRecordType(InstD));
3055
3056 // Build the fully-sugared type for this class template
3057 // specialization as the user wrote in the specialization
3058 // itself. This means that we'll pretty-print the type retrieved
3059 // from the specialization's declaration the way that the user
3060 // actually wrote the specialization, rather than formatting the
3061 // name based on the "canonical" representation used to store the
3062 // template arguments in the specialization.
3063 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
3064 TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
3065 CanonType);
3066
3067 InstD->setAccess(D->getAccess());
3068 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
3069 InstD->setSpecializationKind(D->getSpecializationKind());
3070 InstD->setTypeAsWritten(WrittenTy);
3071 InstD->setExternLoc(D->getExternLoc());
3072 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
3073
3074 Owner->addDecl(InstD);
3075
3076 // Instantiate the members of the class-scope explicit specialization eagerly.
3077 // We don't have support for lazy instantiation of an explicit specialization
3078 // yet, and MSVC eagerly instantiates in this case.
3079 if (D->isThisDeclarationADefinition() &&
3080 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
3081 TSK_ImplicitInstantiation,
3082 /*Complain=*/true))
Craig Topperc3ec1492014-05-26 06:22:03 +00003083 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00003084
3085 return InstD;
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00003086}
3087
Larisse Voufo39a1e502013-08-06 01:03:05 +00003088Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3089 VarTemplateSpecializationDecl *D) {
3090
3091 TemplateArgumentListInfo VarTemplateArgsInfo;
3092 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
3093 assert(VarTemplate &&
3094 "A template specialization without specialized template?");
3095
3096 // Substitute the current template arguments.
3097 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
3098 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
3099 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
3100
3101 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
3102 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00003103 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003104
3105 // Check that the template argument list is well-formed for this template.
3106 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003107 if (SemaRef.CheckTemplateArgumentList(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003108 VarTemplate, VarTemplate->getBeginLoc(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00003109 const_cast<TemplateArgumentListInfo &>(VarTemplateArgsInfo), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00003110 Converted))
Craig Topperc3ec1492014-05-26 06:22:03 +00003111 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003112
3113 // Find the variable template specialization declaration that
3114 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00003115 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003116 if (VarTemplateSpecializationDecl *VarSpec = VarTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +00003117 Converted, InsertPos))
Larisse Voufo39a1e502013-08-06 01:03:05 +00003118 // If we already have a variable template specialization, return it.
3119 return VarSpec;
3120
3121 return VisitVarTemplateSpecializationDecl(VarTemplate, D, InsertPos,
3122 VarTemplateArgsInfo, Converted);
3123}
3124
3125Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3126 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
3127 const TemplateArgumentListInfo &TemplateArgsInfo,
Craig Topper00bbdcf2014-06-28 23:22:23 +00003128 ArrayRef<TemplateArgument> Converted) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003129
Larisse Voufo39a1e502013-08-06 01:03:05 +00003130 // Do substitution on the type of the declaration
3131 TypeSourceInfo *DI =
3132 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
3133 D->getTypeSpecStartLoc(), D->getDeclName());
3134 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00003135 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003136
3137 if (DI->getType()->isFunctionType()) {
3138 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
3139 << D->isStaticDataMember() << DI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00003140 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003141 }
3142
3143 // Build the instantiated declaration
3144 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
3145 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
David Majnemer8b622692016-07-03 21:17:51 +00003146 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003147 Var->setTemplateArgsInfo(TemplateArgsInfo);
Richard Smith8809a0c2013-09-27 20:14:12 +00003148 if (InsertPos)
3149 VarTemplate->AddSpecialization(Var, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003150
3151 // Substitute the nested name specifier, if any.
3152 if (SubstQualifier(D, Var))
Craig Topperc3ec1492014-05-26 06:22:03 +00003153 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003154
3155 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs,
Richard Smith541b38b2013-09-20 01:15:31 +00003156 Owner, StartingScope);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003157
3158 return Var;
3159}
3160
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00003161Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
3162 llvm_unreachable("@defs is not supported in Objective-C++");
3163}
3164
3165Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
3166 // FIXME: We need to be able to instantiate FriendTemplateDecls.
3167 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
3168 DiagnosticsEngine::Error,
3169 "cannot instantiate %0 yet");
3170 SemaRef.Diag(D->getLocation(), DiagID)
3171 << D->getDeclKindName();
3172
Craig Topperc3ec1492014-05-26 06:22:03 +00003173 return nullptr;
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00003174}
3175
3176Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
3177 llvm_unreachable("Unexpected decl");
3178}
3179
John McCall76d824f2009-08-25 22:02:44 +00003180Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregor01afeef2009-08-28 20:31:08 +00003181 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregord002c7b2009-05-11 23:53:27 +00003182 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor71ad4772010-02-16 19:28:15 +00003183 if (D->isInvalidDecl())
Craig Topperc3ec1492014-05-26 06:22:03 +00003184 return nullptr;
Douglas Gregor71ad4772010-02-16 19:28:15 +00003185
Douglas Gregord7e7a512009-03-17 21:15:40 +00003186 return Instantiator.Visit(D);
3187}
3188
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003189/// Instantiates a nested template parameter list in the current
John McCall87a44eb2009-08-20 01:44:21 +00003190/// instantiation context.
3191///
3192/// \param L The parameter list to instantiate
3193///
3194/// \returns NULL if there was an error
3195TemplateParameterList *
John McCall76d824f2009-08-25 22:02:44 +00003196TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCall87a44eb2009-08-20 01:44:21 +00003197 // Get errors for all the parameters before bailing out.
3198 bool Invalid = false;
3199
3200 unsigned N = L->size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003201 typedef SmallVector<NamedDecl *, 8> ParamVector;
John McCall87a44eb2009-08-20 01:44:21 +00003202 ParamVector Params;
3203 Params.reserve(N);
Davide Italiano18960b92015-07-02 19:20:11 +00003204 for (auto &P : *L) {
3205 NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
John McCall87a44eb2009-08-20 01:44:21 +00003206 Params.push_back(D);
Douglas Gregore62e6a02009-11-11 19:13:48 +00003207 Invalid = Invalid || !D || D->isInvalidDecl();
John McCall87a44eb2009-08-20 01:44:21 +00003208 }
3209
3210 // Clean up if we had an error.
Douglas Gregorb412e172010-07-25 18:17:45 +00003211 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +00003212 return nullptr;
John McCall87a44eb2009-08-20 01:44:21 +00003213
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00003214 // Note: we substitute into associated constraints later
3215 Expr *const UninstantiatedRequiresClause = L->getRequiresClause();
3216
John McCall87a44eb2009-08-20 01:44:21 +00003217 TemplateParameterList *InstL
3218 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
David Majnemer902f8c62015-12-27 07:16:27 +00003219 L->getLAngleLoc(), Params,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00003220 L->getRAngleLoc(),
3221 UninstantiatedRequiresClause);
John McCall87a44eb2009-08-20 01:44:21 +00003222 return InstL;
Mike Stump11289f42009-09-09 15:08:12 +00003223}
John McCall87a44eb2009-08-20 01:44:21 +00003224
Richard Smith5d331022018-03-08 01:07:33 +00003225TemplateParameterList *
3226Sema::SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
3227 const MultiLevelTemplateArgumentList &TemplateArgs) {
3228 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
3229 return Instantiator.SubstTemplateParams(Params);
3230}
3231
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003232/// Instantiate the declaration of a class template partial
Douglas Gregor21610382009-10-29 00:04:11 +00003233/// specialization.
3234///
3235/// \param ClassTemplate the (instantiated) class template that is partially
3236// specialized by the instantiation of \p PartialSpec.
3237///
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003238/// \param PartialSpec the (uninstantiated) class template partial
Douglas Gregor21610382009-10-29 00:04:11 +00003239/// specialization that we are instantiating.
3240///
Douglas Gregor869853e2010-11-10 19:44:59 +00003241/// \returns The instantiated partial specialization, if successful; otherwise,
3242/// NULL to indicate an error.
3243ClassTemplatePartialSpecializationDecl *
Douglas Gregor21610382009-10-29 00:04:11 +00003244TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
3245 ClassTemplateDecl *ClassTemplate,
3246 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor954de172009-10-31 17:21:17 +00003247 // Create a local instantiation scope for this class template partial
3248 // specialization, which will contain the instantiations of the template
3249 // parameters.
John McCall19c1bfd2010-08-25 05:32:35 +00003250 LocalInstantiationScope Scope(SemaRef);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003251
Douglas Gregor21610382009-10-29 00:04:11 +00003252 // Substitute into the template parameters of the class template partial
3253 // specialization.
3254 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
3255 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
3256 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00003257 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003258
Douglas Gregor21610382009-10-29 00:04:11 +00003259 // Substitute into the template arguments of the class template partial
3260 // specialization.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00003261 const ASTTemplateArgumentListInfo *TemplArgInfo
3262 = PartialSpec->getTemplateArgsAsWritten();
3263 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
3264 TemplArgInfo->RAngleLoc);
3265 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
3266 TemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00003267 InstTemplateArgs, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00003268 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003269
Douglas Gregor21610382009-10-29 00:04:11 +00003270 // Check that the template argument list is well-formed for this
3271 // class template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003272 SmallVector<TemplateArgument, 4> Converted;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003273 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
Douglas Gregor21610382009-10-29 00:04:11 +00003274 PartialSpec->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003275 InstTemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00003276 false,
3277 Converted))
Craig Topperc3ec1492014-05-26 06:22:03 +00003278 return nullptr;
Douglas Gregor21610382009-10-29 00:04:11 +00003279
Richard Smith57aae072016-12-28 02:37:25 +00003280 // Check these arguments are valid for a template partial specialization.
3281 if (SemaRef.CheckTemplatePartialSpecializationArgs(
3282 PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
3283 Converted))
3284 return nullptr;
3285
Douglas Gregor21610382009-10-29 00:04:11 +00003286 // Figure out where to insert this class template partial specialization
3287 // in the member template's set of class template partial specializations.
Craig Topperc3ec1492014-05-26 06:22:03 +00003288 void *InsertPos = nullptr;
Douglas Gregor21610382009-10-29 00:04:11 +00003289 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00003290 = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003291
Douglas Gregor21610382009-10-29 00:04:11 +00003292 // Build the canonical type that describes the converted template
3293 // arguments of the class template partial specialization.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003294 QualType CanonType
Douglas Gregor21610382009-10-29 00:04:11 +00003295 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
David Majnemer6fbeee32016-07-07 04:43:07 +00003296 Converted);
Douglas Gregor21610382009-10-29 00:04:11 +00003297
3298 // Build the fully-sugared type for this class template
3299 // specialization as the user wrote in the specialization
3300 // itself. This means that we'll pretty-print the type retrieved
3301 // from the specialization's declaration the way that the user
3302 // actually wrote the specialization, rather than formatting the
3303 // name based on the "canonical" representation used to store the
3304 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00003305 TypeSourceInfo *WrittenTy
3306 = SemaRef.Context.getTemplateSpecializationTypeInfo(
3307 TemplateName(ClassTemplate),
3308 PartialSpec->getLocation(),
John McCall6b51f282009-11-23 01:53:49 +00003309 InstTemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00003310 CanonType);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003311
Douglas Gregor21610382009-10-29 00:04:11 +00003312 if (PrevDecl) {
3313 // We've already seen a partial specialization with the same template
3314 // parameters and template arguments. This can happen, for example, when
3315 // substituting the outer template arguments ends up causing two
3316 // class template partial specializations of a member class template
3317 // to have identical forms, e.g.,
3318 //
3319 // template<typename T, typename U>
3320 // struct Outer {
3321 // template<typename X, typename Y> struct Inner;
3322 // template<typename Y> struct Inner<T, Y>;
3323 // template<typename Y> struct Inner<U, Y>;
3324 // };
3325 //
3326 // Outer<int, int> outer; // error: the partial specializations of Inner
3327 // // have the same signature.
3328 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregor869853e2010-11-10 19:44:59 +00003329 << WrittenTy->getType();
Douglas Gregor21610382009-10-29 00:04:11 +00003330 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
3331 << SemaRef.Context.getTypeDeclType(PrevDecl);
Craig Topperc3ec1492014-05-26 06:22:03 +00003332 return nullptr;
Douglas Gregor21610382009-10-29 00:04:11 +00003333 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003334
3335
Douglas Gregor21610382009-10-29 00:04:11 +00003336 // Create the class template partial specialization declaration.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003337 ClassTemplatePartialSpecializationDecl *InstPartialSpec =
3338 ClassTemplatePartialSpecializationDecl::Create(
3339 SemaRef.Context, PartialSpec->getTagKind(), Owner,
3340 PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
3341 ClassTemplate, Converted, InstTemplateArgs, CanonType, nullptr);
John McCall3e11ebe2010-03-15 10:12:16 +00003342 // Substitute the nested name specifier, if any.
3343 if (SubstQualifier(PartialSpec, InstPartialSpec))
Craig Topperc3ec1492014-05-26 06:22:03 +00003344 return nullptr;
John McCall3e11ebe2010-03-15 10:12:16 +00003345
Douglas Gregor21610382009-10-29 00:04:11 +00003346 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor6044d692010-05-19 17:02:24 +00003347 InstPartialSpec->setTypeAsWritten(WrittenTy);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003348
Richard Smith57aae072016-12-28 02:37:25 +00003349 // Check the completed partial specialization.
3350 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
3351
Douglas Gregor21610382009-10-29 00:04:11 +00003352 // Add this partial specialization to the set of class template partial
3353 // specializations.
Craig Topperc3ec1492014-05-26 06:22:03 +00003354 ClassTemplate->AddPartialSpecialization(InstPartialSpec,
3355 /*InsertPos=*/nullptr);
Douglas Gregor869853e2010-11-10 19:44:59 +00003356 return InstPartialSpec;
Douglas Gregor21610382009-10-29 00:04:11 +00003357}
3358
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003359/// Instantiate the declaration of a variable template partial
Larisse Voufo39a1e502013-08-06 01:03:05 +00003360/// specialization.
3361///
3362/// \param VarTemplate the (instantiated) variable template that is partially
3363/// specialized by the instantiation of \p PartialSpec.
3364///
3365/// \param PartialSpec the (uninstantiated) variable template partial
3366/// specialization that we are instantiating.
3367///
3368/// \returns The instantiated partial specialization, if successful; otherwise,
3369/// NULL to indicate an error.
3370VarTemplatePartialSpecializationDecl *
3371TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
3372 VarTemplateDecl *VarTemplate,
3373 VarTemplatePartialSpecializationDecl *PartialSpec) {
3374 // Create a local instantiation scope for this variable template partial
3375 // specialization, which will contain the instantiations of the template
3376 // parameters.
3377 LocalInstantiationScope Scope(SemaRef);
3378
3379 // Substitute into the template parameters of the variable template partial
3380 // specialization.
3381 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
3382 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
3383 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00003384 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003385
3386 // Substitute into the template arguments of the variable template partial
3387 // specialization.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00003388 const ASTTemplateArgumentListInfo *TemplArgInfo
3389 = PartialSpec->getTemplateArgsAsWritten();
3390 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
3391 TemplArgInfo->RAngleLoc);
3392 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
3393 TemplArgInfo->NumTemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00003394 InstTemplateArgs, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00003395 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003396
3397 // Check that the template argument list is well-formed for this
3398 // class template.
3399 SmallVector<TemplateArgument, 4> Converted;
3400 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
3401 InstTemplateArgs, false, Converted))
Craig Topperc3ec1492014-05-26 06:22:03 +00003402 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003403
Richard Smith57aae072016-12-28 02:37:25 +00003404 // Check these arguments are valid for a template partial specialization.
3405 if (SemaRef.CheckTemplatePartialSpecializationArgs(
3406 PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
3407 Converted))
3408 return nullptr;
3409
Larisse Voufo39a1e502013-08-06 01:03:05 +00003410 // Figure out where to insert this variable template partial specialization
3411 // in the member template's set of variable template partial specializations.
Craig Topperc3ec1492014-05-26 06:22:03 +00003412 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003413 VarTemplateSpecializationDecl *PrevDecl =
Craig Topper7e0daca2014-06-26 04:58:53 +00003414 VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003415
3416 // Build the canonical type that describes the converted template
3417 // arguments of the variable template partial specialization.
3418 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00003419 TemplateName(VarTemplate), Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003420
3421 // Build the fully-sugared type for this variable template
3422 // specialization as the user wrote in the specialization
3423 // itself. This means that we'll pretty-print the type retrieved
3424 // from the specialization's declaration the way that the user
3425 // actually wrote the specialization, rather than formatting the
3426 // name based on the "canonical" representation used to store the
3427 // template arguments in the specialization.
3428 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
3429 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
3430 CanonType);
3431
3432 if (PrevDecl) {
3433 // We've already seen a partial specialization with the same template
3434 // parameters and template arguments. This can happen, for example, when
3435 // substituting the outer template arguments ends up causing two
3436 // variable template partial specializations of a member variable template
3437 // to have identical forms, e.g.,
3438 //
3439 // template<typename T, typename U>
3440 // struct Outer {
3441 // template<typename X, typename Y> pair<X,Y> p;
3442 // template<typename Y> pair<T, Y> p;
3443 // template<typename Y> pair<U, Y> p;
3444 // };
3445 //
3446 // Outer<int, int> outer; // error: the partial specializations of Inner
3447 // // have the same signature.
3448 SemaRef.Diag(PartialSpec->getLocation(),
3449 diag::err_var_partial_spec_redeclared)
3450 << WrittenTy->getType();
3451 SemaRef.Diag(PrevDecl->getLocation(),
3452 diag::note_var_prev_partial_spec_here);
Craig Topperc3ec1492014-05-26 06:22:03 +00003453 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003454 }
3455
3456 // Do substitution on the type of the declaration
3457 TypeSourceInfo *DI = SemaRef.SubstType(
3458 PartialSpec->getTypeSourceInfo(), TemplateArgs,
3459 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
3460 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00003461 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003462
3463 if (DI->getType()->isFunctionType()) {
3464 SemaRef.Diag(PartialSpec->getLocation(),
3465 diag::err_variable_instantiates_to_function)
3466 << PartialSpec->isStaticDataMember() << DI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00003467 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003468 }
3469
3470 // Create the variable template partial specialization declaration.
3471 VarTemplatePartialSpecializationDecl *InstPartialSpec =
3472 VarTemplatePartialSpecializationDecl::Create(
3473 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
3474 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
David Majnemer8b622692016-07-03 21:17:51 +00003475 DI, PartialSpec->getStorageClass(), Converted, InstTemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003476
3477 // Substitute the nested name specifier, if any.
3478 if (SubstQualifier(PartialSpec, InstPartialSpec))
Craig Topperc3ec1492014-05-26 06:22:03 +00003479 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003480
3481 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
3482 InstPartialSpec->setTypeAsWritten(WrittenTy);
3483
Richard Smith57aae072016-12-28 02:37:25 +00003484 // Check the completed partial specialization.
3485 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
3486
Larisse Voufo39a1e502013-08-06 01:03:05 +00003487 // Add this partial specialization to the set of variable template partial
3488 // specializations. The instantiation of the initializer is not necessary.
Craig Topperc3ec1492014-05-26 06:22:03 +00003489 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
Larisse Voufo4cda4612013-08-22 00:28:27 +00003490
Larisse Voufo4cda4612013-08-22 00:28:27 +00003491 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
Richard Smith541b38b2013-09-20 01:15:31 +00003492 LateAttrs, Owner, StartingScope);
Larisse Voufo4cda4612013-08-22 00:28:27 +00003493
Larisse Voufo39a1e502013-08-06 01:03:05 +00003494 return InstPartialSpec;
3495}
3496
John McCall58f10c32010-03-11 09:03:00 +00003497TypeSourceInfo*
John McCall76d824f2009-08-25 22:02:44 +00003498TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003499 SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall58f10c32010-03-11 09:03:00 +00003500 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
3501 assert(OldTInfo && "substituting function without type source info");
3502 assert(Params.empty() && "parameter vector is non-empty at start");
Craig Topperc3ec1492014-05-26 06:22:03 +00003503
3504 CXXRecordDecl *ThisContext = nullptr;
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00003505 Qualifiers ThisTypeQuals;
Douglas Gregor3024f072012-04-16 07:05:22 +00003506 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Richard Smithc3d2ebb2013-06-07 02:33:37 +00003507 ThisContext = cast<CXXRecordDecl>(Owner);
Douglas Gregor3024f072012-04-16 07:05:22 +00003508 ThisTypeQuals = Method->getTypeQualifiers();
3509 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003510
John McCallb29f78f2010-04-09 17:38:44 +00003511 TypeSourceInfo *NewTInfo
3512 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
3513 D->getTypeSpecStartLoc(),
Douglas Gregor3024f072012-04-16 07:05:22 +00003514 D->getDeclName(),
3515 ThisContext, ThisTypeQuals);
John McCall58f10c32010-03-11 09:03:00 +00003516 if (!NewTInfo)
Craig Topperc3ec1492014-05-26 06:22:03 +00003517 return nullptr;
Douglas Gregor21342092009-03-24 00:38:23 +00003518
Reid Klecknera09e44c2013-07-31 21:00:18 +00003519 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
3520 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
3521 if (NewTInfo != OldTInfo) {
3522 // Get parameters from the new type info.
Abramo Bagnaraa44c9022010-12-13 22:27:55 +00003523 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +00003524 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
Richard Smith198223b2012-07-18 01:29:05 +00003525 unsigned NewIdx = 0;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003526 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
Douglas Gregorf3010112011-01-07 16:43:16 +00003527 OldIdx != NumOldParams; ++OldIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003528 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
Richard Smith198223b2012-07-18 01:29:05 +00003529 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
3530
David Blaikie05785d12013-02-20 22:23:23 +00003531 Optional<unsigned> NumArgumentsInExpansion;
Richard Smith198223b2012-07-18 01:29:05 +00003532 if (OldParam->isParameterPack())
3533 NumArgumentsInExpansion =
3534 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
3535 TemplateArgs);
3536 if (!NumArgumentsInExpansion) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003537 // Simple case: normal parameter, or a parameter pack that's
Douglas Gregorf3010112011-01-07 16:43:16 +00003538 // instantiated to a (still-dependent) parameter pack.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003539 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
Douglas Gregorf3010112011-01-07 16:43:16 +00003540 Params.push_back(NewParam);
Richard Smith198223b2012-07-18 01:29:05 +00003541 Scope->InstantiatedLocal(OldParam, NewParam);
3542 } else {
3543 // Parameter pack expansion: make the instantiation an argument pack.
3544 Scope->MakeInstantiatedLocalArgPack(OldParam);
3545 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003546 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
Richard Smith198223b2012-07-18 01:29:05 +00003547 Params.push_back(NewParam);
3548 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
3549 }
Douglas Gregorf3010112011-01-07 16:43:16 +00003550 }
Douglas Gregor95c70ec2010-05-03 15:32:18 +00003551 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00003552 } else {
3553 // The function type itself was not dependent and therefore no
3554 // substitution occurred. However, we still need to instantiate
3555 // the function parameters themselves.
3556 const FunctionProtoType *OldProto =
3557 cast<FunctionProtoType>(OldProtoLoc.getType());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003558 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
3559 ++i) {
3560 ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
Reid Klecknera09e44c2013-07-31 21:00:18 +00003561 if (!OldParam) {
3562 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
Alp Toker9cacbab2014-01-20 20:26:09 +00003563 D, D->getLocation(), OldProto->getParamType(i)));
Reid Klecknera09e44c2013-07-31 21:00:18 +00003564 continue;
3565 }
3566
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00003567 ParmVarDecl *Parm =
Reid Klecknera09e44c2013-07-31 21:00:18 +00003568 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
Douglas Gregor95c70ec2010-05-03 15:32:18 +00003569 if (!Parm)
Craig Topperc3ec1492014-05-26 06:22:03 +00003570 return nullptr;
Douglas Gregor95c70ec2010-05-03 15:32:18 +00003571 Params.push_back(Parm);
3572 }
Douglas Gregor940bca72010-04-12 07:48:19 +00003573 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00003574 } else {
3575 // If the type of this function, after ignoring parentheses, is not
3576 // *directly* a function type, then we're instantiating a function that
3577 // was declared via a typedef or with attributes, e.g.,
3578 //
3579 // typedef int functype(int, int);
3580 // functype func;
3581 // int __cdecl meth(int, int);
3582 //
3583 // In this case, we'll just go instantiate the ParmVarDecls that we
3584 // synthesized in the method declaration.
3585 SmallVector<QualType, 4> ParamTypes;
John McCallc8e321d2016-03-01 02:09:25 +00003586 Sema::ExtParameterInfoBuilder ExtParamInfos;
David Majnemer59f77922016-06-24 04:05:48 +00003587 if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
3588 TemplateArgs, ParamTypes, &Params,
3589 ExtParamInfos))
Craig Topperc3ec1492014-05-26 06:22:03 +00003590 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00003591 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00003592
John McCall58f10c32010-03-11 09:03:00 +00003593 return NewTInfo;
Douglas Gregor21342092009-03-24 00:38:23 +00003594}
3595
Richard Smithf623c962012-04-17 00:58:00 +00003596/// Introduce the instantiated function parameters into the local
3597/// instantiation scope, and set the parameter names to those used
3598/// in the template.
Richard Smith2e321552014-11-12 02:00:47 +00003599static bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
Richard Smithf623c962012-04-17 00:58:00 +00003600 const FunctionDecl *PatternDecl,
3601 LocalInstantiationScope &Scope,
3602 const MultiLevelTemplateArgumentList &TemplateArgs) {
3603 unsigned FParamIdx = 0;
3604 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
3605 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
3606 if (!PatternParam->isParameterPack()) {
3607 // Simple case: not a parameter pack.
3608 assert(FParamIdx < Function->getNumParams());
3609 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
Richard Smith2e321552014-11-12 02:00:47 +00003610 FunctionParam->setDeclName(PatternParam->getDeclName());
Richard Smithaae40582014-03-13 00:28:45 +00003611 // If the parameter's type is not dependent, update it to match the type
3612 // in the pattern. They can differ in top-level cv-qualifiers, and we want
3613 // the pattern's type here. If the type is dependent, they can't differ,
Richard Smith2e321552014-11-12 02:00:47 +00003614 // per core issue 1668. Substitute into the type from the pattern, in case
3615 // it's instantiation-dependent.
Richard Smithaae40582014-03-13 00:28:45 +00003616 // FIXME: Updating the type to work around this is at best fragile.
Richard Smith2e321552014-11-12 02:00:47 +00003617 if (!PatternDecl->getType()->isDependentType()) {
3618 QualType T = S.SubstType(PatternParam->getType(), TemplateArgs,
3619 FunctionParam->getLocation(),
3620 FunctionParam->getDeclName());
3621 if (T.isNull())
3622 return true;
3623 FunctionParam->setType(T);
3624 }
Richard Smithaae40582014-03-13 00:28:45 +00003625
Richard Smithf623c962012-04-17 00:58:00 +00003626 Scope.InstantiatedLocal(PatternParam, FunctionParam);
3627 ++FParamIdx;
3628 continue;
3629 }
3630
3631 // Expand the parameter pack.
3632 Scope.MakeInstantiatedLocalArgPack(PatternParam);
David Blaikie05785d12013-02-20 22:23:23 +00003633 Optional<unsigned> NumArgumentsInExpansion
Richard Smithf623c962012-04-17 00:58:00 +00003634 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
Richard Smith198223b2012-07-18 01:29:05 +00003635 assert(NumArgumentsInExpansion &&
3636 "should only be called when all template arguments are known");
Richard Smith2e321552014-11-12 02:00:47 +00003637 QualType PatternType =
3638 PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
Richard Smith198223b2012-07-18 01:29:05 +00003639 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
Richard Smithf623c962012-04-17 00:58:00 +00003640 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
NAKAMURA Takumi23224152014-10-17 12:48:37 +00003641 FunctionParam->setDeclName(PatternParam->getDeclName());
Richard Smith2e321552014-11-12 02:00:47 +00003642 if (!PatternDecl->getType()->isDependentType()) {
3643 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg);
3644 QualType T = S.SubstType(PatternType, TemplateArgs,
3645 FunctionParam->getLocation(),
3646 FunctionParam->getDeclName());
3647 if (T.isNull())
3648 return true;
3649 FunctionParam->setType(T);
3650 }
3651
Richard Smithf623c962012-04-17 00:58:00 +00003652 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
3653 ++FParamIdx;
3654 }
3655 }
Richard Smithf623c962012-04-17 00:58:00 +00003656
Richard Smith2e321552014-11-12 02:00:47 +00003657 return false;
Richard Smithf623c962012-04-17 00:58:00 +00003658}
3659
3660void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
3661 FunctionDecl *Decl) {
Richard Smithd3729422012-04-19 00:08:28 +00003662 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
3663 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
Richard Smithf623c962012-04-17 00:58:00 +00003664 return;
3665
3666 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
3667 InstantiatingTemplate::ExceptionSpecification());
Alp Tokerd4a72d52013-10-08 08:09:04 +00003668 if (Inst.isInvalid()) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003669 // We hit the instantiation depth limit. Clear the exception specification
3670 // so that our callers don't have to cope with EST_Uninstantiated.
Richard Smith8acb4282014-07-31 21:57:55 +00003671 UpdateExceptionSpec(Decl, EST_None);
Richard Smithf623c962012-04-17 00:58:00 +00003672 return;
Richard Smithd3b5c9082012-07-27 04:22:15 +00003673 }
Richard Smith54f18e82016-08-31 02:15:21 +00003674 if (Inst.isAlreadyInstantiating()) {
3675 // This exception specification indirectly depends on itself. Reject.
3676 // FIXME: Corresponding rule in the standard?
3677 Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
3678 UpdateExceptionSpec(Decl, EST_None);
3679 return;
3680 }
Richard Smithf623c962012-04-17 00:58:00 +00003681
3682 // Enter the scope of this instantiation. We don't use
3683 // PushDeclContext because we don't have a scope.
3684 Sema::ContextRAII savedContext(*this, Decl);
3685 LocalInstantiationScope Scope(*this);
3686
3687 MultiLevelTemplateArgumentList TemplateArgs =
Craig Topperc3ec1492014-05-26 06:22:03 +00003688 getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true);
Richard Smithf623c962012-04-17 00:58:00 +00003689
Richard Smithd3729422012-04-19 00:08:28 +00003690 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
Richard Smith2e321552014-11-12 02:00:47 +00003691 if (addInstantiatedParametersToScope(*this, Decl, Template, Scope,
3692 TemplateArgs)) {
3693 UpdateExceptionSpec(Decl, EST_None);
3694 return;
3695 }
Richard Smithf623c962012-04-17 00:58:00 +00003696
Richard Smith2e321552014-11-12 02:00:47 +00003697 SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
3698 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +00003699}
3700
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003701/// Initializes the common fields of an instantiation function
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003702/// declaration (New) from the corresponding fields of its template (Tmpl).
3703///
3704/// \returns true if there was an error
Mike Stump11289f42009-09-09 15:08:12 +00003705bool
3706TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003707 FunctionDecl *Tmpl) {
David Blaikie5a0956e2012-07-16 18:50:45 +00003708 if (Tmpl->isDeleted())
Alexis Hunt4a8ea102011-05-06 20:44:56 +00003709 New->setDeletedAsWritten();
Mike Stump11289f42009-09-09 15:08:12 +00003710
Richard Smith32918772017-02-14 00:25:28 +00003711 New->setImplicit(Tmpl->isImplicit());
3712
David Majnemerdbc0c8f2013-12-04 09:01:55 +00003713 // Forward the mangling number from the template to the instantiated decl.
3714 SemaRef.Context.setManglingNumber(New,
3715 SemaRef.Context.getManglingNumber(Tmpl));
3716
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003717 // If we are performing substituting explicitly-specified template arguments
3718 // or deduced template arguments into a function template and we reach this
3719 // point, we are now past the point where SFINAE applies and have committed
Mike Stump11289f42009-09-09 15:08:12 +00003720 // to keeping the new function template specialization. We therefore
3721 // convert the active template instantiation for the function template
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003722 // into a template instantiation for this specific function template
3723 // specialization, which is not a SFINAE context, so that we diagnose any
3724 // further errors in the declaration itself.
Richard Smith696e3122017-02-23 01:43:54 +00003725 typedef Sema::CodeSynthesisContext ActiveInstType;
3726 ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003727 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
3728 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump11289f42009-09-09 15:08:12 +00003729 if (FunctionTemplateDecl *FunTmpl
Nick Lewyckycc8990f2012-11-16 08:40:59 +00003730 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
Mike Stump11289f42009-09-09 15:08:12 +00003731 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003732 "Deduction from the wrong function template?");
Daniel Dunbar54c59642009-07-16 22:10:11 +00003733 (void) FunTmpl;
Gabor Horvath207e7b12018-02-10 14:04:45 +00003734 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003735 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
Nick Lewyckycc8990f2012-11-16 08:40:59 +00003736 ActiveInst.Entity = New;
Gabor Horvath207e7b12018-02-10 14:04:45 +00003737 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003738 }
3739 }
Mike Stump11289f42009-09-09 15:08:12 +00003740
Douglas Gregor049bdca2009-12-08 17:45:32 +00003741 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
3742 assert(Proto && "Function template without prototype?");
3743
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003744 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
John McCalldb40c7f2010-12-14 08:05:40 +00003745 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00003746
Richard Smithf623c962012-04-17 00:58:00 +00003747 // DR1330: In C++11, defer instantiation of a non-trivial
3748 // exception specification.
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003749 // DR1484: Local classes and their members are instantiated along with the
3750 // containing function.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003751 if (SemaRef.getLangOpts().CPlusPlus11 &&
Richard Smith8acb4282014-07-31 21:57:55 +00003752 EPI.ExceptionSpec.Type != EST_None &&
3753 EPI.ExceptionSpec.Type != EST_DynamicNone &&
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003754 EPI.ExceptionSpec.Type != EST_BasicNoexcept &&
Serge Pavlov73c6a242015-08-23 10:22:28 +00003755 !Tmpl->isLexicallyWithinFunctionOrMethod()) {
Richard Smithd3729422012-04-19 00:08:28 +00003756 FunctionDecl *ExceptionSpecTemplate = Tmpl;
Richard Smith8acb4282014-07-31 21:57:55 +00003757 if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
3758 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
Richard Smith185be182013-04-10 05:48:59 +00003759 ExceptionSpecificationType NewEST = EST_Uninstantiated;
Richard Smith8acb4282014-07-31 21:57:55 +00003760 if (EPI.ExceptionSpec.Type == EST_Unevaluated)
Richard Smith185be182013-04-10 05:48:59 +00003761 NewEST = EST_Unevaluated;
Richard Smithd3729422012-04-19 00:08:28 +00003762
Richard Smithf623c962012-04-17 00:58:00 +00003763 // Mark the function has having an uninstantiated exception specification.
3764 const FunctionProtoType *NewProto
3765 = New->getType()->getAs<FunctionProtoType>();
3766 assert(NewProto && "Template instantiation without function prototype?");
3767 EPI = NewProto->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00003768 EPI.ExceptionSpec.Type = NewEST;
3769 EPI.ExceptionSpec.SourceDecl = New;
3770 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
Reid Kleckner896b32f2013-06-10 20:51:09 +00003771 New->setType(SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003772 NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
Richard Smithf623c962012-04-17 00:58:00 +00003773 } else {
Faisal Vali40fd4ce2017-05-09 04:17:15 +00003774 Sema::ContextRAII SwitchContext(SemaRef, New);
Richard Smith2e321552014-11-12 02:00:47 +00003775 SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +00003776 }
Douglas Gregor049bdca2009-12-08 17:45:32 +00003777 }
3778
Rafael Espindolaba195cf2011-07-06 15:46:09 +00003779 // Get the definition. Leaves the variable unchanged if undefined.
Richard Smithf623c962012-04-17 00:58:00 +00003780 const FunctionDecl *Definition = Tmpl;
Rafael Espindolaba195cf2011-07-06 15:46:09 +00003781 Tmpl->isDefined(Definition);
3782
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00003783 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
3784 LateAttrs, StartingScope);
Douglas Gregor08329632010-06-15 17:05:35 +00003785
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003786 return false;
3787}
3788
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003789/// Initializes common fields of an instantiated method
Douglas Gregor21342092009-03-24 00:38:23 +00003790/// declaration (New) from the corresponding fields of its template
3791/// (Tmpl).
3792///
3793/// \returns true if there was an error
Mike Stump11289f42009-09-09 15:08:12 +00003794bool
3795TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor21342092009-03-24 00:38:23 +00003796 CXXMethodDecl *Tmpl) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003797 if (InitFunctionInstantiation(New, Tmpl))
3798 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003799
Richard Smith5159bbad2018-09-05 22:30:37 +00003800 if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11)
3801 SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New));
3802
Douglas Gregor21342092009-03-24 00:38:23 +00003803 New->setAccess(Tmpl->getAccess());
Fariborz Jahanian6dfc1972009-12-03 18:44:40 +00003804 if (Tmpl->isVirtualAsWritten())
Douglas Gregor11c024b2010-09-28 20:50:54 +00003805 New->setVirtualAsWritten(true);
Douglas Gregor21342092009-03-24 00:38:23 +00003806
Douglas Gregor21342092009-03-24 00:38:23 +00003807 // FIXME: New needs a pointer to Tmpl
3808 return false;
3809}
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003810
Richard Smith50e291e2018-01-02 23:52:42 +00003811/// Instantiate (or find existing instantiation of) a function template with a
3812/// given set of template arguments.
3813///
3814/// Usually this should not be used, and template argument deduction should be
3815/// used in its place.
3816FunctionDecl *
3817Sema::InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
3818 const TemplateArgumentList *Args,
3819 SourceLocation Loc) {
3820 FunctionDecl *FD = FTD->getTemplatedDecl();
3821
3822 sema::TemplateDeductionInfo Info(Loc);
3823 InstantiatingTemplate Inst(
3824 *this, Loc, FTD, Args->asArray(),
3825 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
3826 if (Inst.isInvalid())
3827 return nullptr;
3828
3829 ContextRAII SavedContext(*this, FD);
3830 MultiLevelTemplateArgumentList MArgs(*Args);
3831
3832 return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs));
3833}
3834
Reid Kleckner61195e12017-01-05 01:08:22 +00003835/// In the MS ABI, we need to instantiate default arguments of dllexported
3836/// default constructors along with the constructor definition. This allows IR
3837/// gen to emit a constructor closure which calls the default constructor with
3838/// its default arguments.
3839static void InstantiateDefaultCtorDefaultArgs(Sema &S,
3840 CXXConstructorDecl *Ctor) {
3841 assert(S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
3842 Ctor->isDefaultConstructor());
3843 unsigned NumParams = Ctor->getNumParams();
3844 if (NumParams == 0)
3845 return;
3846 DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>();
3847 if (!Attr)
3848 return;
3849 for (unsigned I = 0; I != NumParams; ++I) {
3850 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), Ctor,
3851 Ctor->getParamDecl(I));
3852 S.DiscardCleanupsInEvaluationContext();
3853 }
3854}
3855
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003856/// Instantiate the definition of the given function from its
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003857/// template.
3858///
Douglas Gregordda7ced2009-06-30 17:20:14 +00003859/// \param PointOfInstantiation the point at which the instantiation was
3860/// required. Note that this is not precisely a "point of instantiation"
3861/// for the function, but it's close.
3862///
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003863/// \param Function the already-instantiated declaration of a
Douglas Gregordda7ced2009-06-30 17:20:14 +00003864/// function template specialization or member function of a class template
3865/// specialization.
3866///
3867/// \param Recursive if true, recursively instantiates any functions that
3868/// are required by this instantiation.
Douglas Gregora8b89d22009-10-15 14:05:49 +00003869///
3870/// \param DefinitionRequired if true, then we are performing an explicit
3871/// instantiation where the body of the function is required. Complain if
3872/// there is no such body.
Douglas Gregor85673582009-05-18 17:01:57 +00003873void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregordda7ced2009-06-30 17:20:14 +00003874 FunctionDecl *Function,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003875 bool Recursive,
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00003876 bool DefinitionRequired,
3877 bool AtEndOfTU) {
Richard Smithcb189572017-10-28 01:15:00 +00003878 if (Function->isInvalidDecl() || Function->isDefined() ||
3879 isa<CXXDeductionGuideDecl>(Function))
Douglas Gregorb4850462009-05-14 23:26:13 +00003880 return;
3881
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003882 // Never instantiate an explicit specialization except if it is a class scope
3883 // explicit specialization.
Vassil Vassilevb21ee082016-08-18 22:01:25 +00003884 TemplateSpecializationKind TSK = Function->getTemplateSpecializationKind();
3885 if (TSK == TSK_ExplicitSpecialization &&
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003886 !Function->getClassScopeSpecializationPattern())
Douglas Gregor86d142a2009-10-08 07:24:58 +00003887 return;
Douglas Gregor69f6a362010-05-17 17:34:56 +00003888
Douglas Gregor24c332b2009-05-14 21:06:31 +00003889 // Find the function body that we'll be substituting.
Douglas Gregorafca3b42009-10-27 20:53:28 +00003890 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Alexis Hunt23f6b832011-05-27 20:00:14 +00003891 assert(PatternDecl && "instantiating a non-template");
3892
Richard Smith6f4e2e02016-08-23 19:41:39 +00003893 const FunctionDecl *PatternDef = PatternDecl->getDefinition();
Richard Smith3f6865a82016-08-23 21:12:54 +00003894 Stmt *Pattern = nullptr;
3895 if (PatternDef) {
3896 Pattern = PatternDef->getBody(PatternDef);
Richard Smith6f4e2e02016-08-23 19:41:39 +00003897 PatternDecl = PatternDef;
Richard Smith6c7161162017-08-12 01:46:03 +00003898 if (PatternDef->willHaveBody())
3899 PatternDef = nullptr;
Richard Smith3f6865a82016-08-23 21:12:54 +00003900 }
Douglas Gregor24c332b2009-05-14 21:06:31 +00003901
Vassil Vassilevb21ee082016-08-18 22:01:25 +00003902 // FIXME: We need to track the instantiation stack in order to know which
3903 // definitions should be visible within this instantiation.
3904 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function,
3905 Function->getInstantiatedFromMemberFunction(),
Richard Smith6f4e2e02016-08-23 19:41:39 +00003906 PatternDecl, PatternDef, TSK,
3907 /*Complain*/DefinitionRequired)) {
3908 if (DefinitionRequired)
3909 Function->setInvalidDecl();
3910 else if (TSK == TSK_ExplicitInstantiationDefinition) {
3911 // Try again at the end of the translation unit (at which point a
3912 // definition will be required).
3913 assert(!Recursive);
Sunil Srivastava15ed2922017-06-20 22:08:44 +00003914 Function->setInstantiationIsPending(true);
Richard Smith6f4e2e02016-08-23 19:41:39 +00003915 PendingInstantiations.push_back(
3916 std::make_pair(Function, PointOfInstantiation));
3917 } else if (TSK == TSK_ImplicitInstantiation) {
Nick Lewycky2adab1b2018-01-02 19:10:12 +00003918 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003919 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
Richard Smith6f4e2e02016-08-23 19:41:39 +00003920 Diag(PointOfInstantiation, diag::warn_func_template_missing)
3921 << Function;
3922 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
3923 if (getLangOpts().CPlusPlus11)
3924 Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
3925 << Function;
3926 }
3927 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +00003928
Richard Smith6f4e2e02016-08-23 19:41:39 +00003929 return;
3930 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +00003931
Francois Pichet1c229c02011-04-22 22:18:13 +00003932 // Postpone late parsed template instantiations.
Alexis Hunt23f6b832011-05-27 20:00:14 +00003933 if (PatternDecl->isLateTemplateParsed() &&
Nick Lewycky610128e2011-05-12 03:51:24 +00003934 !LateTemplateParser) {
Sunil Srivastava15ed2922017-06-20 22:08:44 +00003935 Function->setInstantiationIsPending(true);
Reid Kleckner24bd88c2018-03-26 18:22:47 +00003936 LateParsedInstantiations.push_back(
3937 std::make_pair(Function, PointOfInstantiation));
Francois Pichet1c229c02011-04-22 22:18:13 +00003938 return;
3939 }
3940
Nico Weberae4bb8c2014-08-15 23:21:41 +00003941 // If we're performing recursive template instantiation, create our own
3942 // queue of pending implicit instantiations that we will instantiate later,
3943 // while we're still within our own instantiation context.
3944 // This has to happen before LateTemplateParser below is called, so that
3945 // it marks vtables used in late parsed templates as used.
Richard Smith4f3e3812017-05-20 01:36:41 +00003946 GlobalEagerInstantiationScope GlobalInstantiations(*this,
3947 /*Enabled=*/Recursive);
3948 LocalEagerInstantiationScope LocalInstantiations(*this);
Nico Weberae4bb8c2014-08-15 23:21:41 +00003949
David Majnemerf0a84f22013-08-16 08:29:13 +00003950 // Call the LateTemplateParser callback if there is a need to late parse
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003951 // a templated function definition.
Alexis Hunt23f6b832011-05-27 20:00:14 +00003952 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
Francois Pichet1c229c02011-04-22 22:18:13 +00003953 LateTemplateParser) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00003954 // FIXME: Optimize to allow individual templates to be deserialized.
3955 if (PatternDecl->isFromASTFile())
3956 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
3957
Justin Lebar28f09c52016-10-10 16:26:08 +00003958 auto LPTIter = LateParsedTemplateMap.find(PatternDecl);
3959 assert(LPTIter != LateParsedTemplateMap.end() &&
3960 "missing LateParsedTemplate");
3961 LateTemplateParser(OpaqueParser, *LPTIter->second);
Francois Pichet1c229c02011-04-22 22:18:13 +00003962 Pattern = PatternDecl->getBody(PatternDecl);
3963 }
3964
Richard Smith6f4e2e02016-08-23 19:41:39 +00003965 // Note, we should never try to instantiate a deleted function template.
Ilya Biryukova27eca22017-12-20 14:32:38 +00003966 assert((Pattern || PatternDecl->isDefaulted() ||
3967 PatternDecl->hasSkippedBody()) &&
Richard Smith6f4e2e02016-08-23 19:41:39 +00003968 "unexpected kind of function template definition");
Douglas Gregor24c332b2009-05-14 21:06:31 +00003969
Richard Smith2a7d4812013-05-04 07:00:32 +00003970 // C++1y [temp.explicit]p10:
3971 // Except for inline functions, declarations with types deduced from their
3972 // initializer or return value, and class template specializations, other
3973 // explicit instantiation declarations have the effect of suppressing the
3974 // implicit instantiation of the entity to which they refer.
Vassil Vassilevb21ee082016-08-18 22:01:25 +00003975 if (TSK == TSK_ExplicitInstantiationDeclaration &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003976 !PatternDecl->isInlined() &&
Alp Toker314cc812014-01-25 16:55:45 +00003977 !PatternDecl->getReturnType()->getContainedAutoType())
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003978 return;
Mike Stump11289f42009-09-09 15:08:12 +00003979
Richard Smith195d8ef2014-05-29 03:15:31 +00003980 if (PatternDecl->isInlined()) {
3981 // Function, and all later redeclarations of it (from imported modules,
3982 // for instance), are now implicitly inline.
3983 for (auto *D = Function->getMostRecentDecl(); /**/;
3984 D = D->getPreviousDecl()) {
3985 D->setImplicitlyInline();
3986 if (D == Function)
3987 break;
3988 }
3989 }
Richard Smithf3814ad2013-01-25 00:08:28 +00003990
Douglas Gregor85673582009-05-18 17:01:57 +00003991 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
Richard Smith54f18e82016-08-31 02:15:21 +00003992 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003993 return;
Jordan Rose1e879d82018-03-23 00:07:18 +00003994 PrettyDeclStackTraceEntry CrashInfo(Context, Function, SourceLocation(),
Richard Smithe19b95d2016-05-26 20:23:13 +00003995 "instantiating function definition");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003996
Vassil Vassilevb21ee082016-08-18 22:01:25 +00003997 // The instantiation is visible here, even if it was first declared in an
3998 // unimported module.
Richard Smith90dc5252017-06-23 01:04:34 +00003999 Function->setVisibleDespiteOwningModule();
Vassil Vassilevb21ee082016-08-18 22:01:25 +00004000
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00004001 // Copy the inner loc start from the pattern.
4002 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
4003
Faisal Valid143a0c2017-04-01 21:30:49 +00004004 EnterExpressionEvaluationContext EvalContext(
4005 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
Douglas Gregor67da0d92009-05-15 17:59:04 +00004006
Douglas Gregorb4850462009-05-14 23:26:13 +00004007 // Introduce a new scope where local variable instantiations will be
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004008 // recorded, unless we're actually a member function within a local
4009 // class, in which case we need to merge our results with the parent
4010 // scope (of the enclosing function).
4011 bool MergeWithParentScope = false;
4012 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
4013 MergeWithParentScope = Rec->isLocalClass();
4014
4015 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump11289f42009-09-09 15:08:12 +00004016
Richard Smithbd305122012-12-11 01:14:52 +00004017 if (PatternDecl->isDefaulted())
Alexis Hunt61ae8d32011-05-23 23:14:04 +00004018 SetDeclDefaulted(Function, PatternDecl->getLocation());
Richard Smithbd305122012-12-11 01:14:52 +00004019 else {
Richard Smithcc928662014-10-17 20:37:29 +00004020 MultiLevelTemplateArgumentList TemplateArgs =
4021 getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl);
4022
4023 // Substitute into the qualifier; we can get a substitution failure here
4024 // through evil use of alias templates.
4025 // FIXME: Is CurContext correct for this? Should we go to the (instantiation
4026 // of the) lexical context of the pattern?
4027 SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
4028
Craig Topperc3ec1492014-05-26 06:22:03 +00004029 ActOnStartOfFunctionDef(nullptr, Function);
Richard Smithbd305122012-12-11 01:14:52 +00004030
4031 // Enter the scope of this instantiation. We don't use
4032 // PushDeclContext because we don't have a scope.
4033 Sema::ContextRAII savedContext(*this, Function);
4034
Richard Smith2e321552014-11-12 02:00:47 +00004035 if (addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
4036 TemplateArgs))
4037 return;
Richard Smithbd305122012-12-11 01:14:52 +00004038
Ilya Biryukov0ee4a082018-03-14 13:18:30 +00004039 StmtResult Body;
Ilya Biryukova27eca22017-12-20 14:32:38 +00004040 if (PatternDecl->hasSkippedBody()) {
4041 ActOnSkippedFunctionBody(Function);
Ilya Biryukov0ee4a082018-03-14 13:18:30 +00004042 Body = nullptr;
Ilya Biryukova27eca22017-12-20 14:32:38 +00004043 } else {
Ilya Biryukov95f0d322017-12-28 13:05:46 +00004044 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) {
4045 // If this is a constructor, instantiate the member initializers.
4046 InstantiateMemInitializers(Ctor, cast<CXXConstructorDecl>(PatternDecl),
4047 TemplateArgs);
4048
4049 // If this is an MS ABI dllexport default constructor, instantiate any
4050 // default arguments.
4051 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4052 Ctor->isDefaultConstructor()) {
4053 InstantiateDefaultCtorDefaultArgs(*this, Ctor);
4054 }
4055 }
4056
Ilya Biryukova27eca22017-12-20 14:32:38 +00004057 // Instantiate the function body.
Ilya Biryukov0ee4a082018-03-14 13:18:30 +00004058 Body = SubstStmt(Pattern, TemplateArgs);
Alexis Hunt61ae8d32011-05-23 23:14:04 +00004059
Ilya Biryukova27eca22017-12-20 14:32:38 +00004060 if (Body.isInvalid())
4061 Function->setInvalidDecl();
Ilya Biryukova27eca22017-12-20 14:32:38 +00004062 }
Ilya Biryukov0ee4a082018-03-14 13:18:30 +00004063 // FIXME: finishing the function body while in an expression evaluation
4064 // context seems wrong. Investigate more.
4065 ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true);
Richard Smithbd305122012-12-11 01:14:52 +00004066
4067 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
4068
Richard Smithd28ac5b2014-03-22 23:33:22 +00004069 if (auto *Listener = getASTMutationListener())
4070 Listener->FunctionDefinitionInstantiated(Function);
Richard Smith0ac1b8f2014-03-22 01:43:32 +00004071
Richard Smithbd305122012-12-11 01:14:52 +00004072 savedContext.pop();
Mike Stump11289f42009-09-09 15:08:12 +00004073 }
4074
Douglas Gregor28ad4b52009-05-26 20:50:29 +00004075 DeclGroupRef DG(Function);
4076 Consumer.HandleTopLevelDecl(DG);
Mike Stump11289f42009-09-09 15:08:12 +00004077
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004078 // This class may have local implicit instantiations that need to be
4079 // instantiation within this scope.
Richard Smith4f3e3812017-05-20 01:36:41 +00004080 LocalInstantiations.perform();
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004081 Scope.Exit();
Richard Smith4f3e3812017-05-20 01:36:41 +00004082 GlobalInstantiations.perform();
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00004083}
4084
Larisse Voufo39a1e502013-08-06 01:03:05 +00004085VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
4086 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
4087 const TemplateArgumentList &TemplateArgList,
4088 const TemplateArgumentListInfo &TemplateArgsInfo,
4089 SmallVectorImpl<TemplateArgument> &Converted,
4090 SourceLocation PointOfInstantiation, void *InsertPos,
4091 LateInstantiatedAttrVec *LateAttrs,
4092 LocalInstantiationScope *StartingScope) {
4093 if (FromVar->isInvalidDecl())
Craig Topperc3ec1492014-05-26 06:22:03 +00004094 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004095
4096 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
Alp Tokerd4a72d52013-10-08 08:09:04 +00004097 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00004098 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004099
4100 MultiLevelTemplateArgumentList TemplateArgLists;
4101 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
4102
Richard Smith8809a0c2013-09-27 20:14:12 +00004103 // Instantiate the first declaration of the variable template: for a partial
4104 // specialization of a static data member template, the first declaration may
4105 // or may not be the declaration in the class; if it's in the class, we want
4106 // to instantiate a member in the class (a declaration), and if it's outside,
4107 // we want to instantiate a definition.
Richard Smithbeef3452014-01-16 23:39:20 +00004108 //
4109 // If we're instantiating an explicitly-specialized member template or member
4110 // partial specialization, don't do this. The member specialization completely
4111 // replaces the original declaration in this case.
4112 bool IsMemberSpec = false;
4113 if (VarTemplatePartialSpecializationDecl *PartialSpec =
4114 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar))
4115 IsMemberSpec = PartialSpec->isMemberSpecialization();
4116 else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate())
4117 IsMemberSpec = FromTemplate->isMemberSpecialization();
4118 if (!IsMemberSpec)
4119 FromVar = FromVar->getFirstDecl();
Richard Smith8809a0c2013-09-27 20:14:12 +00004120
Manuel Klimek5843add2013-09-30 13:29:01 +00004121 MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
4122 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
4123 MultiLevelList);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004124
4125 // TODO: Set LateAttrs and StartingScope ...
4126
4127 return cast_or_null<VarTemplateSpecializationDecl>(
4128 Instantiator.VisitVarTemplateSpecializationDecl(
4129 VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
4130}
4131
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004132/// Instantiates a variable template specialization by completing it
Larisse Voufo39a1e502013-08-06 01:03:05 +00004133/// with appropriate type information and initializer.
4134VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
4135 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
4136 const MultiLevelTemplateArgumentList &TemplateArgs) {
Richard Smith435e6472017-12-02 02:48:42 +00004137 assert(PatternDecl->isThisDeclarationADefinition() &&
4138 "don't have a definition to instantiate from");
Larisse Voufo39a1e502013-08-06 01:03:05 +00004139
4140 // Do substitution on the type of the declaration
4141 TypeSourceInfo *DI =
Richard Smith8809a0c2013-09-27 20:14:12 +00004142 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00004143 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
4144 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00004145 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004146
4147 // Update the type of this variable template specialization.
4148 VarSpec->setType(DI->getType());
4149
Richard Smith435e6472017-12-02 02:48:42 +00004150 // Convert the declaration into a definition now.
4151 VarSpec->setCompleteDefinition();
4152
Larisse Voufo39a1e502013-08-06 01:03:05 +00004153 // Instantiate the initializer.
4154 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
4155
4156 return VarSpec;
4157}
4158
4159/// BuildVariableInstantiation - Used after a new variable has been created.
4160/// Sets basic variable data and decides whether to postpone the
4161/// variable instantiation.
4162void Sema::BuildVariableInstantiation(
4163 VarDecl *NewVar, VarDecl *OldVar,
4164 const MultiLevelTemplateArgumentList &TemplateArgs,
Richard Smith541b38b2013-09-20 01:15:31 +00004165 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
4166 LocalInstantiationScope *StartingScope,
Larisse Voufo72caf2b2013-08-22 00:59:14 +00004167 bool InstantiatingVarTemplate) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004168
Richard Smith541b38b2013-09-20 01:15:31 +00004169 // If we are instantiating a local extern declaration, the
4170 // instantiation belongs lexically to the containing function.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004171 // If we are instantiating a static data member defined
4172 // out-of-line, the instantiation will have the same lexical
4173 // context (which will be a namespace scope) as the template.
Richard Smith541b38b2013-09-20 01:15:31 +00004174 if (OldVar->isLocalExternDecl()) {
4175 NewVar->setLocalExternDecl();
4176 NewVar->setLexicalDeclContext(Owner);
4177 } else if (OldVar->isOutOfLine())
Larisse Voufo39a1e502013-08-06 01:03:05 +00004178 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
4179 NewVar->setTSCSpec(OldVar->getTSCSpec());
4180 NewVar->setInitStyle(OldVar->getInitStyle());
4181 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
George Karpenkovec38cf72018-03-29 00:56:24 +00004182 NewVar->setObjCForDecl(OldVar->isObjCForDecl());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004183 NewVar->setConstexpr(OldVar->isConstexpr());
Richard Smithbb13c9a2013-09-28 04:02:39 +00004184 NewVar->setInitCapture(OldVar->isInitCapture());
Richard Smith1c34fb72013-08-13 18:18:50 +00004185 NewVar->setPreviousDeclInSameBlockScope(
4186 OldVar->isPreviousDeclInSameBlockScope());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004187 NewVar->setAccess(OldVar->getAccess());
4188
Richard Smith0b551192013-09-23 23:12:22 +00004189 if (!OldVar->isStaticDataMember()) {
Rafael Espindolae4865d22013-10-23 16:46:34 +00004190 if (OldVar->isUsed(false))
4191 NewVar->setIsUsed();
Larisse Voufo39a1e502013-08-06 01:03:05 +00004192 NewVar->setReferenced(OldVar->isReferenced());
4193 }
4194
4195 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
4196
Richard Smith541b38b2013-09-20 01:15:31 +00004197 LookupResult Previous(
4198 *this, NewVar->getDeclName(), NewVar->getLocation(),
4199 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
4200 : Sema::LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00004201 NewVar->isLocalExternDecl() ? Sema::ForExternalRedeclaration
4202 : forRedeclarationInCurContext());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004203
Argyrios Kyrtzidis91486222013-11-27 08:34:14 +00004204 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
4205 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
4206 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
Richard Smith1c34fb72013-08-13 18:18:50 +00004207 // We have a previous declaration. Use that one, so we merge with the
4208 // right type.
4209 if (NamedDecl *NewPrev = FindInstantiatedDecl(
4210 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
4211 Previous.addDecl(NewPrev);
4212 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
4213 OldVar->hasLinkage())
Larisse Voufo39a1e502013-08-06 01:03:05 +00004214 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
Larisse Voufo72caf2b2013-08-22 00:59:14 +00004215 CheckVariableDeclaration(NewVar, Previous);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004216
Richard Smith541b38b2013-09-20 01:15:31 +00004217 if (!InstantiatingVarTemplate) {
4218 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
4219 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
Larisse Voufo39a1e502013-08-06 01:03:05 +00004220 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
Richard Smith541b38b2013-09-20 01:15:31 +00004221 }
4222
4223 if (!OldVar->isOutOfLine()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004224 if (NewVar->getDeclContext()->isFunctionOrMethod())
4225 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
4226 }
4227
4228 // Link instantiations of static data members back to the template from
4229 // which they were instantiated.
Larisse Voufo72caf2b2013-08-22 00:59:14 +00004230 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate)
Larisse Voufo39a1e502013-08-06 01:03:05 +00004231 NewVar->setInstantiationOfStaticDataMember(OldVar,
4232 TSK_ImplicitInstantiation);
4233
David Majnemerdbc0c8f2013-12-04 09:01:55 +00004234 // Forward the mangling number from the template to the instantiated decl.
4235 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
David Majnemer2206bf52014-03-05 08:57:59 +00004236 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
David Majnemerdbc0c8f2013-12-04 09:01:55 +00004237
Richard Smith62f19e72016-06-25 00:15:56 +00004238 // Delay instantiation of the initializer for variable templates or inline
4239 // static data members until a definition of the variable is needed. We need
4240 // it right away if the type contains 'auto'.
Richard Smithd292b242014-03-16 01:00:40 +00004241 if ((!isa<VarTemplateSpecializationDecl>(NewVar) &&
Richard Smith62f19e72016-06-25 00:15:56 +00004242 !InstantiatingVarTemplate &&
Richard Smith93ee9ca2018-01-10 23:08:26 +00004243 !(OldVar->isInline() && OldVar->isThisDeclarationADefinition() &&
4244 !NewVar->isThisDeclarationADefinition())) ||
Richard Smithd292b242014-03-16 01:00:40 +00004245 NewVar->getType()->isUndeducedType())
Larisse Voufo39a1e502013-08-06 01:03:05 +00004246 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
4247
4248 // Diagnose unused local variables with dependent types, where the diagnostic
4249 // will have been deferred.
4250 if (!NewVar->isInvalidDecl() &&
Nico Weber72889432014-09-06 01:25:55 +00004251 NewVar->getDeclContext()->isFunctionOrMethod() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004252 OldVar->getType()->isDependentType())
4253 DiagnoseUnusedDecl(NewVar);
4254}
4255
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004256/// Instantiate the initializer of a variable.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004257void Sema::InstantiateVariableInitializer(
4258 VarDecl *Var, VarDecl *OldVar,
4259 const MultiLevelTemplateArgumentList &TemplateArgs) {
Richard Smith891fc7f2017-12-05 01:31:47 +00004260 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
4261 L->VariableDefinitionInstantiated(Var);
4262
Richard Smith62f19e72016-06-25 00:15:56 +00004263 // We propagate the 'inline' flag with the initializer, because it
4264 // would otherwise imply that the variable is a definition for a
4265 // non-static data member.
4266 if (OldVar->isInlineSpecified())
4267 Var->setInlineSpecified();
4268 else if (OldVar->isInline())
4269 Var->setImplicitlyInline();
Larisse Voufo39a1e502013-08-06 01:03:05 +00004270
Larisse Voufo39a1e502013-08-06 01:03:05 +00004271 if (OldVar->getInit()) {
Richard Smithc95d2c52017-09-22 04:25:05 +00004272 EnterExpressionEvaluationContext Evaluated(
4273 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, Var);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004274
4275 // Instantiate the initializer.
Akira Hatanakab87faff2016-04-28 23:50:12 +00004276 ExprResult Init;
4277
4278 {
4279 ContextRAII SwitchContext(*this, Var->getDeclContext());
4280 Init = SubstInitializer(OldVar->getInit(), TemplateArgs,
4281 OldVar->getInitStyle() == VarDecl::CallInit);
4282 }
4283
Larisse Voufo39a1e502013-08-06 01:03:05 +00004284 if (!Init.isInvalid()) {
Hans Wennborg91ebe6e2014-06-10 00:55:51 +00004285 Expr *InitExpr = Init.get();
4286
Richard Smith95b83e92014-07-10 20:53:43 +00004287 if (Var->hasAttr<DLLImportAttr>() &&
4288 (!InitExpr ||
4289 !InitExpr->isConstantInitializer(getASTContext(), false))) {
Hans Wennborg91ebe6e2014-06-10 00:55:51 +00004290 // Do not dynamically initialize dllimport variables.
Hans Wennborg91ebe6e2014-06-10 00:55:51 +00004291 } else if (InitExpr) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004292 bool DirectInit = OldVar->isDirectInit();
Richard Smith3beb7c62017-01-12 02:27:38 +00004293 AddInitializerToDecl(Var, InitExpr, DirectInit);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004294 } else
Richard Smith3beb7c62017-01-12 02:27:38 +00004295 ActOnUninitializedDecl(Var);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004296 } else {
4297 // FIXME: Not too happy about invalidating the declaration
4298 // because of a bogus initializer.
4299 Var->setInvalidDecl();
4300 }
Richard Smith54f18e82016-08-31 02:15:21 +00004301 } else {
George Burgess IV18b28a82018-03-20 03:27:44 +00004302 // `inline` variables are a definition and declaration all in one; we won't
4303 // pick up an initializer from anywhere else.
4304 if (Var->isStaticDataMember() && !Var->isInline()) {
Richard Smith54f18e82016-08-31 02:15:21 +00004305 if (!Var->isOutOfLine())
4306 return;
4307
4308 // If the declaration inside the class had an initializer, don't add
4309 // another one to the out-of-line definition.
4310 if (OldVar->getFirstDecl()->hasInit())
4311 return;
4312 }
4313
4314 // We'll add an initializer to a for-range declaration later.
George Karpenkovec38cf72018-03-29 00:56:24 +00004315 if (Var->isCXXForRangeDecl() || Var->isObjCForDecl())
Richard Smith54f18e82016-08-31 02:15:21 +00004316 return;
4317
Richard Smith3beb7c62017-01-12 02:27:38 +00004318 ActOnUninitializedDecl(Var);
Richard Smith54f18e82016-08-31 02:15:21 +00004319 }
Artem Beleviche9fa53a2018-06-06 22:37:25 +00004320
4321 if (getLangOpts().CUDA)
4322 checkAllowedCUDAInitializer(Var);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004323}
4324
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004325/// Instantiate the definition of the given variable from its
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00004326/// template.
4327///
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004328/// \param PointOfInstantiation the point at which the instantiation was
4329/// required. Note that this is not precisely a "point of instantiation"
Richard Smith891fc7f2017-12-05 01:31:47 +00004330/// for the variable, but it's close.
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004331///
Richard Smith891fc7f2017-12-05 01:31:47 +00004332/// \param Var the already-instantiated declaration of a templated variable.
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004333///
4334/// \param Recursive if true, recursively instantiates any functions that
4335/// are required by this instantiation.
Douglas Gregora8b89d22009-10-15 14:05:49 +00004336///
4337/// \param DefinitionRequired if true, then we are performing an explicit
Richard Smith891fc7f2017-12-05 01:31:47 +00004338/// instantiation where a definition of the variable is required. Complain
4339/// if there is no such definition.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004340void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
4341 VarDecl *Var, bool Recursive,
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00004342 bool DefinitionRequired, bool AtEndOfTU) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004343 if (Var->isInvalidDecl())
4344 return;
Mike Stump11289f42009-09-09 15:08:12 +00004345
Larisse Voufo39a1e502013-08-06 01:03:05 +00004346 VarTemplateSpecializationDecl *VarSpec =
4347 dyn_cast<VarTemplateSpecializationDecl>(Var);
Craig Topperc3ec1492014-05-26 06:22:03 +00004348 VarDecl *PatternDecl = nullptr, *Def = nullptr;
Richard Smith8809a0c2013-09-27 20:14:12 +00004349 MultiLevelTemplateArgumentList TemplateArgs =
4350 getTemplateInstantiationArgs(Var);
Mike Stump11289f42009-09-09 15:08:12 +00004351
Larisse Voufo39a1e502013-08-06 01:03:05 +00004352 if (VarSpec) {
Richard Smith8809a0c2013-09-27 20:14:12 +00004353 // If this is a variable template specialization, make sure that it is
4354 // non-dependent, then find its instantiation pattern.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004355 bool InstantiationDependent = false;
4356 assert(!TemplateSpecializationType::anyDependentTemplateArguments(
4357 VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
4358 "Only instantiate variable template specializations that are "
4359 "not type-dependent");
Larisse Voufo4154f462013-08-06 03:57:41 +00004360 (void)InstantiationDependent;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004361
Richard Smith8809a0c2013-09-27 20:14:12 +00004362 // Find the variable initialization that we'll be substituting. If the
4363 // pattern was instantiated from a member template, look back further to
4364 // find the real pattern.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004365 assert(VarSpec->getSpecializedTemplate() &&
4366 "Specialization without specialized template?");
4367 llvm::PointerUnion<VarTemplateDecl *,
4368 VarTemplatePartialSpecializationDecl *> PatternPtr =
4369 VarSpec->getSpecializedTemplateOrPartial();
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00004370 if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00004371 VarTemplatePartialSpecializationDecl *Tmpl =
4372 PatternPtr.get<VarTemplatePartialSpecializationDecl *>();
4373 while (VarTemplatePartialSpecializationDecl *From =
4374 Tmpl->getInstantiatedFromMember()) {
4375 if (Tmpl->isMemberSpecialization())
4376 break;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00004377
Richard Smith8809a0c2013-09-27 20:14:12 +00004378 Tmpl = From;
4379 }
4380 PatternDecl = Tmpl;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00004381 } else {
Richard Smith8809a0c2013-09-27 20:14:12 +00004382 VarTemplateDecl *Tmpl = PatternPtr.get<VarTemplateDecl *>();
4383 while (VarTemplateDecl *From =
4384 Tmpl->getInstantiatedFromMemberTemplate()) {
4385 if (Tmpl->isMemberSpecialization())
4386 break;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00004387
Richard Smith8809a0c2013-09-27 20:14:12 +00004388 Tmpl = From;
4389 }
4390 PatternDecl = Tmpl->getTemplatedDecl();
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00004391 }
Richard Smith8809a0c2013-09-27 20:14:12 +00004392
4393 // If this is a static data member template, there might be an
4394 // uninstantiated initializer on the declaration. If so, instantiate
4395 // it now.
Richard Smith891fc7f2017-12-05 01:31:47 +00004396 //
4397 // FIXME: This largely duplicates what we would do below. The difference
4398 // is that along this path we may instantiate an initializer from an
4399 // in-class declaration of the template and instantiate the definition
4400 // from a separate out-of-class definition.
Richard Smith8809a0c2013-09-27 20:14:12 +00004401 if (PatternDecl->isStaticDataMember() &&
Rafael Espindola8db352d2013-10-17 15:37:26 +00004402 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
Richard Smith8809a0c2013-09-27 20:14:12 +00004403 !Var->hasInit()) {
4404 // FIXME: Factor out the duplicated instantiation context setup/tear down
4405 // code here.
4406 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
Richard Smith54f18e82016-08-31 02:15:21 +00004407 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
Richard Smith8809a0c2013-09-27 20:14:12 +00004408 return;
Jordan Rose1e879d82018-03-23 00:07:18 +00004409 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
Richard Smithe19b95d2016-05-26 20:23:13 +00004410 "instantiating variable initializer");
Richard Smith8809a0c2013-09-27 20:14:12 +00004411
Richard Smithedbc6e92016-10-14 21:41:24 +00004412 // The instantiation is visible here, even if it was first declared in an
4413 // unimported module.
Richard Smith90dc5252017-06-23 01:04:34 +00004414 Var->setVisibleDespiteOwningModule();
Richard Smithedbc6e92016-10-14 21:41:24 +00004415
Richard Smith8809a0c2013-09-27 20:14:12 +00004416 // If we're performing recursive template instantiation, create our own
4417 // queue of pending implicit instantiations that we will instantiate
4418 // later, while we're still within our own instantiation context.
Richard Smith4f3e3812017-05-20 01:36:41 +00004419 GlobalEagerInstantiationScope GlobalInstantiations(*this,
4420 /*Enabled=*/Recursive);
Richard Smith8809a0c2013-09-27 20:14:12 +00004421 LocalInstantiationScope Local(*this);
Richard Smith4f3e3812017-05-20 01:36:41 +00004422 LocalEagerInstantiationScope LocalInstantiations(*this);
Richard Smith8809a0c2013-09-27 20:14:12 +00004423
4424 // Enter the scope of this instantiation. We don't use
4425 // PushDeclContext because we don't have a scope.
4426 ContextRAII PreviousContext(*this, Var->getDeclContext());
4427 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
4428 PreviousContext.pop();
4429
Richard Smith8809a0c2013-09-27 20:14:12 +00004430 // This variable may have local implicit instantiations that need to be
4431 // instantiated within this scope.
Richard Smith4f3e3812017-05-20 01:36:41 +00004432 LocalInstantiations.perform();
Richard Smith8809a0c2013-09-27 20:14:12 +00004433 Local.Exit();
Richard Smith4f3e3812017-05-20 01:36:41 +00004434 GlobalInstantiations.perform();
Richard Smith8809a0c2013-09-27 20:14:12 +00004435 }
4436
4437 // Find actual definition
4438 Def = PatternDecl->getDefinition(getASTContext());
4439 } else {
4440 // If this is a static data member, find its out-of-line definition.
4441 assert(Var->isStaticDataMember() && "not a static data member?");
4442 PatternDecl = Var->getInstantiatedFromStaticDataMember();
4443
4444 assert(PatternDecl && "data member was not instantiated from a template?");
4445 assert(PatternDecl->isStaticDataMember() && "not a static data member?");
Richard Smith62f19e72016-06-25 00:15:56 +00004446 Def = PatternDecl->getDefinition();
Larisse Voufo39a1e502013-08-06 01:03:05 +00004447 }
4448
Richard Smithedbc6e92016-10-14 21:41:24 +00004449 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
Richard Smith6739a102016-05-05 00:56:12 +00004450
Richard Smith8809a0c2013-09-27 20:14:12 +00004451 // If we don't have a definition of the variable template, we won't perform
4452 // any instantiation. Rather, we rely on the user to instantiate this
4453 // definition (or provide a specialization for it) in another translation
4454 // unit.
Richard Smithedbc6e92016-10-14 21:41:24 +00004455 if (!Def && !DefinitionRequired) {
4456 if (TSK == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth54080172010-08-25 08:44:16 +00004457 PendingInstantiations.push_back(
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004458 std::make_pair(Var, PointOfInstantiation));
Richard Smithedbc6e92016-10-14 21:41:24 +00004459 } else if (TSK == TSK_ImplicitInstantiation) {
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00004460 // Warn about missing definition at the end of translation unit.
Nick Lewycky2adab1b2018-01-02 19:10:12 +00004461 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004462 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00004463 Diag(PointOfInstantiation, diag::warn_var_template_missing)
4464 << Var;
4465 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
4466 if (getLangOpts().CPlusPlus11)
4467 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
4468 }
Richard Smithedbc6e92016-10-14 21:41:24 +00004469 return;
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004470 }
4471
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004472 }
4473
Richard Smithedbc6e92016-10-14 21:41:24 +00004474 // FIXME: We need to track the instantiation stack in order to know which
4475 // definitions should be visible within this instantiation.
4476 // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
4477 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var,
4478 /*InstantiatedFromMember*/false,
4479 PatternDecl, Def, TSK,
4480 /*Complain*/DefinitionRequired))
4481 return;
4482
Rafael Espindola189fa742012-03-05 10:54:55 +00004483
Douglas Gregor86d142a2009-10-08 07:24:58 +00004484 // Never instantiate an explicit specialization.
Rafael Espindola189fa742012-03-05 10:54:55 +00004485 if (TSK == TSK_ExplicitSpecialization)
Douglas Gregor86d142a2009-10-08 07:24:58 +00004486 return;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004487
Larisse Voufo39a1e502013-08-06 01:03:05 +00004488 // C++11 [temp.explicit]p10:
Richard Smith4309b662017-10-18 22:45:01 +00004489 // Except for inline functions, const variables of literal types, variables
4490 // of reference types, [...] explicit instantiation declarations
Larisse Voufo39a1e502013-08-06 01:03:05 +00004491 // have the effect of suppressing the implicit instantiation of the entity
4492 // to which they refer.
Richard Smith4309b662017-10-18 22:45:01 +00004493 if (TSK == TSK_ExplicitInstantiationDeclaration &&
4494 !Var->isUsableInConstantExpressions(getASTContext()))
Douglas Gregor86d142a2009-10-08 07:24:58 +00004495 return;
Mike Stump11289f42009-09-09 15:08:12 +00004496
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00004497 // Make sure to pass the instantiated variable to the consumer at the end.
4498 struct PassToConsumerRAII {
4499 ASTConsumer &Consumer;
4500 VarDecl *Var;
4501
4502 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
4503 : Consumer(Consumer), Var(Var) { }
4504
4505 ~PassToConsumerRAII() {
Richard Smith8809a0c2013-09-27 20:14:12 +00004506 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00004507 }
4508 } PassToConsumerRAII(Consumer, Var);
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00004509
Reid Klecknere07140e2015-04-15 01:08:06 +00004510 // If we already have a definition, we're done.
4511 if (VarDecl *Def = Var->getDefinition()) {
4512 // We may be explicitly instantiating something we've already implicitly
4513 // instantiated.
4514 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
4515 PointOfInstantiation);
Richard Smith8809a0c2013-09-27 20:14:12 +00004516 return;
Reid Klecknere07140e2015-04-15 01:08:06 +00004517 }
Douglas Gregor57d4f972011-06-03 03:35:07 +00004518
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004519 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
Richard Smith54f18e82016-08-31 02:15:21 +00004520 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004521 return;
Jordan Rose1e879d82018-03-23 00:07:18 +00004522 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
Richard Smithe19b95d2016-05-26 20:23:13 +00004523 "instantiating variable definition");
Mike Stump11289f42009-09-09 15:08:12 +00004524
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004525 // If we're performing recursive template instantiation, create our own
4526 // queue of pending implicit instantiations that we will instantiate later,
4527 // while we're still within our own instantiation context.
Richard Smith4f3e3812017-05-20 01:36:41 +00004528 GlobalEagerInstantiationScope GlobalInstantiations(*this,
4529 /*Enabled=*/Recursive);
Mike Stump11289f42009-09-09 15:08:12 +00004530
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004531 // Enter the scope of this instantiation. We don't use
4532 // PushDeclContext because we don't have a scope.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004533 ContextRAII PreviousContext(*this, Var->getDeclContext());
Douglas Gregora86bc002012-02-16 21:36:18 +00004534 LocalInstantiationScope Local(*this);
John McCall2957e3e2011-02-14 20:37:25 +00004535
Richard Smith4f3e3812017-05-20 01:36:41 +00004536 LocalEagerInstantiationScope LocalInstantiations(*this);
4537
Larisse Voufo39a1e502013-08-06 01:03:05 +00004538 VarDecl *OldVar = Var;
Richard Smith62f19e72016-06-25 00:15:56 +00004539 if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
4540 // We're instantiating an inline static data member whose definition was
4541 // provided inside the class.
Richard Smith62f19e72016-06-25 00:15:56 +00004542 InstantiateVariableInitializer(Var, Def, TemplateArgs);
4543 } else if (!VarSpec) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004544 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Richard Smith8809a0c2013-09-27 20:14:12 +00004545 TemplateArgs));
Richard Smith62f19e72016-06-25 00:15:56 +00004546 } else if (Var->isStaticDataMember() &&
4547 Var->getLexicalDeclContext()->isRecord()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00004548 // We need to instantiate the definition of a static data member template,
4549 // and all we have is the in-class declaration of it. Instantiate a separate
4550 // declaration of the definition.
4551 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
4552 TemplateArgs);
4553 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
Craig Topperc3ec1492014-05-26 06:22:03 +00004554 VarSpec->getSpecializedTemplate(), Def, nullptr,
Richard Smith8809a0c2013-09-27 20:14:12 +00004555 VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
4556 if (Var) {
4557 llvm::PointerUnion<VarTemplateDecl *,
4558 VarTemplatePartialSpecializationDecl *> PatternPtr =
4559 VarSpec->getSpecializedTemplateOrPartial();
4560 if (VarTemplatePartialSpecializationDecl *Partial =
4561 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
4562 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
4563 Partial, &VarSpec->getTemplateInstantiationArgs());
4564
4565 // Merge the definition with the declaration.
4566 LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
Richard Smithbecb92d2017-10-10 22:33:17 +00004567 LookupOrdinaryName, forRedeclarationInCurContext());
Richard Smith8809a0c2013-09-27 20:14:12 +00004568 R.addDecl(OldVar);
4569 MergeVarDecl(Var, R);
4570
4571 // Attach the initializer.
4572 InstantiateVariableInitializer(Var, Def, TemplateArgs);
4573 }
4574 } else
4575 // Complete the existing variable's definition with an appropriately
4576 // substituted type and initializer.
4577 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004578
4579 PreviousContext.pop();
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004580
4581 if (Var) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004582 PassToConsumerRAII.Var = Var;
Richard Smith8809a0c2013-09-27 20:14:12 +00004583 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
4584 OldVar->getPointOfInstantiation());
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004585 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004586
4587 // This variable may have local implicit instantiations that need to be
4588 // instantiated within this scope.
Richard Smith4f3e3812017-05-20 01:36:41 +00004589 LocalInstantiations.perform();
Douglas Gregora86bc002012-02-16 21:36:18 +00004590 Local.Exit();
Richard Smith4f3e3812017-05-20 01:36:41 +00004591 GlobalInstantiations.perform();
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00004592}
Douglas Gregor51783312009-05-27 05:35:12 +00004593
Anders Carlsson70553942009-08-29 05:16:22 +00004594void
4595Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
4596 const CXXConstructorDecl *Tmpl,
4597 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00004598
Richard Trieu9becef62011-09-09 03:18:59 +00004599 SmallVector<CXXCtorInitializer*, 4> NewInits;
Richard Smith60f2e1e2012-09-25 00:23:05 +00004600 bool AnyErrors = Tmpl->isInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004601
Anders Carlsson70553942009-08-29 05:16:22 +00004602 // Instantiate all the initializers.
Aaron Ballman0ad78302014-03-13 17:34:31 +00004603 for (const auto *Init : Tmpl->inits()) {
Chandler Carruthf92bd8c2010-09-03 21:54:20 +00004604 // Only instantiate written initializers, let Sema re-construct implicit
4605 // ones.
4606 if (!Init->isWritten())
4607 continue;
4608
Douglas Gregor44e7df62011-01-04 00:32:56 +00004609 SourceLocation EllipsisLoc;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004610
Douglas Gregor44e7df62011-01-04 00:32:56 +00004611 if (Init->isPackExpansion()) {
4612 // This is a pack expansion. We should expand it now.
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004613 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
Nick Lewycky2c308502013-06-13 00:45:47 +00004614 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
Douglas Gregor44e7df62011-01-04 00:32:56 +00004615 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
Nick Lewycky2c308502013-06-13 00:45:47 +00004616 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
Douglas Gregor44e7df62011-01-04 00:32:56 +00004617 bool ShouldExpand = false;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00004618 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00004619 Optional<unsigned> NumExpansions;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004620 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004621 BaseTL.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00004622 Unexpanded,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004623 TemplateArgs, ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00004624 RetainExpansion,
Douglas Gregor44e7df62011-01-04 00:32:56 +00004625 NumExpansions)) {
4626 AnyErrors = true;
4627 New->setInvalidDecl();
4628 continue;
4629 }
4630 assert(ShouldExpand && "Partial instantiation of base initializer?");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004631
4632 // Loop over all of the arguments in the argument pack(s),
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004633 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00004634 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
4635
4636 // Instantiate the initializer.
Sebastian Redla9351792012-02-11 23:51:47 +00004637 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4638 /*CXXDirectInit=*/true);
4639 if (TempInit.isInvalid()) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00004640 AnyErrors = true;
4641 break;
4642 }
4643
4644 // Instantiate the base type.
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004645 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004646 TemplateArgs,
4647 Init->getSourceLocation(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004648 New->getDeclName());
4649 if (!BaseTInfo) {
4650 AnyErrors = true;
4651 break;
4652 }
4653
4654 // Build the initializer.
Sebastian Redla74948d2011-09-24 17:48:25 +00004655 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004656 BaseTInfo, TempInit.get(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004657 New->getParent(),
4658 SourceLocation());
4659 if (NewInit.isInvalid()) {
4660 AnyErrors = true;
4661 break;
4662 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004663
Douglas Gregor44e7df62011-01-04 00:32:56 +00004664 NewInits.push_back(NewInit.get());
Douglas Gregor44e7df62011-01-04 00:32:56 +00004665 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004666
Douglas Gregor44e7df62011-01-04 00:32:56 +00004667 continue;
4668 }
4669
Douglas Gregorb30f22b2010-03-02 07:38:39 +00004670 // Instantiate the initializer.
Sebastian Redla9351792012-02-11 23:51:47 +00004671 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4672 /*CXXDirectInit=*/true);
4673 if (TempInit.isInvalid()) {
Douglas Gregorb30f22b2010-03-02 07:38:39 +00004674 AnyErrors = true;
4675 continue;
Anders Carlsson70553942009-08-29 05:16:22 +00004676 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004677
Anders Carlsson70553942009-08-29 05:16:22 +00004678 MemInitResult NewInit;
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004679 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
4680 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
4681 TemplateArgs,
4682 Init->getSourceLocation(),
4683 New->getDeclName());
4684 if (!TInfo) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004685 AnyErrors = true;
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00004686 New->setInvalidDecl();
4687 continue;
4688 }
Sebastian Redla74948d2011-09-24 17:48:25 +00004689
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004690 if (Init->isBaseInitializer())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004691 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004692 New->getParent(), EllipsisLoc);
4693 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004694 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004695 cast<CXXRecordDecl>(CurContext->getParent()));
Anders Carlsson70553942009-08-29 05:16:22 +00004696 } else if (Init->isMemberInitializer()) {
Douglas Gregor55e6b312011-03-04 19:46:35 +00004697 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
Francois Pichetd583da02010-12-04 09:14:42 +00004698 Init->getMemberLocation(),
4699 Init->getMember(),
4700 TemplateArgs));
Douglas Gregor55e6b312011-03-04 19:46:35 +00004701 if (!Member) {
4702 AnyErrors = true;
4703 New->setInvalidDecl();
4704 continue;
4705 }
Mike Stump11289f42009-09-09 15:08:12 +00004706
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004707 NewInit = BuildMemberInitializer(Member, TempInit.get(),
Sebastian Redla74948d2011-09-24 17:48:25 +00004708 Init->getSourceLocation());
Francois Pichetd583da02010-12-04 09:14:42 +00004709 } else if (Init->isIndirectMemberInitializer()) {
4710 IndirectFieldDecl *IndirectMember =
Douglas Gregor55e6b312011-03-04 19:46:35 +00004711 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
Francois Pichetd583da02010-12-04 09:14:42 +00004712 Init->getMemberLocation(),
4713 Init->getIndirectMember(), TemplateArgs));
4714
Douglas Gregor55e6b312011-03-04 19:46:35 +00004715 if (!IndirectMember) {
4716 AnyErrors = true;
4717 New->setInvalidDecl();
Sebastian Redla74948d2011-09-24 17:48:25 +00004718 continue;
Douglas Gregor55e6b312011-03-04 19:46:35 +00004719 }
Sebastian Redla74948d2011-09-24 17:48:25 +00004720
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004721 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
Sebastian Redla74948d2011-09-24 17:48:25 +00004722 Init->getSourceLocation());
Anders Carlsson70553942009-08-29 05:16:22 +00004723 }
4724
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004725 if (NewInit.isInvalid()) {
4726 AnyErrors = true;
Anders Carlsson70553942009-08-29 05:16:22 +00004727 New->setInvalidDecl();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004728 } else {
Richard Trieu9becef62011-09-09 03:18:59 +00004729 NewInits.push_back(NewInit.get());
Anders Carlsson70553942009-08-29 05:16:22 +00004730 }
4731 }
Mike Stump11289f42009-09-09 15:08:12 +00004732
Anders Carlsson70553942009-08-29 05:16:22 +00004733 // Assign all the initializers to the new constructor.
John McCall48871652010-08-21 09:40:31 +00004734 ActOnMemInitializers(New,
Anders Carlsson70553942009-08-29 05:16:22 +00004735 /*FIXME: ColonLoc */
4736 SourceLocation(),
David Blaikie3fc2f912013-01-17 05:26:25 +00004737 NewInits,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004738 AnyErrors);
Anders Carlsson70553942009-08-29 05:16:22 +00004739}
4740
John McCall59660882009-08-29 08:11:13 +00004741// TODO: this could be templated if the various decl types used the
4742// same method name.
4743static bool isInstantiationOf(ClassTemplateDecl *Pattern,
4744 ClassTemplateDecl *Instance) {
4745 Pattern = Pattern->getCanonicalDecl();
4746
4747 do {
4748 Instance = Instance->getCanonicalDecl();
4749 if (Pattern == Instance) return true;
4750 Instance = Instance->getInstantiatedFromMemberTemplate();
4751 } while (Instance);
4752
4753 return false;
4754}
4755
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004756static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
4757 FunctionTemplateDecl *Instance) {
4758 Pattern = Pattern->getCanonicalDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004759
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004760 do {
4761 Instance = Instance->getCanonicalDecl();
4762 if (Pattern == Instance) return true;
4763 Instance = Instance->getInstantiatedFromMemberTemplate();
4764 } while (Instance);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004765
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004766 return false;
4767}
4768
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004769static bool
Douglas Gregor21610382009-10-29 00:04:11 +00004770isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
4771 ClassTemplatePartialSpecializationDecl *Instance) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004772 Pattern
Douglas Gregor21610382009-10-29 00:04:11 +00004773 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
4774 do {
4775 Instance = cast<ClassTemplatePartialSpecializationDecl>(
4776 Instance->getCanonicalDecl());
4777 if (Pattern == Instance)
4778 return true;
4779 Instance = Instance->getInstantiatedFromMember();
4780 } while (Instance);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004781
Douglas Gregor21610382009-10-29 00:04:11 +00004782 return false;
4783}
4784
John McCall59660882009-08-29 08:11:13 +00004785static bool isInstantiationOf(CXXRecordDecl *Pattern,
4786 CXXRecordDecl *Instance) {
4787 Pattern = Pattern->getCanonicalDecl();
4788
4789 do {
4790 Instance = Instance->getCanonicalDecl();
4791 if (Pattern == Instance) return true;
4792 Instance = Instance->getInstantiatedFromMemberClass();
4793 } while (Instance);
4794
4795 return false;
4796}
4797
4798static bool isInstantiationOf(FunctionDecl *Pattern,
4799 FunctionDecl *Instance) {
4800 Pattern = Pattern->getCanonicalDecl();
4801
4802 do {
4803 Instance = Instance->getCanonicalDecl();
4804 if (Pattern == Instance) return true;
4805 Instance = Instance->getInstantiatedFromMemberFunction();
4806 } while (Instance);
4807
4808 return false;
4809}
4810
4811static bool isInstantiationOf(EnumDecl *Pattern,
4812 EnumDecl *Instance) {
4813 Pattern = Pattern->getCanonicalDecl();
4814
4815 do {
4816 Instance = Instance->getCanonicalDecl();
4817 if (Pattern == Instance) return true;
4818 Instance = Instance->getInstantiatedFromMemberEnum();
4819 } while (Instance);
4820
4821 return false;
4822}
4823
John McCallb96ec562009-12-04 22:46:56 +00004824static bool isInstantiationOf(UsingShadowDecl *Pattern,
4825 UsingShadowDecl *Instance,
4826 ASTContext &C) {
Richard Smith32952e12014-10-14 02:00:47 +00004827 return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
4828 Pattern);
John McCallb96ec562009-12-04 22:46:56 +00004829}
4830
Richard Smith151c4562016-12-20 21:35:28 +00004831static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance,
John McCallb96ec562009-12-04 22:46:56 +00004832 ASTContext &C) {
Richard Smith32952e12014-10-14 02:00:47 +00004833 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
John McCallb96ec562009-12-04 22:46:56 +00004834}
4835
Richard Smith151c4562016-12-20 21:35:28 +00004836template<typename T>
4837static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other,
4838 ASTContext &Ctx) {
4839 // An unresolved using declaration can instantiate to an unresolved using
4840 // declaration, or to a using declaration or a using declaration pack.
4841 //
4842 // Multiple declarations can claim to be instantiated from an unresolved
4843 // using declaration if it's a pack expansion. We want the UsingPackDecl
4844 // in that case, not the individual UsingDecls within the pack.
4845 bool OtherIsPackExpansion;
4846 NamedDecl *OtherFrom;
4847 if (auto *OtherUUD = dyn_cast<T>(Other)) {
4848 OtherIsPackExpansion = OtherUUD->isPackExpansion();
4849 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD);
4850 } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) {
4851 OtherIsPackExpansion = true;
4852 OtherFrom = OtherUPD->getInstantiatedFromUsingDecl();
4853 } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) {
4854 OtherIsPackExpansion = false;
4855 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD);
4856 } else {
4857 return false;
4858 }
4859 return Pattern->isPackExpansion() == OtherIsPackExpansion &&
4860 declaresSameEntity(OtherFrom, Pattern);
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004861}
4862
John McCall59660882009-08-29 08:11:13 +00004863static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
4864 VarDecl *Instance) {
4865 assert(Instance->isStaticDataMember());
4866
4867 Pattern = Pattern->getCanonicalDecl();
4868
4869 do {
4870 Instance = Instance->getCanonicalDecl();
4871 if (Pattern == Instance) return true;
4872 Instance = Instance->getInstantiatedFromStaticDataMember();
4873 } while (Instance);
4874
4875 return false;
4876}
4877
John McCallb96ec562009-12-04 22:46:56 +00004878// Other is the prospective instantiation
4879// D is the prospective pattern
Douglas Gregor51783312009-05-27 05:35:12 +00004880static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Richard Smith151c4562016-12-20 21:35:28 +00004881 if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D))
4882 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
John McCalle61f2ba2009-11-18 02:36:19 +00004883
Richard Smith151c4562016-12-20 21:35:28 +00004884 if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D))
4885 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
Douglas Gregor51783312009-05-27 05:35:12 +00004886
Richard Smith151c4562016-12-20 21:35:28 +00004887 if (D->getKind() != Other->getKind())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004888 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004889
Richard Smithd8a9e372016-12-18 21:39:37 +00004890 if (auto *Record = dyn_cast<CXXRecordDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00004891 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump11289f42009-09-09 15:08:12 +00004892
Richard Smithd8a9e372016-12-18 21:39:37 +00004893 if (auto *Function = dyn_cast<FunctionDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00004894 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor51783312009-05-27 05:35:12 +00004895
Richard Smithd8a9e372016-12-18 21:39:37 +00004896 if (auto *Enum = dyn_cast<EnumDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00004897 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor51783312009-05-27 05:35:12 +00004898
Richard Smithd8a9e372016-12-18 21:39:37 +00004899 if (auto *Var = dyn_cast<VarDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00004900 if (Var->isStaticDataMember())
4901 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
4902
Richard Smithd8a9e372016-12-18 21:39:37 +00004903 if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00004904 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregorf3db0032009-08-28 22:03:51 +00004905
Richard Smithd8a9e372016-12-18 21:39:37 +00004906 if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other))
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004907 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
4908
Richard Smithd8a9e372016-12-18 21:39:37 +00004909 if (auto *PartialSpec =
4910 dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
Douglas Gregor21610382009-10-29 00:04:11 +00004911 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
4912 PartialSpec);
4913
Richard Smithd8a9e372016-12-18 21:39:37 +00004914 if (auto *Field = dyn_cast<FieldDecl>(Other)) {
Anders Carlsson5da84842009-09-01 04:26:58 +00004915 if (!Field->getDeclName()) {
4916 // This is an unnamed field.
Richard Smith32952e12014-10-14 02:00:47 +00004917 return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field),
4918 cast<FieldDecl>(D));
Anders Carlsson5da84842009-09-01 04:26:58 +00004919 }
4920 }
Mike Stump11289f42009-09-09 15:08:12 +00004921
Richard Smithd8a9e372016-12-18 21:39:37 +00004922 if (auto *Using = dyn_cast<UsingDecl>(Other))
John McCallb96ec562009-12-04 22:46:56 +00004923 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
4924
Richard Smithd8a9e372016-12-18 21:39:37 +00004925 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other))
John McCallb96ec562009-12-04 22:46:56 +00004926 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
4927
Richard Smithd8a9e372016-12-18 21:39:37 +00004928 return D->getDeclName() &&
4929 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
Douglas Gregor51783312009-05-27 05:35:12 +00004930}
4931
4932template<typename ForwardIterator>
Mike Stump11289f42009-09-09 15:08:12 +00004933static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor51783312009-05-27 05:35:12 +00004934 NamedDecl *D,
4935 ForwardIterator first,
4936 ForwardIterator last) {
4937 for (; first != last; ++first)
4938 if (isInstantiationOf(Ctx, D, *first))
4939 return cast<NamedDecl>(*first);
4940
Craig Topperc3ec1492014-05-26 06:22:03 +00004941 return nullptr;
Douglas Gregor51783312009-05-27 05:35:12 +00004942}
4943
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004944/// Finds the instantiation of the given declaration context
John McCallaa74a0c2009-08-28 07:59:38 +00004945/// within the current instantiation.
4946///
4947/// \returns NULL if there was an error
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004948DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregor64621e62009-09-16 18:34:49 +00004949 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCallaa74a0c2009-08-28 07:59:38 +00004950 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Richard Smith4f440e32017-06-08 01:08:50 +00004951 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true);
John McCallaa74a0c2009-08-28 07:59:38 +00004952 return cast_or_null<DeclContext>(ID);
4953 } else return DC;
4954}
4955
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004956/// Find the instantiation of the given declaration within the
Douglas Gregorcd3a0972009-05-27 17:54:46 +00004957/// current instantiation.
Douglas Gregor51783312009-05-27 05:35:12 +00004958///
4959/// This routine is intended to be used when \p D is a declaration
4960/// referenced from within a template, that needs to mapped into the
4961/// corresponding declaration within an instantiation. For example,
4962/// given:
4963///
4964/// \code
4965/// template<typename T>
4966/// struct X {
4967/// enum Kind {
4968/// KnownValue = sizeof(T)
4969/// };
4970///
4971/// bool getKind() const { return KnownValue; }
4972/// };
4973///
4974/// template struct X<int>;
4975/// \endcode
4976///
Serge Pavloved5fe902013-07-10 04:59:14 +00004977/// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
4978/// \p EnumConstantDecl for \p KnownValue (which refers to
4979/// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
4980/// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
4981/// this mapping from within the instantiation of <tt>X<int></tt>.
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004982NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Richard Smith4f440e32017-06-08 01:08:50 +00004983 const MultiLevelTemplateArgumentList &TemplateArgs,
4984 bool FindingInstantiatedContext) {
Douglas Gregor51783312009-05-27 05:35:12 +00004985 DeclContext *ParentDC = D->getDeclContext();
Fangrui Song6907ce22018-07-30 19:24:48 +00004986 // FIXME: Parmeters of pointer to functions (y below) that are themselves
Faisal Vali2cba1332013-10-23 06:44:28 +00004987 // parameters (p below) can have their ParentDC set to the translation-unit
Fangrui Song6907ce22018-07-30 19:24:48 +00004988 // - thus we can not consistently check if the ParentDC of such a parameter
Faisal Vali2cba1332013-10-23 06:44:28 +00004989 // is Dependent or/and a FunctionOrMethod.
Fangrui Song6907ce22018-07-30 19:24:48 +00004990 // For e.g. this code, during Template argument deduction tries to
Faisal Vali2cba1332013-10-23 06:44:28 +00004991 // find an instantiated decl for (T y) when the ParentDC for y is
Fangrui Song6907ce22018-07-30 19:24:48 +00004992 // the translation unit.
4993 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
Aaron Ballman36a53502014-01-16 13:03:14 +00004994 // float baz(float(*)()) { return 0.0; }
Faisal Vali2cba1332013-10-23 06:44:28 +00004995 // Foo(baz);
4996 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
4997 // it gets here, always has a FunctionOrMethod as its ParentDC??
4998 // For now:
4999 // - as long as we have a ParmVarDecl whose parent is non-dependent and
5000 // whose type is not instantiation dependent, do nothing to the decl
5001 // - otherwise find its instantiated decl.
5002 if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() &&
5003 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
5004 return D;
Rafael Espindola09b00e32013-10-23 04:12:23 +00005005 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregorb93971082010-02-05 19:54:12 +00005006 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Alexey Bataeve6aa4692018-09-13 16:54:05 +00005007 ((ParentDC->isFunctionOrMethod() ||
5008 isa<OMPDeclareReductionDecl>(ParentDC)) &&
5009 ParentDC->isDependentContext()) ||
Douglas Gregora86bc002012-02-16 21:36:18 +00005010 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
Douglas Gregorf98d9b62009-05-27 17:07:49 +00005011 // D is a local of some kind. Look into the map of local
5012 // declarations to their instantiations.
Alexey Samsonov2c0aac22014-09-03 18:45:45 +00005013 if (CurrentInstantiationScope) {
5014 if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
5015 if (Decl *FD = Found->dyn_cast<Decl *>())
5016 return cast<NamedDecl>(FD);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005017
Alexey Samsonov2c0aac22014-09-03 18:45:45 +00005018 int PackIdx = ArgumentPackSubstitutionIndex;
5019 assert(PackIdx != -1 &&
5020 "found declaration pack but not pack expanding");
5021 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
5022 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
5023 }
Chris Lattnercab02a62011-02-17 20:34:02 +00005024 }
5025
Serge Pavlov7cd8f602013-07-15 06:14:07 +00005026 // If we're performing a partial substitution during template argument
5027 // deduction, we may not have values for template parameters yet. They
5028 // just map to themselves.
5029 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
5030 isa<TemplateTemplateParmDecl>(D))
5031 return D;
5032
Serge Pavlov074a5182013-08-10 12:00:21 +00005033 if (D->isInvalidDecl())
Craig Topperc3ec1492014-05-26 06:22:03 +00005034 return nullptr;
Serge Pavlov074a5182013-08-10 12:00:21 +00005035
Serge Pavlove7ad8312015-05-15 10:10:28 +00005036 // Normally this function only searches for already instantiated declaration
5037 // however we have to make an exclusion for local types used before
5038 // definition as in the code:
5039 //
5040 // template<typename T> void f1() {
5041 // void g1(struct x1);
5042 // struct x1 {};
5043 // }
5044 //
5045 // In this case instantiation of the type of 'g1' requires definition of
5046 // 'x1', which is defined later. Error recovery may produce an enum used
5047 // before definition. In these cases we need to instantiate relevant
5048 // declarations here.
5049 bool NeedInstantiate = false;
5050 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5051 NeedInstantiate = RD->isLocalClass();
5052 else
5053 NeedInstantiate = isa<EnumDecl>(D);
5054 if (NeedInstantiate) {
Serge Pavlov4c511742015-05-04 16:44:39 +00005055 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
5056 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
5057 return cast<TypeDecl>(Inst);
5058 }
5059
Chris Lattnercab02a62011-02-17 20:34:02 +00005060 // If we didn't find the decl, then we must have a label decl that hasn't
5061 // been found yet. Lazily instantiate it and return it now.
5062 assert(isa<LabelDecl>(D));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005063
Chris Lattnercab02a62011-02-17 20:34:02 +00005064 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
5065 assert(Inst && "Failed to instantiate label??");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005066
Chris Lattnercab02a62011-02-17 20:34:02 +00005067 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
5068 return cast<LabelDecl>(Inst);
Douglas Gregorf98d9b62009-05-27 17:07:49 +00005069 }
Douglas Gregor51783312009-05-27 05:35:12 +00005070
Larisse Voufo39a1e502013-08-06 01:03:05 +00005071 // For variable template specializations, update those that are still
5072 // type-dependent.
5073 if (VarTemplateSpecializationDecl *VarSpec =
5074 dyn_cast<VarTemplateSpecializationDecl>(D)) {
5075 bool InstantiationDependent = false;
5076 const TemplateArgumentListInfo &VarTemplateArgs =
5077 VarSpec->getTemplateArgsInfo();
5078 if (TemplateSpecializationType::anyDependentTemplateArguments(
5079 VarTemplateArgs, InstantiationDependent))
5080 D = cast<NamedDecl>(
5081 SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs));
5082 return D;
5083 }
5084
Douglas Gregor64621e62009-09-16 18:34:49 +00005085 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
5086 if (!Record->isDependentContext())
5087 return D;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005088
Douglas Gregor4109afa2011-11-07 17:43:18 +00005089 // Determine whether this record is the "templated" declaration describing
5090 // a class template or class template partial specialization.
Douglas Gregor64621e62009-09-16 18:34:49 +00005091 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
Douglas Gregor4109afa2011-11-07 17:43:18 +00005092 if (ClassTemplate)
5093 ClassTemplate = ClassTemplate->getCanonicalDecl();
5094 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5095 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
5096 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
Larisse Voufo39a1e502013-08-06 01:03:05 +00005097
Douglas Gregor4109afa2011-11-07 17:43:18 +00005098 // Walk the current context to find either the record or an instantiation of
5099 // it.
5100 DeclContext *DC = CurContext;
5101 while (!DC->isFileContext()) {
5102 // If we're performing substitution while we're inside the template
5103 // definition, we'll find our own context. We're done.
5104 if (DC->Equals(Record))
5105 return Record;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005106
Douglas Gregor4109afa2011-11-07 17:43:18 +00005107 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
5108 // Check whether we're in the process of instantiating a class template
5109 // specialization of the template we're mapping.
5110 if (ClassTemplateSpecializationDecl *InstSpec
5111 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
5112 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
5113 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
5114 return InstRecord;
5115 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00005116
Douglas Gregor4109afa2011-11-07 17:43:18 +00005117 // Check whether we're in the process of instantiating a member class.
5118 if (isInstantiationOf(Record, InstRecord))
5119 return InstRecord;
Douglas Gregor64621e62009-09-16 18:34:49 +00005120 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00005121
Douglas Gregor4109afa2011-11-07 17:43:18 +00005122 // Move to the outer template scope.
5123 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
5124 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
5125 DC = FD->getLexicalDeclContext();
5126 continue;
5127 }
Richard Smith32918772017-02-14 00:25:28 +00005128 // An implicit deduction guide acts as if it's within the class template
5129 // specialization described by its name and first N template params.
Richard Smithbc491202017-02-17 20:05:37 +00005130 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD);
5131 if (Guide && Guide->isImplicit()) {
5132 TemplateDecl *TD = Guide->getDeducedTemplate();
Richard Smith0cd9c042017-02-21 08:42:39 +00005133 // Convert the arguments to an "as-written" list.
Richard Smith32918772017-02-14 00:25:28 +00005134 TemplateArgumentListInfo Args(Loc, Loc);
Richard Smith0cd9c042017-02-21 08:42:39 +00005135 for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front(
5136 TD->getTemplateParameters()->size())) {
5137 ArrayRef<TemplateArgument> Unpacked(Arg);
5138 if (Arg.getKind() == TemplateArgument::Pack)
5139 Unpacked = Arg.pack_elements();
5140 for (TemplateArgument UnpackedArg : Unpacked)
5141 Args.addArgument(
5142 getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc));
5143 }
Richard Smith32918772017-02-14 00:25:28 +00005144 QualType T = CheckTemplateIdType(TemplateName(TD), Loc, Args);
5145 if (T.isNull())
5146 return nullptr;
Richard Smithe6d4b772017-06-07 02:42:27 +00005147 auto *SubstRecord = T->getAsCXXRecordDecl();
5148 assert(SubstRecord && "class template id not a class type?");
5149 // Check that this template-id names the primary template and not a
5150 // partial or explicit specialization. (In the latter cases, it's
5151 // meaningless to attempt to find an instantiation of D within the
5152 // specialization.)
5153 // FIXME: The standard doesn't say what should happen here.
Richard Smith4f440e32017-06-08 01:08:50 +00005154 if (FindingInstantiatedContext &&
5155 usesPartialOrExplicitSpecialization(
5156 Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) {
Richard Smithe6d4b772017-06-07 02:42:27 +00005157 Diag(Loc, diag::err_specialization_not_primary_template)
5158 << T << (SubstRecord->getTemplateSpecializationKind() ==
5159 TSK_ExplicitSpecialization);
5160 return nullptr;
5161 }
5162 DC = SubstRecord;
Richard Smith32918772017-02-14 00:25:28 +00005163 continue;
5164 }
John McCall59660882009-08-29 08:11:13 +00005165 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00005166
Douglas Gregor4109afa2011-11-07 17:43:18 +00005167 DC = DC->getParent();
John McCall59660882009-08-29 08:11:13 +00005168 }
Douglas Gregord225fa02010-02-05 22:40:03 +00005169
Douglas Gregor64621e62009-09-16 18:34:49 +00005170 // Fall through to deal with other dependent record types (e.g.,
5171 // anonymous unions in class templates).
5172 }
John McCall59660882009-08-29 08:11:13 +00005173
Douglas Gregor64621e62009-09-16 18:34:49 +00005174 if (!ParentDC->isDependentContext())
5175 return D;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005176
Douglas Gregora04f2ca2010-03-01 15:56:25 +00005177 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00005178 if (!ParentDC)
Craig Topperc3ec1492014-05-26 06:22:03 +00005179 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005180
Douglas Gregor51783312009-05-27 05:35:12 +00005181 if (ParentDC != D->getDeclContext()) {
5182 // We performed some kind of instantiation in the parent context,
5183 // so now we need to look into the instantiated parent context to
5184 // find the instantiation of the declaration D.
Douglas Gregora04f2ca2010-03-01 15:56:25 +00005185
John McCalle78aac42010-03-10 03:28:59 +00005186 // If our context used to be dependent, we may need to instantiate
5187 // it before performing lookup into that context.
Douglas Gregor528ad932011-03-06 20:12:45 +00005188 bool IsBeingInstantiated = false;
John McCalle78aac42010-03-10 03:28:59 +00005189 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00005190 if (!Spec->isDependentContext()) {
5191 QualType T = Context.getTypeDeclType(Spec);
John McCalle78aac42010-03-10 03:28:59 +00005192 const RecordType *Tag = T->getAs<RecordType>();
5193 assert(Tag && "type of non-dependent record is not a RecordType");
Douglas Gregor528ad932011-03-06 20:12:45 +00005194 if (Tag->isBeingDefined())
5195 IsBeingInstantiated = true;
John McCalle78aac42010-03-10 03:28:59 +00005196 if (!Tag->isBeingDefined() &&
5197 RequireCompleteType(Loc, T, diag::err_incomplete_type))
Craig Topperc3ec1492014-05-26 06:22:03 +00005198 return nullptr;
Douglas Gregor25edf432010-11-05 23:22:45 +00005199
5200 ParentDC = Tag->getDecl();
Douglas Gregora04f2ca2010-03-01 15:56:25 +00005201 }
5202 }
5203
Craig Topperc3ec1492014-05-26 06:22:03 +00005204 NamedDecl *Result = nullptr;
Richard Smith151c4562016-12-20 21:35:28 +00005205 // FIXME: If the name is a dependent name, this lookup won't necessarily
5206 // find it. Does that ever matter?
Akira Hatanaka59e3b432017-01-31 19:53:32 +00005207 if (auto Name = D->getDeclName()) {
5208 DeclarationNameInfo NameInfo(Name, D->getLocation());
5209 Name = SubstDeclarationNameInfo(NameInfo, TemplateArgs).getName();
5210 if (!Name)
5211 return nullptr;
5212 DeclContext::lookup_result Found = ParentDC->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00005213 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
Douglas Gregor51783312009-05-27 05:35:12 +00005214 } else {
5215 // Since we don't have a name for the entity we're looking for,
5216 // our only option is to walk through all of the declarations to
5217 // find that name. This will occur in a few cases:
5218 //
5219 // - anonymous struct/union within a template
5220 // - unnamed class/struct/union/enum within a template
5221 //
5222 // FIXME: Find a better way to find these instantiations!
Mike Stump11289f42009-09-09 15:08:12 +00005223 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005224 ParentDC->decls_begin(),
5225 ParentDC->decls_end());
Douglas Gregor51783312009-05-27 05:35:12 +00005226 }
Mike Stump11289f42009-09-09 15:08:12 +00005227
Douglas Gregor528ad932011-03-06 20:12:45 +00005228 if (!Result) {
5229 if (isa<UsingShadowDecl>(D)) {
5230 // UsingShadowDecls can instantiate to nothing because of using hiding.
5231 } else if (Diags.hasErrorOccurred()) {
5232 // We've already complained about something, so most likely this
5233 // declaration failed to instantiate. There's no point in complaining
5234 // further, since this is normal in invalid code.
5235 } else if (IsBeingInstantiated) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005236 // The class in which this member exists is currently being
Douglas Gregor528ad932011-03-06 20:12:45 +00005237 // instantiated, and we haven't gotten around to instantiating this
5238 // member yet. This can happen when the code uses forward declarations
5239 // of member classes, and introduces ordering dependencies via
5240 // template instantiation.
5241 Diag(Loc, diag::err_member_not_yet_instantiated)
5242 << D->getDeclName()
5243 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
5244 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
Richard Smith169f2192012-03-26 20:28:16 +00005245 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
5246 // This enumeration constant was found when the template was defined,
5247 // but can't be found in the instantiation. This can happen if an
5248 // unscoped enumeration member is explicitly specialized.
5249 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
5250 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
5251 TemplateArgs));
5252 assert(Spec->getTemplateSpecializationKind() ==
5253 TSK_ExplicitSpecialization);
5254 Diag(Loc, diag::err_enumerator_does_not_exist)
5255 << D->getDeclName()
5256 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
5257 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
5258 << Context.getTypeDeclType(Spec);
Douglas Gregor528ad932011-03-06 20:12:45 +00005259 } else {
5260 // We should have found something, but didn't.
5261 llvm_unreachable("Unable to find instantiation of declaration!");
5262 }
5263 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005264
Douglas Gregor51783312009-05-27 05:35:12 +00005265 D = Result;
5266 }
5267
Douglas Gregor51783312009-05-27 05:35:12 +00005268 return D;
5269}
Douglas Gregor77b50e12009-06-22 23:06:13 +00005270
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005271/// Performs template instantiation for all implicit template
Douglas Gregor77b50e12009-06-22 23:06:13 +00005272/// instantiations we have seen until this point.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00005273void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregor7f792cf2010-01-16 22:29:39 +00005274 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth54080172010-08-25 08:44:16 +00005275 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor7f792cf2010-01-16 22:29:39 +00005276 PendingImplicitInstantiation Inst;
5277
5278 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth54080172010-08-25 08:44:16 +00005279 Inst = PendingInstantiations.front();
5280 PendingInstantiations.pop_front();
Douglas Gregor7f792cf2010-01-16 22:29:39 +00005281 } else {
5282 Inst = PendingLocalImplicitInstantiations.front();
5283 PendingLocalImplicitInstantiations.pop_front();
5284 }
Mike Stump11289f42009-09-09 15:08:12 +00005285
Douglas Gregora6ef8f02009-07-24 20:34:43 +00005286 // Instantiate function definitions
5287 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Chandler Carruthcfe41db2010-08-25 08:27:02 +00005288 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
5289 TSK_ExplicitInstantiationDefinition;
Erich Keane0fb16482018-08-13 18:33:20 +00005290 if (Function->isMultiVersion()) {
5291 getASTContext().forEachMultiversionedFunctionVersion(
5292 Function, [this, Inst, DefinitionRequired](FunctionDecl *CurFD) {
5293 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, CurFD, true,
5294 DefinitionRequired, true);
5295 if (CurFD->isDefined())
5296 CurFD->setInstantiationIsPending(false);
5297 });
5298 } else {
5299 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, Function, true,
5300 DefinitionRequired, true);
5301 if (Function->isDefined())
5302 Function->setInstantiationIsPending(false);
5303 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00005304 continue;
5305 }
Mike Stump11289f42009-09-09 15:08:12 +00005306
Larisse Voufo39a1e502013-08-06 01:03:05 +00005307 // Instantiate variable definitions
Douglas Gregora6ef8f02009-07-24 20:34:43 +00005308 VarDecl *Var = cast<VarDecl>(Inst.first);
Larisse Voufo39a1e502013-08-06 01:03:05 +00005309
5310 assert((Var->isStaticDataMember() ||
5311 isa<VarTemplateSpecializationDecl>(Var)) &&
5312 "Not a static data member, nor a variable template"
5313 " specialization?");
Anders Carlsson62215c42009-09-01 05:12:24 +00005314
Chandler Carruth6b4756a2010-02-13 10:17:50 +00005315 // Don't try to instantiate declarations if the most recent redeclaration
5316 // is invalid.
Douglas Gregorec9fd132012-01-14 16:38:05 +00005317 if (Var->getMostRecentDecl()->isInvalidDecl())
Chandler Carruth6b4756a2010-02-13 10:17:50 +00005318 continue;
5319
5320 // Check if the most recent declaration has changed the specialization kind
5321 // and removed the need for implicit instantiation.
Douglas Gregorec9fd132012-01-14 16:38:05 +00005322 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
Chandler Carruth6b4756a2010-02-13 10:17:50 +00005323 case TSK_Undeclared:
David Blaikie83d382b2011-09-23 05:06:16 +00005324 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
Chandler Carruth6b4756a2010-02-13 10:17:50 +00005325 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth6b4756a2010-02-13 10:17:50 +00005326 case TSK_ExplicitSpecialization:
Chandler Carruthcfe41db2010-08-25 08:27:02 +00005327 continue; // No longer need to instantiate this type.
5328 case TSK_ExplicitInstantiationDefinition:
5329 // We only need an instantiation if the pending instantiation *is* the
5330 // explicit instantiation.
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00005331 if (Var != Var->getMostRecentDecl())
5332 continue;
5333 break;
Chandler Carruth6b4756a2010-02-13 10:17:50 +00005334 case TSK_ImplicitInstantiation:
5335 break;
5336 }
5337
Jordan Rose1e879d82018-03-23 00:07:18 +00005338 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00005339 "instantiating variable definition");
Chandler Carruthcfe41db2010-08-25 08:27:02 +00005340 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
5341 TSK_ExplicitInstantiationDefinition;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005342
5343 // Instantiate static data member definitions or variable template
5344 // specializations.
5345 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00005346 DefinitionRequired, true);
Douglas Gregor77b50e12009-06-22 23:06:13 +00005347 }
5348}
John McCallc62bb642010-03-24 05:22:00 +00005349
5350void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
5351 const MultiLevelTemplateArgumentList &TemplateArgs) {
Aaron Ballmanb105e492014-03-07 14:09:15 +00005352 for (auto DD : Pattern->ddiags()) {
John McCallc62bb642010-03-24 05:22:00 +00005353 switch (DD->getKind()) {
5354 case DependentDiagnostic::Access:
5355 HandleDependentAccessCheck(*DD, TemplateArgs);
5356 break;
5357 }
5358 }
5359}