Bug Summary

File:clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
Warning:line 3185, column 46
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaTemplateInstantiateDecl.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/Sema -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/include -D NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-09-04-040900-46481-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp

/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp

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