Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaTemplateInstantiateDecl.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-12-07-102640-14763-1 -x c++ /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp

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

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h

1//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
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//
9// This file defines the Sema class, which performs semantic analysis and
10// builds ASTs.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SEMA_SEMA_H
15#define LLVM_CLANG_SEMA_SEMA_H
16
17#include "clang/AST/Attr.h"
18#include "clang/AST/Availability.h"
19#include "clang/AST/ComparisonCategories.h"
20#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/DeclarationName.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/ExprObjC.h"
25#include "clang/AST/ExternalASTSource.h"
26#include "clang/AST/LocInfoType.h"
27#include "clang/AST/MangleNumberingContext.h"
28#include "clang/AST/NSAPI.h"
29#include "clang/AST/PrettyPrinter.h"
30#include "clang/AST/StmtCXX.h"
31#include "clang/AST/TypeLoc.h"
32#include "clang/AST/TypeOrdering.h"
33#include "clang/Basic/ExpressionTraits.h"
34#include "clang/Basic/Module.h"
35#include "clang/Basic/OpenMPKinds.h"
36#include "clang/Basic/PragmaKinds.h"
37#include "clang/Basic/Specifiers.h"
38#include "clang/Basic/TemplateKinds.h"
39#include "clang/Basic/TypeTraits.h"
40#include "clang/Sema/AnalysisBasedWarnings.h"
41#include "clang/Sema/CleanupInfo.h"
42#include "clang/Sema/DeclSpec.h"
43#include "clang/Sema/ExternalSemaSource.h"
44#include "clang/Sema/IdentifierResolver.h"
45#include "clang/Sema/ObjCMethodList.h"
46#include "clang/Sema/Ownership.h"
47#include "clang/Sema/Scope.h"
48#include "clang/Sema/TypoCorrection.h"
49#include "clang/Sema/Weak.h"
50#include "llvm/ADT/ArrayRef.h"
51#include "llvm/ADT/Optional.h"
52#include "llvm/ADT/SetVector.h"
53#include "llvm/ADT/SmallBitVector.h"
54#include "llvm/ADT/SmallPtrSet.h"
55#include "llvm/ADT/SmallVector.h"
56#include "llvm/ADT/TinyPtrVector.h"
57#include <deque>
58#include <memory>
59#include <string>
60#include <tuple>
61#include <vector>
62
63namespace llvm {
64 class APSInt;
65 template <typename ValueT> struct DenseMapInfo;
66 template <typename ValueT, typename ValueInfoT> class DenseSet;
67 class SmallBitVector;
68 struct InlineAsmIdentifierInfo;
69}
70
71namespace clang {
72 class ADLResult;
73 class ASTConsumer;
74 class ASTContext;
75 class ASTMutationListener;
76 class ASTReader;
77 class ASTWriter;
78 class ArrayType;
79 class ParsedAttr;
80 class BindingDecl;
81 class BlockDecl;
82 class CapturedDecl;
83 class CXXBasePath;
84 class CXXBasePaths;
85 class CXXBindTemporaryExpr;
86 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
87 class CXXConstructorDecl;
88 class CXXConversionDecl;
89 class CXXDeleteExpr;
90 class CXXDestructorDecl;
91 class CXXFieldCollector;
92 class CXXMemberCallExpr;
93 class CXXMethodDecl;
94 class CXXScopeSpec;
95 class CXXTemporary;
96 class CXXTryStmt;
97 class CallExpr;
98 class ClassTemplateDecl;
99 class ClassTemplatePartialSpecializationDecl;
100