Bug Summary

File:build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
Warning:line 3218, 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 -clear-ast-before-backend -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 -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm -resource-dir /usr/lib/llvm-15/lib/clang/15.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/lib/Sema -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U 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-15/lib/clang/15.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 -fmacro-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -O3 -Wno-unused-command-line-argument -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-15~++20220420111733+e13d2efed663/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -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-2022-04-20-140412-16051-1 -x c++ /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp

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