Bug Summary

File:clang/lib/Sema/SemaTemplate.cpp
Warning:line 1376, column 5
Value stored to 'RD' is never read

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaTemplate.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.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-12~++20200927111121+5811d723998/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include -I /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/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-12/lib/clang/12.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-12~++20200927111121+5811d723998/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-09-28-092409-31635-1 -x c++ /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp
1//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
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 semantic analysis for C++ templates.
9//===----------------------------------------------------------------------===//
10
11#include "TreeTransform.h"
12#include "clang/AST/ASTConsumer.h"
13#include "clang/AST/ASTContext.h"
14#include "clang/AST/DeclFriend.h"
15#include "clang/AST/DeclTemplate.h"
16#include "clang/AST/Expr.h"
17#include "clang/AST/ExprCXX.h"
18#include "clang/AST/RecursiveASTVisitor.h"
19#include "clang/AST/TypeVisitor.h"
20#include "clang/Basic/Builtins.h"
21#include "clang/Basic/LangOptions.h"
22#include "clang/Basic/PartialDiagnostic.h"
23#include "clang/Basic/Stack.h"
24#include "clang/Basic/TargetInfo.h"
25#include "clang/Sema/DeclSpec.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/Overload.h"
28#include "clang/Sema/ParsedTemplate.h"
29#include "clang/Sema/Scope.h"
30#include "clang/Sema/SemaInternal.h"
31#include "clang/Sema/Template.h"
32#include "clang/Sema/TemplateDeduction.h"
33#include "llvm/ADT/SmallBitVector.h"
34#include "llvm/ADT/SmallString.h"
35#include "llvm/ADT/StringExtras.h"
36
37#include <iterator>
38using namespace clang;
39using namespace sema;
40
41// Exported for use by Parser.
42SourceRange
43clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
44 unsigned N) {
45 if (!N) return SourceRange();
46 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
47}
48
49unsigned Sema::getTemplateDepth(Scope *S) const {
50 unsigned Depth = 0;
51
52 // Each template parameter scope represents one level of template parameter
53 // depth.
54 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
55 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
56 ++Depth;
57 }
58
59 // Note that there are template parameters with the given depth.
60 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };
61
62 // Look for parameters of an enclosing generic lambda. We don't create a
63 // template parameter scope for these.
64 for (FunctionScopeInfo *FSI : getFunctionScopes()) {
65 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
66 if (!LSI->TemplateParams.empty()) {
67 ParamsAtDepth(LSI->AutoTemplateParameterDepth);
68 break;
69 }
70 if (LSI->GLTemplateParameterList) {
71 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
72 break;
73 }
74 }
75 }
76
77 // Look for parameters of an enclosing terse function template. We don't
78 // create a template parameter scope for these either.
79 for (const InventedTemplateParameterInfo &Info :
80 getInventedParameterInfos()) {
81 if (!Info.TemplateParams.empty()) {
82 ParamsAtDepth(Info.AutoTemplateParameterDepth);
83 break;
84 }
85 }
86
87 return Depth;
88}
89
90/// \brief Determine whether the declaration found is acceptable as the name
91/// of a template and, if so, return that template declaration. Otherwise,
92/// returns null.
93///
94/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
95/// is true. In all other cases it will return a TemplateDecl (or null).
96NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D,
97 bool AllowFunctionTemplates,
98 bool AllowDependent) {
99 D = D->getUnderlyingDecl();
100
101 if (isa<TemplateDecl>(D)) {
102 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
103 return nullptr;
104
105 return D;
106 }
107
108 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
109 // C++ [temp.local]p1:
110 // Like normal (non-template) classes, class templates have an
111 // injected-class-name (Clause 9). The injected-class-name
112 // can be used with or without a template-argument-list. When
113 // it is used without a template-argument-list, it is
114 // equivalent to the injected-class-name followed by the
115 // template-parameters of the class template enclosed in
116 // <>. When it is used with a template-argument-list, it
117 // refers to the specified class template specialization,
118 // which could be the current specialization or another
119 // specialization.
120 if (Record->isInjectedClassName()) {
121 Record = cast<CXXRecordDecl>(Record->getDeclContext());
122 if (Record->getDescribedClassTemplate())
123 return Record->getDescribedClassTemplate();
124
125 if (ClassTemplateSpecializationDecl *Spec
126 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
127 return Spec->getSpecializedTemplate();
128 }
129
130 return nullptr;
131 }
132
133 // 'using Dependent::foo;' can resolve to a template name.
134 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
135 // injected-class-name).
136 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
137 return D;
138
139 return nullptr;
140}
141
142void Sema::FilterAcceptableTemplateNames(LookupResult &R,
143 bool AllowFunctionTemplates,
144 bool AllowDependent) {
145 LookupResult::Filter filter = R.makeFilter();
146 while (filter.hasNext()) {
147 NamedDecl *Orig = filter.next();
148 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
149 filter.erase();
150 }
151 filter.done();
152}
153
154bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
155 bool AllowFunctionTemplates,
156 bool AllowDependent,
157 bool AllowNonTemplateFunctions) {
158 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
159 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
160 return true;
161 if (AllowNonTemplateFunctions &&
162 isa<FunctionDecl>((*I)->getUnderlyingDecl()))
163 return true;
164 }
165
166 return false;
167}
168
169TemplateNameKind Sema::isTemplateName(Scope *S,
170 CXXScopeSpec &SS,
171 bool hasTemplateKeyword,
172 const UnqualifiedId &Name,
173 ParsedType ObjectTypePtr,
174 bool EnteringContext,
175 TemplateTy &TemplateResult,
176 bool &MemberOfUnknownSpecialization,
177 bool Disambiguation) {
178 assert(getLangOpts().CPlusPlus && "No template names in C!")((getLangOpts().CPlusPlus && "No template names in C!"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"No template names in C!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 178, __PRETTY_FUNCTION__))
;
179
180 DeclarationName TName;
181 MemberOfUnknownSpecialization = false;
182
183 switch (Name.getKind()) {
184 case UnqualifiedIdKind::IK_Identifier:
185 TName = DeclarationName(Name.Identifier);
186 break;
187
188 case UnqualifiedIdKind::IK_OperatorFunctionId:
189 TName = Context.DeclarationNames.getCXXOperatorName(
190 Name.OperatorFunctionId.Operator);
191 break;
192
193 case UnqualifiedIdKind::IK_LiteralOperatorId:
194 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
195 break;
196
197 default:
198 return TNK_Non_template;
199 }
200
201 QualType ObjectType = ObjectTypePtr.get();
202
203 AssumedTemplateKind AssumedTemplate;
204 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
205 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
206 MemberOfUnknownSpecialization, SourceLocation(),
207 &AssumedTemplate,
208 /*AllowTypoCorrection=*/!Disambiguation))
209 return TNK_Non_template;
210
211 if (AssumedTemplate != AssumedTemplateKind::None) {
212 TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
213 // Let the parser know whether we found nothing or found functions; if we
214 // found nothing, we want to more carefully check whether this is actually
215 // a function template name versus some other kind of undeclared identifier.
216 return AssumedTemplate == AssumedTemplateKind::FoundNothing
217 ? TNK_Undeclared_template
218 : TNK_Function_template;
219 }
220
221 if (R.empty())
222 return TNK_Non_template;
223
224 NamedDecl *D = nullptr;
225 if (R.isAmbiguous()) {
226 // If we got an ambiguity involving a non-function template, treat this
227 // as a template name, and pick an arbitrary template for error recovery.
228 bool AnyFunctionTemplates = false;
229 for (NamedDecl *FoundD : R) {
230 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
231 if (isa<FunctionTemplateDecl>(FoundTemplate))
232 AnyFunctionTemplates = true;
233 else {
234 D = FoundTemplate;
235 break;
236 }
237 }
238 }
239
240 // If we didn't find any templates at all, this isn't a template name.
241 // Leave the ambiguity for a later lookup to diagnose.
242 if (!D && !AnyFunctionTemplates) {
243 R.suppressDiagnostics();
244 return TNK_Non_template;
245 }
246
247 // If the only templates were function templates, filter out the rest.
248 // We'll diagnose the ambiguity later.
249 if (!D)
250 FilterAcceptableTemplateNames(R);
251 }
252
253 // At this point, we have either picked a single template name declaration D
254 // or we have a non-empty set of results R containing either one template name
255 // declaration or a set of function templates.
256
257 TemplateName Template;
258 TemplateNameKind TemplateKind;
259
260 unsigned ResultCount = R.end() - R.begin();
261 if (!D && ResultCount > 1) {
262 // We assume that we'll preserve the qualifier from a function
263 // template name in other ways.
264 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
265 TemplateKind = TNK_Function_template;
266
267 // We'll do this lookup again later.
268 R.suppressDiagnostics();
269 } else {
270 if (!D) {
271 D = getAsTemplateNameDecl(*R.begin());
272 assert(D && "unambiguous result is not a template name")((D && "unambiguous result is not a template name") ?
static_cast<void> (0) : __assert_fail ("D && \"unambiguous result is not a template name\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 272, __PRETTY_FUNCTION__))
;
273 }
274
275 if (isa<UnresolvedUsingValueDecl>(D)) {
276 // We don't yet know whether this is a template-name or not.
277 MemberOfUnknownSpecialization = true;
278 return TNK_Non_template;
279 }
280
281 TemplateDecl *TD = cast<TemplateDecl>(D);
282
283 if (SS.isSet() && !SS.isInvalid()) {
284 NestedNameSpecifier *Qualifier = SS.getScopeRep();
285 Template = Context.getQualifiedTemplateName(Qualifier,
286 hasTemplateKeyword, TD);
287 } else {
288 Template = TemplateName(TD);
289 }
290
291 if (isa<FunctionTemplateDecl>(TD)) {
292 TemplateKind = TNK_Function_template;
293
294 // We'll do this lookup again later.
295 R.suppressDiagnostics();
296 } else {
297 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||((isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl
>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl
>(TD) || isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl
>(TD)) ? static_cast<void> (0) : __assert_fail ("isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD)"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 299, __PRETTY_FUNCTION__))
298 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||((isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl
>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl
>(TD) || isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl
>(TD)) ? static_cast<void> (0) : __assert_fail ("isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD)"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 299, __PRETTY_FUNCTION__))
299 isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD))((isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl
>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl
>(TD) || isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl
>(TD)) ? static_cast<void> (0) : __assert_fail ("isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD)"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 299, __PRETTY_FUNCTION__))
;
300 TemplateKind =
301 isa<VarTemplateDecl>(TD) ? TNK_Var_template :
302 isa<ConceptDecl>(TD) ? TNK_Concept_template :
303 TNK_Type_template;
304 }
305 }
306
307 TemplateResult = TemplateTy::make(Template);
308 return TemplateKind;
309}
310
311bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
312 SourceLocation NameLoc,
313 ParsedTemplateTy *Template) {
314 CXXScopeSpec SS;
315 bool MemberOfUnknownSpecialization = false;
316
317 // We could use redeclaration lookup here, but we don't need to: the
318 // syntactic form of a deduction guide is enough to identify it even
319 // if we can't look up the template name at all.
320 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
321 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
322 /*EnteringContext*/ false,
323 MemberOfUnknownSpecialization))
324 return false;
325
326 if (R.empty()) return false;
327 if (R.isAmbiguous()) {
328 // FIXME: Diagnose an ambiguity if we find at least one template.
329 R.suppressDiagnostics();
330 return false;
331 }
332
333 // We only treat template-names that name type templates as valid deduction
334 // guide names.
335 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
336 if (!TD || !getAsTypeTemplateDecl(TD))
337 return false;
338
339 if (Template)
340 *Template = TemplateTy::make(TemplateName(TD));
341 return true;
342}
343
344bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
345 SourceLocation IILoc,
346 Scope *S,
347 const CXXScopeSpec *SS,
348 TemplateTy &SuggestedTemplate,
349 TemplateNameKind &SuggestedKind) {
350 // We can't recover unless there's a dependent scope specifier preceding the
351 // template name.
352 // FIXME: Typo correction?
353 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
354 computeDeclContext(*SS))
355 return false;
356
357 // The code is missing a 'template' keyword prior to the dependent template
358 // name.
359 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
360 Diag(IILoc, diag::err_template_kw_missing)
361 << Qualifier << II.getName()
362 << FixItHint::CreateInsertion(IILoc, "template ");
363 SuggestedTemplate
364 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
365 SuggestedKind = TNK_Dependent_template_name;
366 return true;
367}
368
369bool Sema::LookupTemplateName(LookupResult &Found,
370 Scope *S, CXXScopeSpec &SS,
371 QualType ObjectType,
372 bool EnteringContext,
373 bool &MemberOfUnknownSpecialization,
374 RequiredTemplateKind RequiredTemplate,
375 AssumedTemplateKind *ATK,
376 bool AllowTypoCorrection) {
377 if (ATK)
378 *ATK = AssumedTemplateKind::None;
379
380 if (SS.isInvalid())
381 return true;
382
383 Found.setTemplateNameLookup(true);
384
385 // Determine where to perform name lookup
386 MemberOfUnknownSpecialization = false;
387 DeclContext *LookupCtx = nullptr;
388 bool IsDependent = false;
389 if (!ObjectType.isNull()) {
390 // This nested-name-specifier occurs in a member access expression, e.g.,
391 // x->B::f, and we are looking into the type of the object.
392 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist")((SS.isEmpty() && "ObjectType and scope specifier cannot coexist"
) ? static_cast<void> (0) : __assert_fail ("SS.isEmpty() && \"ObjectType and scope specifier cannot coexist\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 392, __PRETTY_FUNCTION__))
;
393 LookupCtx = computeDeclContext(ObjectType);
394 IsDependent = !LookupCtx && ObjectType->isDependentType();
395 assert((IsDependent || !ObjectType->isIncompleteType() ||(((IsDependent || !ObjectType->isIncompleteType() || ObjectType
->castAs<TagType>()->isBeingDefined()) &&
"Caller should have completed object type") ? static_cast<
void> (0) : __assert_fail ("(IsDependent || !ObjectType->isIncompleteType() || ObjectType->castAs<TagType>()->isBeingDefined()) && \"Caller should have completed object type\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 397, __PRETTY_FUNCTION__))
396 ObjectType->castAs<TagType>()->isBeingDefined()) &&(((IsDependent || !ObjectType->isIncompleteType() || ObjectType
->castAs<TagType>()->isBeingDefined()) &&
"Caller should have completed object type") ? static_cast<
void> (0) : __assert_fail ("(IsDependent || !ObjectType->isIncompleteType() || ObjectType->castAs<TagType>()->isBeingDefined()) && \"Caller should have completed object type\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 397, __PRETTY_FUNCTION__))
397 "Caller should have completed object type")(((IsDependent || !ObjectType->isIncompleteType() || ObjectType
->castAs<TagType>()->isBeingDefined()) &&
"Caller should have completed object type") ? static_cast<
void> (0) : __assert_fail ("(IsDependent || !ObjectType->isIncompleteType() || ObjectType->castAs<TagType>()->isBeingDefined()) && \"Caller should have completed object type\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 397, __PRETTY_FUNCTION__))
;
398
399 // Template names cannot appear inside an Objective-C class or object type
400 // or a vector type.
401 //
402 // FIXME: This is wrong. For example:
403 //
404 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
405 // Vec<int> vi;
406 // vi.Vec<int>::~Vec<int>();
407 //
408 // ... should be accepted but we will not treat 'Vec' as a template name
409 // here. The right thing to do would be to check if the name is a valid
410 // vector component name, and look up a template name if not. And similarly
411 // for lookups into Objective-C class and object types, where the same
412 // problem can arise.
413 if (ObjectType->isObjCObjectOrInterfaceType() ||
414 ObjectType->isVectorType()) {
415 Found.clear();
416 return false;
417 }
418 } else if (SS.isNotEmpty()) {
419 // This nested-name-specifier occurs after another nested-name-specifier,
420 // so long into the context associated with the prior nested-name-specifier.
421 LookupCtx = computeDeclContext(SS, EnteringContext);
422 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
423
424 // The declaration context must be complete.
425 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
426 return true;
427 }
428
429 bool ObjectTypeSearchedInScope = false;
430 bool AllowFunctionTemplatesInLookup = true;
431 if (LookupCtx) {
432 // Perform "qualified" name lookup into the declaration context we
433 // computed, which is either the type of the base of a member access
434 // expression or the declaration context associated with a prior
435 // nested-name-specifier.
436 LookupQualifiedName(Found, LookupCtx);
437
438 // FIXME: The C++ standard does not clearly specify what happens in the
439 // case where the object type is dependent, and implementations vary. In
440 // Clang, we treat a name after a . or -> as a template-name if lookup
441 // finds a non-dependent member or member of the current instantiation that
442 // is a type template, or finds no such members and lookup in the context
443 // of the postfix-expression finds a type template. In the latter case, the
444 // name is nonetheless dependent, and we may resolve it to a member of an
445 // unknown specialization when we come to instantiate the template.
446 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
447 }
448
449 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
450 // C++ [basic.lookup.classref]p1:
451 // In a class member access expression (5.2.5), if the . or -> token is
452 // immediately followed by an identifier followed by a <, the
453 // identifier must be looked up to determine whether the < is the
454 // beginning of a template argument list (14.2) or a less-than operator.
455 // The identifier is first looked up in the class of the object
456 // expression. If the identifier is not found, it is then looked up in
457 // the context of the entire postfix-expression and shall name a class
458 // template.
459 if (S)
460 LookupName(Found, S);
461
462 if (!ObjectType.isNull()) {
463 // FIXME: We should filter out all non-type templates here, particularly
464 // variable templates and concepts. But the exclusion of alias templates
465 // and template template parameters is a wording defect.
466 AllowFunctionTemplatesInLookup = false;
467 ObjectTypeSearchedInScope = true;
468 }
469
470 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
471 }
472
473 if (Found.isAmbiguous())
474 return false;
475
476 if (ATK && SS.isEmpty() && ObjectType.isNull() &&
477 !RequiredTemplate.hasTemplateKeyword()) {
478 // C++2a [temp.names]p2:
479 // A name is also considered to refer to a template if it is an
480 // unqualified-id followed by a < and name lookup finds either one or more
481 // functions or finds nothing.
482 //
483 // To keep our behavior consistent, we apply the "finds nothing" part in
484 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
485 // successfully form a call to an undeclared template-id.
486 bool AllFunctions =
487 getLangOpts().CPlusPlus20 &&
488 std::all_of(Found.begin(), Found.end(), [](NamedDecl *ND) {
489 return isa<FunctionDecl>(ND->getUnderlyingDecl());
490 });
491 if (AllFunctions || (Found.empty() && !IsDependent)) {
492 // If lookup found any functions, or if this is a name that can only be
493 // used for a function, then strongly assume this is a function
494 // template-id.
495 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
496 ? AssumedTemplateKind::FoundNothing
497 : AssumedTemplateKind::FoundFunctions;
498 Found.clear();
499 return false;
500 }
501 }
502
503 if (Found.empty() && !IsDependent && AllowTypoCorrection) {
504 // If we did not find any names, and this is not a disambiguation, attempt
505 // to correct any typos.
506 DeclarationName Name = Found.getLookupName();
507 Found.clear();
508 // Simple filter callback that, for keywords, only accepts the C++ *_cast
509 DefaultFilterCCC FilterCCC{};
510 FilterCCC.WantTypeSpecifiers = false;
511 FilterCCC.WantExpressionKeywords = false;
512 FilterCCC.WantRemainingKeywords = false;
513 FilterCCC.WantCXXNamedCasts = true;
514 if (TypoCorrection Corrected =
515 CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S,
516 &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) {
517 if (auto *ND = Corrected.getFoundDecl())
518 Found.addDecl(ND);
519 FilterAcceptableTemplateNames(Found);
520 if (Found.isAmbiguous()) {
521 Found.clear();
522 } else if (!Found.empty()) {
523 Found.setLookupName(Corrected.getCorrection());
524 if (LookupCtx) {
525 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
526 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
527 Name.getAsString() == CorrectedStr;
528 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
529 << Name << LookupCtx << DroppedSpecifier
530 << SS.getRange());
531 } else {
532 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
533 }
534 }
535 }
536 }
537
538 NamedDecl *ExampleLookupResult =
539 Found.empty() ? nullptr : Found.getRepresentativeDecl();
540 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
541 if (Found.empty()) {
542 if (IsDependent) {
543 MemberOfUnknownSpecialization = true;
544 return false;
545 }
546
547 // If a 'template' keyword was used, a lookup that finds only non-template
548 // names is an error.
549 if (ExampleLookupResult && RequiredTemplate) {
550 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
551 << Found.getLookupName() << SS.getRange()
552 << RequiredTemplate.hasTemplateKeyword()
553 << RequiredTemplate.getTemplateKeywordLoc();
554 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
555 diag::note_template_kw_refers_to_non_template)
556 << Found.getLookupName();
557 return true;
558 }
559
560 return false;
561 }
562
563 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
564 !getLangOpts().CPlusPlus11) {
565 // C++03 [basic.lookup.classref]p1:
566 // [...] If the lookup in the class of the object expression finds a
567 // template, the name is also looked up in the context of the entire
568 // postfix-expression and [...]
569 //
570 // Note: C++11 does not perform this second lookup.
571 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
572 LookupOrdinaryName);
573 FoundOuter.setTemplateNameLookup(true);
574 LookupName(FoundOuter, S);
575 // FIXME: We silently accept an ambiguous lookup here, in violation of
576 // [basic.lookup]/1.
577 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
578
579 NamedDecl *OuterTemplate;
580 if (FoundOuter.empty()) {
581 // - if the name is not found, the name found in the class of the
582 // object expression is used, otherwise
583 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
584 !(OuterTemplate =
585 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
586 // - if the name is found in the context of the entire
587 // postfix-expression and does not name a class template, the name
588 // found in the class of the object expression is used, otherwise
589 FoundOuter.clear();
590 } else if (!Found.isSuppressingDiagnostics()) {
591 // - if the name found is a class template, it must refer to the same
592 // entity as the one found in the class of the object expression,
593 // otherwise the program is ill-formed.
594 if (!Found.isSingleResult() ||
595 getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
596 OuterTemplate->getCanonicalDecl()) {
597 Diag(Found.getNameLoc(),
598 diag::ext_nested_name_member_ref_lookup_ambiguous)
599 << Found.getLookupName()
600 << ObjectType;
601 Diag(Found.getRepresentativeDecl()->getLocation(),
602 diag::note_ambig_member_ref_object_type)
603 << ObjectType;
604 Diag(FoundOuter.getFoundDecl()->getLocation(),
605 diag::note_ambig_member_ref_scope);
606
607 // Recover by taking the template that we found in the object
608 // expression's type.
609 }
610 }
611 }
612
613 return false;
614}
615
616void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
617 SourceLocation Less,
618 SourceLocation Greater) {
619 if (TemplateName.isInvalid())
620 return;
621
622 DeclarationNameInfo NameInfo;
623 CXXScopeSpec SS;
624 LookupNameKind LookupKind;
625
626 DeclContext *LookupCtx = nullptr;
627 NamedDecl *Found = nullptr;
628 bool MissingTemplateKeyword = false;
629
630 // Figure out what name we looked up.
631 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
632 NameInfo = DRE->getNameInfo();
633 SS.Adopt(DRE->getQualifierLoc());
634 LookupKind = LookupOrdinaryName;
635 Found = DRE->getFoundDecl();
636 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
637 NameInfo = ME->getMemberNameInfo();
638 SS.Adopt(ME->getQualifierLoc());
639 LookupKind = LookupMemberName;
640 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
641 Found = ME->getMemberDecl();
642 } else if (auto *DSDRE =
643 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
644 NameInfo = DSDRE->getNameInfo();
645 SS.Adopt(DSDRE->getQualifierLoc());
646 MissingTemplateKeyword = true;
647 } else if (auto *DSME =
648 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
649 NameInfo = DSME->getMemberNameInfo();
650 SS.Adopt(DSME->getQualifierLoc());
651 MissingTemplateKeyword = true;
652 } else {
653 llvm_unreachable("unexpected kind of potential template name")::llvm::llvm_unreachable_internal("unexpected kind of potential template name"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 653)
;
654 }
655
656 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
657 // was missing.
658 if (MissingTemplateKeyword) {
659 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
660 << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
661 return;
662 }
663
664 // Try to correct the name by looking for templates and C++ named casts.
665 struct TemplateCandidateFilter : CorrectionCandidateCallback {
666 Sema &S;
667 TemplateCandidateFilter(Sema &S) : S(S) {
668 WantTypeSpecifiers = false;
669 WantExpressionKeywords = false;
670 WantRemainingKeywords = false;
671 WantCXXNamedCasts = true;
672 };
673 bool ValidateCandidate(const TypoCorrection &Candidate) override {
674 if (auto *ND = Candidate.getCorrectionDecl())
675 return S.getAsTemplateNameDecl(ND);
676 return Candidate.isKeyword();
677 }
678
679 std::unique_ptr<CorrectionCandidateCallback> clone() override {
680 return std::make_unique<TemplateCandidateFilter>(*this);
681 }
682 };
683
684 DeclarationName Name = NameInfo.getName();
685 TemplateCandidateFilter CCC(*this);
686 if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
687 CTK_ErrorRecovery, LookupCtx)) {
688 auto *ND = Corrected.getFoundDecl();
689 if (ND)
690 ND = getAsTemplateNameDecl(ND);
691 if (ND || Corrected.isKeyword()) {
692 if (LookupCtx) {
693 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
694 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
695 Name.getAsString() == CorrectedStr;
696 diagnoseTypo(Corrected,
697 PDiag(diag::err_non_template_in_member_template_id_suggest)
698 << Name << LookupCtx << DroppedSpecifier
699 << SS.getRange(), false);
700 } else {
701 diagnoseTypo(Corrected,
702 PDiag(diag::err_non_template_in_template_id_suggest)
703 << Name, false);
704 }
705 if (Found)
706 Diag(Found->getLocation(),
707 diag::note_non_template_in_template_id_found);
708 return;
709 }
710 }
711
712 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
713 << Name << SourceRange(Less, Greater);
714 if (Found)
715 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
716}
717
718/// ActOnDependentIdExpression - Handle a dependent id-expression that
719/// was just parsed. This is only possible with an explicit scope
720/// specifier naming a dependent type.
721ExprResult
722Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
723 SourceLocation TemplateKWLoc,
724 const DeclarationNameInfo &NameInfo,
725 bool isAddressOfOperand,
726 const TemplateArgumentListInfo *TemplateArgs) {
727 DeclContext *DC = getFunctionLevelDeclContext();
728
729 // C++11 [expr.prim.general]p12:
730 // An id-expression that denotes a non-static data member or non-static
731 // member function of a class can only be used:
732 // (...)
733 // - if that id-expression denotes a non-static data member and it
734 // appears in an unevaluated operand.
735 //
736 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
737 // CXXDependentScopeMemberExpr. The former can instantiate to either
738 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
739 // always a MemberExpr.
740 bool MightBeCxx11UnevalField =
741 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
742
743 // Check if the nested name specifier is an enum type.
744 bool IsEnum = false;
745 if (NestedNameSpecifier *NNS = SS.getScopeRep())
746 IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
747
748 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
749 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
750 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType();
751
752 // Since the 'this' expression is synthesized, we don't need to
753 // perform the double-lookup check.
754 NamedDecl *FirstQualifierInScope = nullptr;
755
756 return CXXDependentScopeMemberExpr::Create(
757 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
758 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
759 FirstQualifierInScope, NameInfo, TemplateArgs);
760 }
761
762 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
763}
764
765ExprResult
766Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
767 SourceLocation TemplateKWLoc,
768 const DeclarationNameInfo &NameInfo,
769 const TemplateArgumentListInfo *TemplateArgs) {
770 // DependentScopeDeclRefExpr::Create requires a valid QualifierLoc
771 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
772 if (!QualifierLoc)
773 return ExprError();
774
775 return DependentScopeDeclRefExpr::Create(
776 Context, QualifierLoc, TemplateKWLoc, NameInfo, TemplateArgs);
777}
778
779
780/// Determine whether we would be unable to instantiate this template (because
781/// it either has no definition, or is in the process of being instantiated).
782bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
783 NamedDecl *Instantiation,
784 bool InstantiatedFromMember,
785 const NamedDecl *Pattern,
786 const NamedDecl *PatternDef,
787 TemplateSpecializationKind TSK,
788 bool Complain /*= true*/) {
789 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||((isa<TagDecl>(Instantiation) || isa<FunctionDecl>
(Instantiation) || isa<VarDecl>(Instantiation)) ? static_cast
<void> (0) : __assert_fail ("isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) || isa<VarDecl>(Instantiation)"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 790, __PRETTY_FUNCTION__))
790 isa<VarDecl>(Instantiation))((isa<TagDecl>(Instantiation) || isa<FunctionDecl>
(Instantiation) || isa<VarDecl>(Instantiation)) ? static_cast
<void> (0) : __assert_fail ("isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) || isa<VarDecl>(Instantiation)"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 790, __PRETTY_FUNCTION__))
;
791
792 bool IsEntityBeingDefined = false;
793 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
794 IsEntityBeingDefined = TD->isBeingDefined();
795
796 if (PatternDef && !IsEntityBeingDefined) {
797 NamedDecl *SuggestedDef = nullptr;
798 if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
799 /*OnlyNeedComplete*/false)) {
800 // If we're allowed to diagnose this and recover, do so.
801 bool Recover = Complain && !isSFINAEContext();
802 if (Complain)
803 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
804 Sema::MissingImportKind::Definition, Recover);
805 return !Recover;
806 }
807 return false;
808 }
809
810 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
811 return true;
812
813 llvm::Optional<unsigned> Note;
814 QualType InstantiationTy;
815 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
816 InstantiationTy = Context.getTypeDeclType(TD);
817 if (PatternDef) {
818 Diag(PointOfInstantiation,
819 diag::err_template_instantiate_within_definition)
820 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
821 << InstantiationTy;
822 // Not much point in noting the template declaration here, since
823 // we're lexically inside it.
824 Instantiation->setInvalidDecl();
825 } else if (InstantiatedFromMember) {
826 if (isa<FunctionDecl>(Instantiation)) {
827 Diag(PointOfInstantiation,
828 diag::err_explicit_instantiation_undefined_member)
829 << /*member function*/ 1 << Instantiation->getDeclName()
830 << Instantiation->getDeclContext();
831 Note = diag::note_explicit_instantiation_here;
832 } else {
833 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!")((isa<TagDecl>(Instantiation) && "Must be a TagDecl!"
) ? static_cast<void> (0) : __assert_fail ("isa<TagDecl>(Instantiation) && \"Must be a TagDecl!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 833, __PRETTY_FUNCTION__))
;
834 Diag(PointOfInstantiation,
835 diag::err_implicit_instantiate_member_undefined)
836 << InstantiationTy;
837 Note = diag::note_member_declared_at;
838 }
839 } else {
840 if (isa<FunctionDecl>(Instantiation)) {
841 Diag(PointOfInstantiation,
842 diag::err_explicit_instantiation_undefined_func_template)
843 << Pattern;
844 Note = diag::note_explicit_instantiation_here;
845 } else if (isa<TagDecl>(Instantiation)) {
846 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
847 << (TSK != TSK_ImplicitInstantiation)
848 << InstantiationTy;
849 Note = diag::note_template_decl_here;
850 } else {
851 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!")((isa<VarDecl>(Instantiation) && "Must be a VarDecl!"
) ? static_cast<void> (0) : __assert_fail ("isa<VarDecl>(Instantiation) && \"Must be a VarDecl!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 851, __PRETTY_FUNCTION__))
;
852 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
853 Diag(PointOfInstantiation,
854 diag::err_explicit_instantiation_undefined_var_template)
855 << Instantiation;
856 Instantiation->setInvalidDecl();
857 } else
858 Diag(PointOfInstantiation,
859 diag::err_explicit_instantiation_undefined_member)
860 << /*static data member*/ 2 << Instantiation->getDeclName()
861 << Instantiation->getDeclContext();
862 Note = diag::note_explicit_instantiation_here;
863 }
864 }
865 if (Note) // Diagnostics were emitted.
866 Diag(Pattern->getLocation(), Note.getValue());
867
868 // In general, Instantiation isn't marked invalid to get more than one
869 // error for multiple undefined instantiations. But the code that does
870 // explicit declaration -> explicit definition conversion can't handle
871 // invalid declarations, so mark as invalid in that case.
872 if (TSK == TSK_ExplicitInstantiationDeclaration)
873 Instantiation->setInvalidDecl();
874 return true;
875}
876
877/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
878/// that the template parameter 'PrevDecl' is being shadowed by a new
879/// declaration at location Loc. Returns true to indicate that this is
880/// an error, and false otherwise.
881void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
882 assert(PrevDecl->isTemplateParameter() && "Not a template parameter")((PrevDecl->isTemplateParameter() && "Not a template parameter"
) ? static_cast<void> (0) : __assert_fail ("PrevDecl->isTemplateParameter() && \"Not a template parameter\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 882, __PRETTY_FUNCTION__))
;
883
884 // C++ [temp.local]p4:
885 // A template-parameter shall not be redeclared within its
886 // scope (including nested scopes).
887 //
888 // Make this a warning when MSVC compatibility is requested.
889 unsigned DiagId = getLangOpts().MSVCCompat ? diag::ext_template_param_shadow
890 : diag::err_template_param_shadow;
891 Diag(Loc, DiagId) << cast<NamedDecl>(PrevDecl)->getDeclName();
892 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
893}
894
895/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
896/// the parameter D to reference the templated declaration and return a pointer
897/// to the template declaration. Otherwise, do nothing to D and return null.
898TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
899 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
900 D = Temp->getTemplatedDecl();
901 return Temp;
902 }
903 return nullptr;
904}
905
906ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
907 SourceLocation EllipsisLoc) const {
908 assert(Kind == Template &&((Kind == Template && "Only template template arguments can be pack expansions here"
) ? static_cast<void> (0) : __assert_fail ("Kind == Template && \"Only template template arguments can be pack expansions here\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 909, __PRETTY_FUNCTION__))
909 "Only template template arguments can be pack expansions here")((Kind == Template && "Only template template arguments can be pack expansions here"
) ? static_cast<void> (0) : __assert_fail ("Kind == Template && \"Only template template arguments can be pack expansions here\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 909, __PRETTY_FUNCTION__))
;
910 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&((getAsTemplate().get().containsUnexpandedParameterPack() &&
"Template template argument pack expansion without packs") ?
static_cast<void> (0) : __assert_fail ("getAsTemplate().get().containsUnexpandedParameterPack() && \"Template template argument pack expansion without packs\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 911, __PRETTY_FUNCTION__))
911 "Template template argument pack expansion without packs")((getAsTemplate().get().containsUnexpandedParameterPack() &&
"Template template argument pack expansion without packs") ?
static_cast<void> (0) : __assert_fail ("getAsTemplate().get().containsUnexpandedParameterPack() && \"Template template argument pack expansion without packs\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 911, __PRETTY_FUNCTION__))
;
912 ParsedTemplateArgument Result(*this);
913 Result.EllipsisLoc = EllipsisLoc;
914 return Result;
915}
916
917static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
918 const ParsedTemplateArgument &Arg) {
919
920 switch (Arg.getKind()) {
921 case ParsedTemplateArgument::Type: {
922 TypeSourceInfo *DI;
923 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
924 if (!DI)
925 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
926 return TemplateArgumentLoc(TemplateArgument(T), DI);
927 }
928
929 case ParsedTemplateArgument::NonType: {
930 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
931 return TemplateArgumentLoc(TemplateArgument(E), E);
932 }
933
934 case ParsedTemplateArgument::Template: {
935 TemplateName Template = Arg.getAsTemplate().get();
936 TemplateArgument TArg;
937 if (Arg.getEllipsisLoc().isValid())
938 TArg = TemplateArgument(Template, Optional<unsigned int>());
939 else
940 TArg = Template;
941 return TemplateArgumentLoc(
942 SemaRef.Context, TArg,
943 Arg.getScopeSpec().getWithLocInContext(SemaRef.Context),
944 Arg.getLocation(), Arg.getEllipsisLoc());
945 }
946 }
947
948 llvm_unreachable("Unhandled parsed template argument")::llvm::llvm_unreachable_internal("Unhandled parsed template argument"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 948)
;
949}
950
951/// Translates template arguments as provided by the parser
952/// into template arguments used by semantic analysis.
953void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
954 TemplateArgumentListInfo &TemplateArgs) {
955 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
956 TemplateArgs.addArgument(translateTemplateArgument(*this,
957 TemplateArgsIn[I]));
958}
959
960static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
961 SourceLocation Loc,
962 IdentifierInfo *Name) {
963 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
964 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
965 if (PrevDecl && PrevDecl->isTemplateParameter())
966 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
967}
968
969/// Convert a parsed type into a parsed template argument. This is mostly
970/// trivial, except that we may have parsed a C++17 deduced class template
971/// specialization type, in which case we should form a template template
972/// argument instead of a type template argument.
973ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
974 TypeSourceInfo *TInfo;
975 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
976 if (T.isNull())
977 return ParsedTemplateArgument();
978 assert(TInfo && "template argument with no location")((TInfo && "template argument with no location") ? static_cast
<void> (0) : __assert_fail ("TInfo && \"template argument with no location\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 978, __PRETTY_FUNCTION__))
;
979
980 // If we might have formed a deduced template specialization type, convert
981 // it to a template template argument.
982 if (getLangOpts().CPlusPlus17) {
983 TypeLoc TL = TInfo->getTypeLoc();
984 SourceLocation EllipsisLoc;
985 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
986 EllipsisLoc = PET.getEllipsisLoc();
987 TL = PET.getPatternLoc();
988 }
989
990 CXXScopeSpec SS;
991 if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
992 SS.Adopt(ET.getQualifierLoc());
993 TL = ET.getNamedTypeLoc();
994 }
995
996 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
997 TemplateName Name = DTST.getTypePtr()->getTemplateName();
998 if (SS.isSet())
999 Name = Context.getQualifiedTemplateName(SS.getScopeRep(),
1000 /*HasTemplateKeyword*/ false,
1001 Name.getAsTemplateDecl());
1002 ParsedTemplateArgument Result(SS, TemplateTy::make(Name),
1003 DTST.getTemplateNameLoc());
1004 if (EllipsisLoc.isValid())
1005 Result = Result.getTemplatePackExpansion(EllipsisLoc);
1006 return Result;
1007 }
1008 }
1009
1010 // This is a normal type template argument. Note, if the type template
1011 // argument is an injected-class-name for a template, it has a dual nature
1012 // and can be used as either a type or a template. We handle that in
1013 // convertTypeTemplateArgumentToTemplate.
1014 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1015 ParsedType.get().getAsOpaquePtr(),
1016 TInfo->getTypeLoc().getBeginLoc());
1017}
1018
1019/// ActOnTypeParameter - Called when a C++ template type parameter
1020/// (e.g., "typename T") has been parsed. Typename specifies whether
1021/// the keyword "typename" was used to declare the type parameter
1022/// (otherwise, "class" was used), and KeyLoc is the location of the
1023/// "class" or "typename" keyword. ParamName is the name of the
1024/// parameter (NULL indicates an unnamed template parameter) and
1025/// ParamNameLoc is the location of the parameter name (if any).
1026/// If the type parameter has a default argument, it will be added
1027/// later via ActOnTypeParameterDefault.
1028NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
1029 SourceLocation EllipsisLoc,
1030 SourceLocation KeyLoc,
1031 IdentifierInfo *ParamName,
1032 SourceLocation ParamNameLoc,
1033 unsigned Depth, unsigned Position,
1034 SourceLocation EqualLoc,
1035 ParsedType DefaultArg,
1036 bool HasTypeConstraint) {
1037 assert(S->isTemplateParamScope() &&((S->isTemplateParamScope() && "Template type parameter not in template parameter scope!"
) ? static_cast<void> (0) : __assert_fail ("S->isTemplateParamScope() && \"Template type parameter not in template parameter scope!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 1038, __PRETTY_FUNCTION__))
1038 "Template type parameter not in template parameter scope!")((S->isTemplateParamScope() && "Template type parameter not in template parameter scope!"
) ? static_cast<void> (0) : __assert_fail ("S->isTemplateParamScope() && \"Template type parameter not in template parameter scope!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 1038, __PRETTY_FUNCTION__))
;
1039
1040 bool IsParameterPack = EllipsisLoc.isValid();
1041 TemplateTypeParmDecl *Param
1042 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1043 KeyLoc, ParamNameLoc, Depth, Position,
1044 ParamName, Typename, IsParameterPack,
1045 HasTypeConstraint);
1046 Param->setAccess(AS_public);
1047
1048 if (Param->isParameterPack())
1049 if (auto *LSI = getEnclosingLambda())
1050 LSI->LocalPacks.push_back(Param);
1051
1052 if (ParamName) {
1053 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1054
1055 // Add the template parameter into the current scope.
1056 S->AddDecl(Param);
1057 IdResolver.AddDecl(Param);
1058 }
1059
1060 // C++0x [temp.param]p9:
1061 // A default template-argument may be specified for any kind of
1062 // template-parameter that is not a template parameter pack.
1063 if (DefaultArg && IsParameterPack) {
1064 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1065 DefaultArg = nullptr;
1066 }
1067
1068 // Handle the default argument, if provided.
1069 if (DefaultArg) {
1070 TypeSourceInfo *DefaultTInfo;
1071 GetTypeFromParser(DefaultArg, &DefaultTInfo);
1072
1073 assert(DefaultTInfo && "expected source information for type")((DefaultTInfo && "expected source information for type"
) ? static_cast<void> (0) : __assert_fail ("DefaultTInfo && \"expected source information for type\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 1073, __PRETTY_FUNCTION__))
;
1074
1075 // Check for unexpanded parameter packs.
1076 if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1077 UPPC_DefaultArgument))
1078 return Param;
1079
1080 // Check the template argument itself.
1081 if (CheckTemplateArgument(Param, DefaultTInfo)) {
1082 Param->setInvalidDecl();
1083 return Param;
1084 }
1085
1086 Param->setDefaultArgument(DefaultTInfo);
1087 }
1088
1089 return Param;
1090}
1091
1092/// Convert the parser's template argument list representation into our form.
1093static TemplateArgumentListInfo
1094makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
1095 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1096 TemplateId.RAngleLoc);
1097 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1098 TemplateId.NumArgs);
1099 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1100 return TemplateArgs;
1101}
1102
1103bool Sema::ActOnTypeConstraint(const CXXScopeSpec &SS,
1104 TemplateIdAnnotation *TypeConstr,
1105 TemplateTypeParmDecl *ConstrainedParameter,
1106 SourceLocation EllipsisLoc) {
1107 ConceptDecl *CD =
1108 cast<ConceptDecl>(TypeConstr->Template.get().getAsTemplateDecl());
1109
1110 // C++2a [temp.param]p4:
1111 // [...] The concept designated by a type-constraint shall be a type
1112 // concept ([temp.concept]).
1113 if (!CD->isTypeConcept()) {
1114 Diag(TypeConstr->TemplateNameLoc,
1115 diag::err_type_constraint_non_type_concept);
1116 return true;
1117 }
1118
1119 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1120
1121 if (!WereArgsSpecified &&
1122 CD->getTemplateParameters()->getMinRequiredArguments() > 1) {
1123 Diag(TypeConstr->TemplateNameLoc,
1124 diag::err_type_constraint_missing_arguments) << CD;
1125 return true;
1126 }
1127
1128 TemplateArgumentListInfo TemplateArgs;
1129 if (TypeConstr->LAngleLoc.isValid()) {
1130 TemplateArgs =
1131 makeTemplateArgumentListInfo(*this, *TypeConstr);
1132 }
1133 return AttachTypeConstraint(
1134 SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1135 DeclarationNameInfo(DeclarationName(TypeConstr->Name),
1136 TypeConstr->TemplateNameLoc), CD,
1137 TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1138 ConstrainedParameter, EllipsisLoc);
1139}
1140
1141template<typename ArgumentLocAppender>
1142static ExprResult formImmediatelyDeclaredConstraint(
1143 Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo,
1144 ConceptDecl *NamedConcept, SourceLocation LAngleLoc,
1145 SourceLocation RAngleLoc, QualType ConstrainedType,
1146 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1147 SourceLocation EllipsisLoc) {
1148
1149 TemplateArgumentListInfo ConstraintArgs;
1150 ConstraintArgs.addArgument(
1151 S.getTrivialTemplateArgumentLoc(TemplateArgument(ConstrainedType),
1152 /*NTTPType=*/QualType(), ParamNameLoc));
1153
1154 ConstraintArgs.setRAngleLoc(RAngleLoc);
1155 ConstraintArgs.setLAngleLoc(LAngleLoc);
1156 Appender(ConstraintArgs);
1157
1158 // C++2a [temp.param]p4:
1159 // [...] This constraint-expression E is called the immediately-declared
1160 // constraint of T. [...]
1161 CXXScopeSpec SS;
1162 SS.Adopt(NS);
1163 ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1164 SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1165 /*FoundDecl=*/NamedConcept, NamedConcept, &ConstraintArgs);
1166 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1167 return ImmediatelyDeclaredConstraint;
1168
1169 // C++2a [temp.param]p4:
1170 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1171 //
1172 // We have the following case:
1173 //
1174 // template<typename T> concept C1 = true;
1175 // template<C1... T> struct s1;
1176 //
1177 // The constraint: (C1<T> && ...)
1178 //
1179 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1180 // any unqualified lookups for 'operator&&' here.
1181 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1182 /*LParenLoc=*/SourceLocation(),
1183 ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1184 EllipsisLoc, /*RHS=*/nullptr,
1185 /*RParenLoc=*/SourceLocation(),
1186 /*NumExpansions=*/None);
1187}
1188
1189/// Attach a type-constraint to a template parameter.
1190/// \returns true if an error occured. This can happen if the
1191/// immediately-declared constraint could not be formed (e.g. incorrect number
1192/// of arguments for the named concept).
1193bool Sema::AttachTypeConstraint(NestedNameSpecifierLoc NS,
1194 DeclarationNameInfo NameInfo,
1195 ConceptDecl *NamedConcept,
1196 const TemplateArgumentListInfo *TemplateArgs,
1197 TemplateTypeParmDecl *ConstrainedParameter,
1198 SourceLocation EllipsisLoc) {
1199 // C++2a [temp.param]p4:
1200 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1201 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1202 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1203 TemplateArgs ? ASTTemplateArgumentListInfo::Create(Context,
1204 *TemplateArgs) : nullptr;
1205
1206 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1207
1208 ExprResult ImmediatelyDeclaredConstraint =
1209 formImmediatelyDeclaredConstraint(
1210 *this, NS, NameInfo, NamedConcept,
1211 TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1212 TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1213 ParamAsArgument, ConstrainedParameter->getLocation(),
1214 [&] (TemplateArgumentListInfo &ConstraintArgs) {
1215 if (TemplateArgs)
1216 for (const auto &ArgLoc : TemplateArgs->arguments())
1217 ConstraintArgs.addArgument(ArgLoc);
1218 }, EllipsisLoc);
1219 if (ImmediatelyDeclaredConstraint.isInvalid())
1220 return true;
1221
1222 ConstrainedParameter->setTypeConstraint(NS, NameInfo,
1223 /*FoundDecl=*/NamedConcept,
1224 NamedConcept, ArgsAsWritten,
1225 ImmediatelyDeclaredConstraint.get());
1226 return false;
1227}
1228
1229bool Sema::AttachTypeConstraint(AutoTypeLoc TL, NonTypeTemplateParmDecl *NTTP,
1230 SourceLocation EllipsisLoc) {
1231 if (NTTP->getType() != TL.getType() ||
1232 TL.getAutoKeyword() != AutoTypeKeyword::Auto) {
1233 Diag(NTTP->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1234 diag::err_unsupported_placeholder_constraint)
1235 << NTTP->getTypeSourceInfo()->getTypeLoc().getSourceRange();
1236 return true;
1237 }
1238 // FIXME: Concepts: This should be the type of the placeholder, but this is
1239 // unclear in the wording right now.
1240 DeclRefExpr *Ref = BuildDeclRefExpr(NTTP, NTTP->getType(), VK_RValue,
1241 NTTP->getLocation());
1242 if (!Ref)
1243 return true;
1244 ExprResult ImmediatelyDeclaredConstraint =
1245 formImmediatelyDeclaredConstraint(
1246 *this, TL.getNestedNameSpecifierLoc(), TL.getConceptNameInfo(),
1247 TL.getNamedConcept(), TL.getLAngleLoc(), TL.getRAngleLoc(),
1248 BuildDecltypeType(Ref, NTTP->getLocation()), NTTP->getLocation(),
1249 [&] (TemplateArgumentListInfo &ConstraintArgs) {
1250 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1251 ConstraintArgs.addArgument(TL.getArgLoc(I));
1252 }, EllipsisLoc);
1253 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1254 !ImmediatelyDeclaredConstraint.isUsable())
1255 return true;
1256
1257 NTTP->setPlaceholderTypeConstraint(ImmediatelyDeclaredConstraint.get());
1258 return false;
1259}
1260
1261/// Check that the type of a non-type template parameter is
1262/// well-formed.
1263///
1264/// \returns the (possibly-promoted) parameter type if valid;
1265/// otherwise, produces a diagnostic and returns a NULL type.
1266QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
1267 SourceLocation Loc) {
1268 if (TSI->getType()->isUndeducedType()) {
1269 // C++17 [temp.dep.expr]p3:
1270 // An id-expression is type-dependent if it contains
1271 // - an identifier associated by name lookup with a non-type
1272 // template-parameter declared with a type that contains a
1273 // placeholder type (7.1.7.4),
1274 TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
1275 }
1276
1277 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1278}
1279
1280/// Require the given type to be a structural type, and diagnose if it is not.
1281///
1282/// \return \c true if an error was produced.
1283bool Sema::RequireStructuralType(QualType T, SourceLocation Loc) {
1284 if (T->isDependentType())
1285 return false;
1286
1287 if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1288 return true;
1289
1290 if (T->isStructuralType())
1291 return false;
1292
1293 // Structural types are required to be object types or lvalue references.
1294 if (T->isRValueReferenceType()) {
1295 Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1296 return true;
1297 }
1298
1299 // Don't mention structural types in our diagnostic prior to C++20. Also,
1300 // there's not much more we can say about non-scalar non-class types --
1301 // because we can't see functions or arrays here, those can only be language
1302 // extensions.
1303 if (!getLangOpts().CPlusPlus20 ||
1304 (!T->isScalarType() && !T->isRecordType())) {
1305 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1306 return true;
1307 }
1308
1309 // Structural types are required to be literal types.
1310 if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1311 return true;
1312
1313 Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1314
1315 // Drill down into the reason why the class is non-structural.
1316 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1317 // All members are required to be public and non-mutable, and can't be of
1318 // rvalue reference type. Check these conditions first to prefer a "local"
1319 // reason over a more distant one.
1320 for (const FieldDecl *FD : RD->fields()) {
1321 if (FD->getAccess() != AS_public) {
1322 Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1323 return true;
1324 }
1325 if (FD->isMutable()) {
1326 Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1327 return true;
1328 }
1329 if (FD->getType()->isRValueReferenceType()) {
1330 Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1331 << T;
1332 return true;
1333 }
1334 }
1335
1336 // All bases are required to be public.
1337 for (const auto &BaseSpec : RD->bases()) {
1338 if (BaseSpec.getAccessSpecifier() != AS_public) {
1339 Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1340 << T << 1;
1341 return true;
1342 }
1343 }
1344
1345 // All subobjects are required to be of structural types.
1346 SourceLocation SubLoc;
1347 QualType SubType;
1348 int Kind = -1;
1349
1350 for (const FieldDecl *FD : RD->fields()) {
1351 QualType T = Context.getBaseElementType(FD->getType());
1352 if (!T->isStructuralType()) {
1353 SubLoc = FD->getLocation();
1354 SubType = T;
1355 Kind = 0;
1356 break;
1357 }
1358 }
1359
1360 if (Kind == -1) {
1361 for (const auto &BaseSpec : RD->bases()) {
1362 QualType T = BaseSpec.getType();
1363 if (!T->isStructuralType()) {
1364 SubLoc = BaseSpec.getBaseTypeLoc();
1365 SubType = T;
1366 Kind = 1;
1367 break;
1368 }
1369 }
1370 }
1371
1372 assert(Kind != -1 && "couldn't find reason why type is not structural")((Kind != -1 && "couldn't find reason why type is not structural"
) ? static_cast<void> (0) : __assert_fail ("Kind != -1 && \"couldn't find reason why type is not structural\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 1372, __PRETTY_FUNCTION__))
;
1373 Diag(SubLoc, diag::note_not_structural_subobject)
1374 << T << Kind << SubType;
1375 T = SubType;
1376 RD = T->getAsCXXRecordDecl();
Value stored to 'RD' is never read
1377 }
1378
1379 return true;
1380}
1381
1382QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
1383 SourceLocation Loc) {
1384 // We don't allow variably-modified types as the type of non-type template
1385 // parameters.
1386 if (T->isVariablyModifiedType()) {
1387 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1388 << T;
1389 return QualType();
1390 }
1391
1392 // C++ [temp.param]p4:
1393 //
1394 // A non-type template-parameter shall have one of the following
1395 // (optionally cv-qualified) types:
1396 //
1397 // -- integral or enumeration type,
1398 if (T->isIntegralOrEnumerationType() ||
1399 // -- pointer to object or pointer to function,
1400 T->isPointerType() ||
1401 // -- lvalue reference to object or lvalue reference to function,
1402 T->isLValueReferenceType() ||
1403 // -- pointer to member,
1404 T->isMemberPointerType() ||
1405 // -- std::nullptr_t, or
1406 T->isNullPtrType() ||
1407 // -- a type that contains a placeholder type.
1408 T->isUndeducedType()) {
1409 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1410 // are ignored when determining its type.
1411 return T.getUnqualifiedType();
1412 }
1413
1414 // C++ [temp.param]p8:
1415 //
1416 // A non-type template-parameter of type "array of T" or
1417 // "function returning T" is adjusted to be of type "pointer to
1418 // T" or "pointer to function returning T", respectively.
1419 if (T->isArrayType() || T->isFunctionType())
1420 return Context.getDecayedType(T);
1421
1422 // If T is a dependent type, we can't do the check now, so we
1423 // assume that it is well-formed. Note that stripping off the
1424 // qualifiers here is not really correct if T turns out to be
1425 // an array type, but we'll recompute the type everywhere it's
1426 // used during instantiation, so that should be OK. (Using the
1427 // qualified type is equally wrong.)
1428 if (T->isDependentType())
1429 return T.getUnqualifiedType();
1430
1431 // C++20 [temp.param]p6:
1432 // -- a structural type
1433 if (RequireStructuralType(T, Loc))
1434 return QualType();
1435
1436 if (!getLangOpts().CPlusPlus20) {
1437 // FIXME: Consider allowing structural types as an extension in C++17. (In
1438 // earlier language modes, the template argument evaluation rules are too
1439 // inflexible.)
1440 Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1441 return QualType();
1442 }
1443
1444 return T.getUnqualifiedType();
1445}
1446
1447NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
1448 unsigned Depth,
1449 unsigned Position,
1450 SourceLocation EqualLoc,
1451 Expr *Default) {
1452 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
1453
1454 // Check that we have valid decl-specifiers specified.
1455 auto CheckValidDeclSpecifiers = [this, &D] {
1456 // C++ [temp.param]
1457 // p1
1458 // template-parameter:
1459 // ...
1460 // parameter-declaration
1461 // p2
1462 // ... A storage class shall not be specified in a template-parameter
1463 // declaration.
1464 // [dcl.typedef]p1:
1465 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1466 // of a parameter-declaration
1467 const DeclSpec &DS = D.getDeclSpec();
1468 auto EmitDiag = [this](SourceLocation Loc) {
1469 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1470 << FixItHint::CreateRemoval(Loc);
1471 };
1472 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1473 EmitDiag(DS.getStorageClassSpecLoc());
1474
1475 if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
1476 EmitDiag(DS.getThreadStorageClassSpecLoc());
1477
1478 // [dcl.inline]p1:
1479 // The inline specifier can be applied only to the declaration or
1480 // definition of a variable or function.
1481
1482 if (DS.isInlineSpecified())
1483 EmitDiag(DS.getInlineSpecLoc());
1484
1485 // [dcl.constexpr]p1:
1486 // The constexpr specifier shall be applied only to the definition of a
1487 // variable or variable template or the declaration of a function or
1488 // function template.
1489
1490 if (DS.hasConstexprSpecifier())
1491 EmitDiag(DS.getConstexprSpecLoc());
1492
1493 // [dcl.fct.spec]p1:
1494 // Function-specifiers can be used only in function declarations.
1495
1496 if (DS.isVirtualSpecified())
1497 EmitDiag(DS.getVirtualSpecLoc());
1498
1499 if (DS.hasExplicitSpecifier())
1500 EmitDiag(DS.getExplicitSpecLoc());
1501
1502 if (DS.isNoreturnSpecified())
1503 EmitDiag(DS.getNoreturnSpecLoc());
1504 };
1505
1506 CheckValidDeclSpecifiers();
1507
1508 if (TInfo->getType()->isUndeducedType()) {
1509 Diag(D.getIdentifierLoc(),
1510 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1511 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1512 }
1513
1514 assert(S->isTemplateParamScope() &&((S->isTemplateParamScope() && "Non-type template parameter not in template parameter scope!"
) ? static_cast<void> (0) : __assert_fail ("S->isTemplateParamScope() && \"Non-type template parameter not in template parameter scope!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 1515, __PRETTY_FUNCTION__))
1515 "Non-type template parameter not in template parameter scope!")((S->isTemplateParamScope() && "Non-type template parameter not in template parameter scope!"
) ? static_cast<void> (0) : __assert_fail ("S->isTemplateParamScope() && \"Non-type template parameter not in template parameter scope!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 1515, __PRETTY_FUNCTION__))
;
1516 bool Invalid = false;
1517
1518 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
1519 if (T.isNull()) {
1520 T = Context.IntTy; // Recover with an 'int' type.
1521 Invalid = true;
1522 }
1523
1524 CheckFunctionOrTemplateParamDeclarator(S, D);
1525
1526 IdentifierInfo *ParamName = D.getIdentifier();
1527 bool IsParameterPack = D.hasEllipsis();
1528 NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
1529 Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1530 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1531 TInfo);
1532 Param->setAccess(AS_public);
1533
1534 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc())
1535 if (TL.isConstrained())
1536 if (AttachTypeConstraint(TL, Param, D.getEllipsisLoc()))
1537 Invalid = true;
1538
1539 if (Invalid)
1540 Param->setInvalidDecl();
1541
1542 if (Param->isParameterPack())
1543 if (auto *LSI = getEnclosingLambda())
1544 LSI->LocalPacks.push_back(Param);
1545
1546 if (ParamName) {
1547 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1548 ParamName);
1549
1550 // Add the template parameter into the current scope.
1551 S->AddDecl(Param);
1552 IdResolver.AddDecl(Param);
1553 }
1554
1555 // C++0x [temp.param]p9:
1556 // A default template-argument may be specified for any kind of
1557 // template-parameter that is not a template parameter pack.
1558 if (Default && IsParameterPack) {
1559 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1560 Default = nullptr;
1561 }
1562
1563 // Check the well-formedness of the default template argument, if provided.
1564 if (Default) {
1565 // Check for unexpanded parameter packs.
1566 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
1567 return Param;
1568
1569 TemplateArgument Converted;
1570 ExprResult DefaultRes =
1571 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
1572 if (DefaultRes.isInvalid()) {
1573 Param->setInvalidDecl();
1574 return Param;
1575 }
1576 Default = DefaultRes.get();
1577
1578 Param->setDefaultArgument(Default);
1579 }
1580
1581 return Param;
1582}
1583
1584/// ActOnTemplateTemplateParameter - Called when a C++ template template
1585/// parameter (e.g. T in template <template \<typename> class T> class array)
1586/// has been parsed. S is the current scope.
1587NamedDecl *Sema::ActOnTemplateTemplateParameter(Scope* S,
1588 SourceLocation TmpLoc,
1589 TemplateParameterList *Params,
1590 SourceLocation EllipsisLoc,
1591 IdentifierInfo *Name,
1592 SourceLocation NameLoc,
1593 unsigned Depth,
1594 unsigned Position,
1595 SourceLocation EqualLoc,
1596 ParsedTemplateArgument Default) {
1597 assert(S->isTemplateParamScope() &&((S->isTemplateParamScope() && "Template template parameter not in template parameter scope!"
) ? static_cast<void> (0) : __assert_fail ("S->isTemplateParamScope() && \"Template template parameter not in template parameter scope!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 1598, __PRETTY_FUNCTION__))
1598 "Template template parameter not in template parameter scope!")((S->isTemplateParamScope() && "Template template parameter not in template parameter scope!"
) ? static_cast<void> (0) : __assert_fail ("S->isTemplateParamScope() && \"Template template parameter not in template parameter scope!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 1598, __PRETTY_FUNCTION__))
;
1599
1600 // Construct the parameter object.
1601 bool IsParameterPack = EllipsisLoc.isValid();
1602 TemplateTemplateParmDecl *Param =
1603 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1604 NameLoc.isInvalid()? TmpLoc : NameLoc,
1605 Depth, Position, IsParameterPack,
1606 Name, Params);
1607 Param->setAccess(AS_public);
1608
1609 if (Param->isParameterPack())
1610 if (auto *LSI = getEnclosingLambda())
1611 LSI->LocalPacks.push_back(Param);
1612
1613 // If the template template parameter has a name, then link the identifier
1614 // into the scope and lookup mechanisms.
1615 if (Name) {
1616 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1617
1618 S->AddDecl(Param);
1619 IdResolver.AddDecl(Param);
1620 }
1621
1622 if (Params->size() == 0) {
1623 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1624 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1625 Param->setInvalidDecl();
1626 }
1627
1628 // C++0x [temp.param]p9:
1629 // A default template-argument may be specified for any kind of
1630 // template-parameter that is not a template parameter pack.
1631 if (IsParameterPack && !Default.isInvalid()) {
1632 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1633 Default = ParsedTemplateArgument();
1634 }
1635
1636 if (!Default.isInvalid()) {
1637 // Check only that we have a template template argument. We don't want to
1638 // try to check well-formedness now, because our template template parameter
1639 // might have dependent types in its template parameters, which we wouldn't
1640 // be able to match now.
1641 //
1642 // If none of the template template parameter's template arguments mention
1643 // other template parameters, we could actually perform more checking here.
1644 // However, it isn't worth doing.
1645 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1646 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1647 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1648 << DefaultArg.getSourceRange();
1649 return Param;
1650 }
1651
1652 // Check for unexpanded parameter packs.
1653 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
1654 DefaultArg.getArgument().getAsTemplate(),
1655 UPPC_DefaultArgument))
1656 return Param;
1657
1658 Param->setDefaultArgument(Context, DefaultArg);
1659 }
1660
1661 return Param;
1662}
1663
1664/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1665/// constrained by RequiresClause, that contains the template parameters in
1666/// Params.
1667TemplateParameterList *
1668Sema::ActOnTemplateParameterList(unsigned Depth,
1669 SourceLocation ExportLoc,
1670 SourceLocation TemplateLoc,
1671 SourceLocation LAngleLoc,
1672 ArrayRef<NamedDecl *> Params,
1673 SourceLocation RAngleLoc,
1674 Expr *RequiresClause) {
1675 if (ExportLoc.isValid())
1676 Diag(ExportLoc, diag::warn_template_export_unsupported);
1677
1678 return TemplateParameterList::Create(
1679 Context, TemplateLoc, LAngleLoc,
1680 llvm::makeArrayRef(Params.data(), Params.size()),
1681 RAngleLoc, RequiresClause);
1682}
1683
1684static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
1685 const CXXScopeSpec &SS) {
1686 if (SS.isSet())
1687 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1688}
1689
1690DeclResult Sema::CheckClassTemplate(
1691 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1692 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1693 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1694 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1695 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1696 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1697 assert(TemplateParams && TemplateParams->size() > 0 &&((TemplateParams && TemplateParams->size() > 0 &&
"No template parameters") ? static_cast<void> (0) : __assert_fail
("TemplateParams && TemplateParams->size() > 0 && \"No template parameters\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 1698, __PRETTY_FUNCTION__))
1698 "No template parameters")((TemplateParams && TemplateParams->size() > 0 &&
"No template parameters") ? static_cast<void> (0) : __assert_fail
("TemplateParams && TemplateParams->size() > 0 && \"No template parameters\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 1698, __PRETTY_FUNCTION__))
;
1699 assert(TUK != TUK_Reference && "Can only declare or define class templates")((TUK != TUK_Reference && "Can only declare or define class templates"
) ? static_cast<void> (0) : __assert_fail ("TUK != TUK_Reference && \"Can only declare or define class templates\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 1699, __PRETTY_FUNCTION__))
;
1700 bool Invalid = false;
1701
1702 // Check that we can declare a template here.
1703 if (CheckTemplateDeclScope(S, TemplateParams))
1704 return true;
1705
1706 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1707 assert(Kind != TTK_Enum && "can't build template of enumerated type")((Kind != TTK_Enum && "can't build template of enumerated type"
) ? static_cast<void> (0) : __assert_fail ("Kind != TTK_Enum && \"can't build template of enumerated type\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 1707, __PRETTY_FUNCTION__))
;
1708
1709 // There is no such thing as an unnamed class template.
1710 if (!Name) {
1711 Diag(KWLoc, diag::err_template_unnamed_class);
1712 return true;
1713 }
1714
1715 // Find any previous declaration with this name. For a friend with no
1716 // scope explicitly specified, we only look for tag declarations (per
1717 // C++11 [basic.lookup.elab]p2).
1718 DeclContext *SemanticContext;
1719 LookupResult Previous(*this, Name, NameLoc,
1720 (SS.isEmpty() && TUK == TUK_Friend)
1721 ? LookupTagName : LookupOrdinaryName,
1722 forRedeclarationInCurContext());
1723 if (SS.isNotEmpty() && !SS.isInvalid()) {
1724 SemanticContext = computeDeclContext(SS, true);
1725 if (!SemanticContext) {
1726 // FIXME: Horrible, horrible hack! We can't currently represent this
1727 // in the AST, and historically we have just ignored such friend
1728 // class templates, so don't complain here.
1729 Diag(NameLoc, TUK == TUK_Friend
1730 ? diag::warn_template_qualified_friend_ignored
1731 : diag::err_template_qualified_declarator_no_match)
1732 << SS.getScopeRep() << SS.getRange();
1733 return TUK != TUK_Friend;
1734 }
1735
1736 if (RequireCompleteDeclContext(SS, SemanticContext))
1737 return true;
1738
1739 // If we're adding a template to a dependent context, we may need to
1740 // rebuilding some of the types used within the template parameter list,
1741 // now that we know what the current instantiation is.
1742 if (SemanticContext->isDependentContext()) {
1743 ContextRAII SavedContext(*this, SemanticContext);
1744 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1745 Invalid = true;
1746 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1747 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc, false);
1748
1749 LookupQualifiedName(Previous, SemanticContext);
1750 } else {
1751 SemanticContext = CurContext;
1752
1753 // C++14 [class.mem]p14:
1754 // If T is the name of a class, then each of the following shall have a
1755 // name different from T:
1756 // -- every member template of class T
1757 if (TUK != TUK_Friend &&
1758 DiagnoseClassNameShadow(SemanticContext,
1759 DeclarationNameInfo(Name, NameLoc)))
1760 return true;
1761
1762 LookupName(Previous, S);
1763 }
1764
1765 if (Previous.isAmbiguous())
1766 return true;
1767
1768 NamedDecl *PrevDecl = nullptr;
1769 if (Previous.begin() != Previous.end())
1770 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1771
1772 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1773 // Maybe we will complain about the shadowed template parameter.
1774 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1775 // Just pretend that we didn't see the previous declaration.
1776 PrevDecl = nullptr;
1777 }
1778
1779 // If there is a previous declaration with the same name, check
1780 // whether this is a valid redeclaration.
1781 ClassTemplateDecl *PrevClassTemplate =
1782 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1783
1784 // We may have found the injected-class-name of a class template,
1785 // class template partial specialization, or class template specialization.
1786 // In these cases, grab the template that is being defined or specialized.
1787 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
1788 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1789 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1790 PrevClassTemplate
1791 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1792 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1793 PrevClassTemplate
1794 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1795 ->getSpecializedTemplate();
1796 }
1797 }
1798
1799 if (TUK == TUK_Friend) {
1800 // C++ [namespace.memdef]p3:
1801 // [...] When looking for a prior declaration of a class or a function
1802 // declared as a friend, and when the name of the friend class or
1803 // function is neither a qualified name nor a template-id, scopes outside
1804 // the innermost enclosing namespace scope are not considered.
1805 if (!SS.isSet()) {
1806 DeclContext *OutermostContext = CurContext;
1807 while (!OutermostContext->isFileContext())
1808 OutermostContext = OutermostContext->getLookupParent();
1809
1810 if (PrevDecl &&
1811 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1812 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1813 SemanticContext = PrevDecl->getDeclContext();
1814 } else {
1815 // Declarations in outer scopes don't matter. However, the outermost
1816 // context we computed is the semantic context for our new
1817 // declaration.
1818 PrevDecl = PrevClassTemplate = nullptr;
1819 SemanticContext = OutermostContext;
1820
1821 // Check that the chosen semantic context doesn't already contain a
1822 // declaration of this name as a non-tag type.
1823 Previous.clear(LookupOrdinaryName);
1824 DeclContext *LookupContext = SemanticContext;
1825 while (LookupContext->isTransparentContext())
1826 LookupContext = LookupContext->getLookupParent();
1827 LookupQualifiedName(Previous, LookupContext);
1828
1829 if (Previous.isAmbiguous())
1830 return true;
1831
1832 if (Previous.begin() != Previous.end())
1833 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1834 }
1835 }
1836 } else if (PrevDecl &&
1837 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1838 S, SS.isValid()))
1839 PrevDecl = PrevClassTemplate = nullptr;
1840
1841 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1842 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1843 if (SS.isEmpty() &&
1844 !(PrevClassTemplate &&
1845 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1846 SemanticContext->getRedeclContext()))) {
1847 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1848 Diag(Shadow->getTargetDecl()->getLocation(),
1849 diag::note_using_decl_target);
1850 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1851 // Recover by ignoring the old declaration.
1852 PrevDecl = PrevClassTemplate = nullptr;
1853 }
1854 }
1855
1856 if (PrevClassTemplate) {
1857 // Ensure that the template parameter lists are compatible. Skip this check
1858 // for a friend in a dependent context: the template parameter list itself
1859 // could be dependent.
1860 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1861 !TemplateParameterListsAreEqual(TemplateParams,
1862 PrevClassTemplate->getTemplateParameters(),
1863 /*Complain=*/true,
1864 TPL_TemplateMatch))
1865 return true;
1866
1867 // C++ [temp.class]p4:
1868 // In a redeclaration, partial specialization, explicit
1869 // specialization or explicit instantiation of a class template,
1870 // the class-key shall agree in kind with the original class
1871 // template declaration (7.1.5.3).
1872 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
1873 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
1874 TUK == TUK_Definition, KWLoc, Name)) {
1875 Diag(KWLoc, diag::err_use_with_wrong_tag)
1876 << Name
1877 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
1878 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
1879 Kind = PrevRecordDecl->getTagKind();
1880 }
1881
1882 // Check for redefinition of this class template.
1883 if (TUK == TUK_Definition) {
1884 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
1885 // If we have a prior definition that is not visible, treat this as
1886 // simply making that previous definition visible.
1887 NamedDecl *Hidden = nullptr;
1888 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
1889 SkipBody->ShouldSkip = true;
1890 SkipBody->Previous = Def;
1891 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1892 assert(Tmpl && "original definition of a class template is not a "((Tmpl && "original definition of a class template is not a "
"class template?") ? static_cast<void> (0) : __assert_fail
("Tmpl && \"original definition of a class template is not a \" \"class template?\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 1893, __PRETTY_FUNCTION__))
1893 "class template?")((Tmpl && "original definition of a class template is not a "
"class template?") ? static_cast<void> (0) : __assert_fail
("Tmpl && \"original definition of a class template is not a \" \"class template?\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 1893, __PRETTY_FUNCTION__))
;
1894 makeMergedDefinitionVisible(Hidden);
1895 makeMergedDefinitionVisible(Tmpl);
1896 } else {
1897 Diag(NameLoc, diag::err_redefinition) << Name;
1898 Diag(Def->getLocation(), diag::note_previous_definition);
1899 // FIXME: Would it make sense to try to "forget" the previous
1900 // definition, as part of error recovery?
1901 return true;
1902 }
1903 }
1904 }
1905 } else if (PrevDecl) {
1906 // C++ [temp]p5:
1907 // A class template shall not have the same name as any other
1908 // template, class, function, object, enumeration, enumerator,
1909 // namespace, or type in the same scope (3.3), except as specified
1910 // in (14.5.4).
1911 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1912 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1913 return true;
1914 }
1915
1916 // Check the template parameter list of this declaration, possibly
1917 // merging in the template parameter list from the previous class
1918 // template declaration. Skip this check for a friend in a dependent
1919 // context, because the template parameter list might be dependent.
1920 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1921 CheckTemplateParameterList(
1922 TemplateParams,
1923 PrevClassTemplate
1924 ? PrevClassTemplate->getMostRecentDecl()->getTemplateParameters()
1925 : nullptr,
1926 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1927 SemanticContext->isDependentContext())
1928 ? TPC_ClassTemplateMember
1929 : TUK == TUK_Friend ? TPC_FriendClassTemplate : TPC_ClassTemplate,
1930 SkipBody))
1931 Invalid = true;
1932
1933 if (SS.isSet()) {
1934 // If the name of the template was qualified, we must be defining the
1935 // template out-of-line.
1936 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1937 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1938 : diag::err_member_decl_does_not_match)
1939 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
1940 Invalid = true;
1941 }
1942 }
1943
1944 // If this is a templated friend in a dependent context we should not put it
1945 // on the redecl chain. In some cases, the templated friend can be the most
1946 // recent declaration tricking the template instantiator to make substitutions
1947 // there.
1948 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1949 bool ShouldAddRedecl
1950 = !(TUK == TUK_Friend && CurContext->isDependentContext());
1951
1952 CXXRecordDecl *NewClass =
1953 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1954 PrevClassTemplate && ShouldAddRedecl ?
1955 PrevClassTemplate->getTemplatedDecl() : nullptr,
1956 /*DelayTypeCreation=*/true);
1957 SetNestedNameSpecifier(*this, NewClass, SS);
1958 if (NumOuterTemplateParamLists > 0)
1959 NewClass->setTemplateParameterListsInfo(
1960 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1961 NumOuterTemplateParamLists));
1962
1963 // Add alignment attributes if necessary; these attributes are checked when
1964 // the ASTContext lays out the structure.
1965 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
1966 AddAlignmentAttributesForRecord(NewClass);
1967 AddMsStructLayoutForRecord(NewClass);
1968 }
1969
1970 ClassTemplateDecl *NewTemplate
1971 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1972 DeclarationName(Name), TemplateParams,
1973 NewClass);
1974
1975 if (ShouldAddRedecl)
1976 NewTemplate->setPreviousDecl(PrevClassTemplate);
1977
1978 NewClass->setDescribedClassTemplate(NewTemplate);
1979
1980 if (ModulePrivateLoc.isValid())
1981 NewTemplate->setModulePrivate();
1982
1983 // Build the type for the class template declaration now.
1984 QualType T = NewTemplate->getInjectedClassNameSpecialization();
1985 T = Context.getInjectedClassNameType(NewClass, T);
1986 assert(T->isDependentType() && "Class template type is not dependent?")((T->isDependentType() && "Class template type is not dependent?"
) ? static_cast<void> (0) : __assert_fail ("T->isDependentType() && \"Class template type is not dependent?\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 1986, __PRETTY_FUNCTION__))
;
1987 (void)T;
1988
1989 // If we are providing an explicit specialization of a member that is a
1990 // class template, make a note of that.
1991 if (PrevClassTemplate &&
1992 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1993 PrevClassTemplate->setMemberSpecialization();
1994
1995 // Set the access specifier.
1996 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
1997 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
1998
1999 // Set the lexical context of these templates
2000 NewClass->setLexicalDeclContext(CurContext);
2001 NewTemplate->setLexicalDeclContext(CurContext);
2002
2003 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
2004 NewClass->startDefinition();
2005
2006 ProcessDeclAttributeList(S, NewClass, Attr);
2007
2008 if (PrevClassTemplate)
2009 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2010
2011 AddPushedVisibilityAttribute(NewClass);
2012 inferGslOwnerPointerAttribute(NewClass);
2013
2014 if (TUK != TUK_Friend) {
2015 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2016 Scope *Outer = S;
2017 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2018 Outer = Outer->getParent();
2019 PushOnScopeChains(NewTemplate, Outer);
2020 } else {
2021 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2022 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2023 NewClass->setAccess(PrevClassTemplate->getAccess());
2024 }
2025
2026 NewTemplate->setObjectOfFriendDecl();
2027
2028 // Friend templates are visible in fairly strange ways.
2029 if (!CurContext->isDependentContext()) {
2030 DeclContext *DC = SemanticContext->getRedeclContext();
2031 DC->makeDeclVisibleInContext(NewTemplate);
2032 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2033 PushOnScopeChains(NewTemplate, EnclosingScope,
2034 /* AddToContext = */ false);
2035 }
2036
2037 FriendDecl *Friend = FriendDecl::Create(
2038 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2039 Friend->setAccess(AS_public);
2040 CurContext->addDecl(Friend);
2041 }
2042
2043 if (PrevClassTemplate)
2044 CheckRedeclarationModuleOwnership(NewTemplate, PrevClassTemplate);
2045
2046 if (Invalid) {
2047 NewTemplate->setInvalidDecl();
2048 NewClass->setInvalidDecl();
2049 }
2050
2051 ActOnDocumentableDecl(NewTemplate);
2052
2053 if (SkipBody && SkipBody->ShouldSkip)
2054 return SkipBody->Previous;
2055
2056 return NewTemplate;
2057}
2058
2059namespace {
2060/// Tree transform to "extract" a transformed type from a class template's
2061/// constructor to a deduction guide.
2062class ExtractTypeForDeductionGuide
2063 : public TreeTransform<ExtractTypeForDeductionGuide> {
2064 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs;
2065
2066public:
2067 typedef TreeTransform<ExtractTypeForDeductionGuide> Base;
2068 ExtractTypeForDeductionGuide(
2069 Sema &SemaRef,
2070 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs)
2071 : Base(SemaRef), MaterializedTypedefs(MaterializedTypedefs) {}
2072
2073 TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); }
2074
2075 QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) {
2076 ASTContext &Context = SemaRef.getASTContext();
2077 TypedefNameDecl *OrigDecl = TL.getTypedefNameDecl();
2078 TypeLocBuilder InnerTLB;
2079 QualType Transformed =
2080 TransformType(InnerTLB, OrigDecl->getTypeSourceInfo()->getTypeLoc());
2081 TypeSourceInfo *TSI =
2082 TransformType(InnerTLB.getTypeSourceInfo(Context, Transformed));
2083
2084 TypedefNameDecl *Decl = nullptr;
2085
2086 if (isa<TypeAliasDecl>(OrigDecl))
2087 Decl = TypeAliasDecl::Create(
2088 Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
2089 OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
2090 else {
2091 assert(isa<TypedefDecl>(OrigDecl) && "Not a Type alias or typedef")((isa<TypedefDecl>(OrigDecl) && "Not a Type alias or typedef"
) ? static_cast<void> (0) : __assert_fail ("isa<TypedefDecl>(OrigDecl) && \"Not a Type alias or typedef\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 2091, __PRETTY_FUNCTION__))
;
2092 Decl = TypedefDecl::Create(
2093 Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
2094 OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
2095 }
2096
2097 MaterializedTypedefs.push_back(Decl);
2098
2099 QualType TDTy = Context.getTypedefType(Decl);
2100 TypedefTypeLoc TypedefTL = TLB.push<TypedefTypeLoc>(TDTy);
2101 TypedefTL.setNameLoc(TL.getNameLoc());
2102
2103 return TDTy;
2104 }
2105};
2106
2107/// Transform to convert portions of a constructor declaration into the
2108/// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
2109struct ConvertConstructorToDeductionGuideTransform {
2110 ConvertConstructorToDeductionGuideTransform(Sema &S,
2111 ClassTemplateDecl *Template)
2112 : SemaRef(S), Template(Template) {}
2113
2114 Sema &SemaRef;
2115 ClassTemplateDecl *Template;
2116
2117 DeclContext *DC = Template->getDeclContext();
2118 CXXRecordDecl *Primary = Template->getTemplatedDecl();
2119 DeclarationName DeductionGuideName =
2120 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
2121
2122 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
2123
2124 // Index adjustment to apply to convert depth-1 template parameters into
2125 // depth-0 template parameters.
2126 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
2127
2128 /// Transform a constructor declaration into a deduction guide.
2129 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
2130 CXXConstructorDecl *CD) {
2131 SmallVector<TemplateArgument, 16> SubstArgs;
2132
2133 LocalInstantiationScope Scope(SemaRef);
2134
2135 // C++ [over.match.class.deduct]p1:
2136 // -- For each constructor of the class template designated by the
2137 // template-name, a function template with the following properties:
2138
2139 // -- The template parameters are the template parameters of the class
2140 // template followed by the template parameters (including default
2141 // template arguments) of the constructor, if any.
2142 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2143 if (FTD) {
2144 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
2145 SmallVector<NamedDecl *, 16> AllParams;
2146 AllParams.reserve(TemplateParams->size() + InnerParams->size());
2147 AllParams.insert(AllParams.begin(),
2148 TemplateParams->begin(), TemplateParams->end());
2149 SubstArgs.reserve(InnerParams->size());
2150
2151 // Later template parameters could refer to earlier ones, so build up
2152 // a list of substituted template arguments as we go.
2153 for (NamedDecl *Param : *InnerParams) {
2154 MultiLevelTemplateArgumentList Args;
2155 Args.setKind(TemplateSubstitutionKind::Rewrite);
2156 Args.addOuterTemplateArguments(SubstArgs);
2157 Args.addOuterRetainedLevel();
2158 NamedDecl *NewParam = transformTemplateParameter(Param, Args);
2159 if (!NewParam)
2160 return nullptr;
2161 AllParams.push_back(NewParam);
2162 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
2163 SemaRef.Context.getInjectedTemplateArg(NewParam)));
2164 }
2165 TemplateParams = TemplateParameterList::Create(
2166 SemaRef.Context, InnerParams->getTemplateLoc(),
2167 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
2168 /*FIXME: RequiresClause*/ nullptr);
2169 }
2170
2171 // If we built a new template-parameter-list, track that we need to
2172 // substitute references to the old parameters into references to the
2173 // new ones.
2174 MultiLevelTemplateArgumentList Args;
2175 Args.setKind(TemplateSubstitutionKind::Rewrite);
2176 if (FTD) {
2177 Args.addOuterTemplateArguments(SubstArgs);
2178 Args.addOuterRetainedLevel();
2179 }
2180
2181 FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
2182 .getAsAdjusted<FunctionProtoTypeLoc>();
2183 assert(FPTL && "no prototype for constructor declaration")((FPTL && "no prototype for constructor declaration")
? static_cast<void> (0) : __assert_fail ("FPTL && \"no prototype for constructor declaration\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 2183, __PRETTY_FUNCTION__))
;
2184
2185 // Transform the type of the function, adjusting the return type and
2186 // replacing references to the old parameters with references to the
2187 // new ones.
2188 TypeLocBuilder TLB;
2189 SmallVector<ParmVarDecl*, 8> Params;
2190 SmallVector<TypedefNameDecl *, 4> MaterializedTypedefs;
2191 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args,
2192 MaterializedTypedefs);
2193 if (NewType.isNull())
2194 return nullptr;
2195 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
2196
2197 return buildDeductionGuide(TemplateParams, CD->getExplicitSpecifier(),
2198 NewTInfo, CD->getBeginLoc(), CD->getLocation(),
2199 CD->getEndLoc(), MaterializedTypedefs);
2200 }
2201
2202 /// Build a deduction guide with the specified parameter types.
2203 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
2204 SourceLocation Loc = Template->getLocation();
2205
2206 // Build the requested type.
2207 FunctionProtoType::ExtProtoInfo EPI;
2208 EPI.HasTrailingReturn = true;
2209 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
2210 DeductionGuideName, EPI);
2211 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
2212
2213 FunctionProtoTypeLoc FPTL =
2214 TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
2215
2216 // Build the parameters, needed during deduction / substitution.
2217 SmallVector<ParmVarDecl*, 4> Params;
2218 for (auto T : ParamTypes) {
2219 ParmVarDecl *NewParam = ParmVarDecl::Create(
2220 SemaRef.Context, DC, Loc, Loc, nullptr, T,
2221 SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
2222 NewParam->setScopeInfo(0, Params.size());
2223 FPTL.setParam(Params.size(), NewParam);
2224 Params.push_back(NewParam);
2225 }
2226
2227 return buildDeductionGuide(Template->getTemplateParameters(),
2228 ExplicitSpecifier(), TSI, Loc, Loc, Loc);
2229 }
2230
2231private:
2232 /// Transform a constructor template parameter into a deduction guide template
2233 /// parameter, rebuilding any internal references to earlier parameters and
2234 /// renumbering as we go.
2235 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
2236 MultiLevelTemplateArgumentList &Args) {
2237 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
2238 // TemplateTypeParmDecl's index cannot be changed after creation, so
2239 // substitute it directly.
2240 auto *NewTTP = TemplateTypeParmDecl::Create(
2241 SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(),
2242 /*Depth*/ 0, Depth1IndexAdjustment + TTP->getIndex(),
2243 TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
2244 TTP->isParameterPack(), TTP->hasTypeConstraint(),
2245 TTP->isExpandedParameterPack() ?
2246 llvm::Optional<unsigned>(TTP->getNumExpansionParameters()) : None);
2247 if (const auto *TC = TTP->getTypeConstraint()) {
2248 TemplateArgumentListInfo TransformedArgs;
2249 const auto *ArgsAsWritten = TC->getTemplateArgsAsWritten();
2250 if (!ArgsAsWritten ||
2251 SemaRef.Subst(ArgsAsWritten->getTemplateArgs(),
2252 ArgsAsWritten->NumTemplateArgs, TransformedArgs,
2253 Args))
2254 SemaRef.AttachTypeConstraint(
2255 TC->getNestedNameSpecifierLoc(), TC->getConceptNameInfo(),
2256 TC->getNamedConcept(), ArgsAsWritten ? &TransformedArgs : nullptr,
2257 NewTTP,
2258 NewTTP->isParameterPack()
2259 ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2260 ->getEllipsisLoc()
2261 : SourceLocation());
2262 }
2263 if (TTP->hasDefaultArgument()) {
2264 TypeSourceInfo *InstantiatedDefaultArg =
2265 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
2266 TTP->getDefaultArgumentLoc(), TTP->getDeclName());
2267 if (InstantiatedDefaultArg)
2268 NewTTP->setDefaultArgument(InstantiatedDefaultArg);
2269 }
2270 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
2271 NewTTP);
2272 return NewTTP;
2273 }
2274
2275 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
2276 return transformTemplateParameterImpl(TTP, Args);
2277
2278 return transformTemplateParameterImpl(
2279 cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
2280 }
2281 template<typename TemplateParmDecl>
2282 TemplateParmDecl *
2283 transformTemplateParameterImpl(TemplateParmDecl *OldParam,
2284 MultiLevelTemplateArgumentList &Args) {
2285 // Ask the template instantiator to do the heavy lifting for us, then adjust
2286 // the index of the parameter once it's done.
2287 auto *NewParam =
2288 cast<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
2289 assert(NewParam->getDepth() == 0 && "unexpected template param depth")((NewParam->getDepth() == 0 && "unexpected template param depth"
) ? static_cast<void> (0) : __assert_fail ("NewParam->getDepth() == 0 && \"unexpected template param depth\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 2289, __PRETTY_FUNCTION__))
;
2290 NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
2291 return NewParam;
2292 }
2293
2294 QualType transformFunctionProtoType(
2295 TypeLocBuilder &TLB, FunctionProtoTypeLoc TL,
2296 SmallVectorImpl<ParmVarDecl *> &Params,
2297 MultiLevelTemplateArgumentList &Args,
2298 SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) {
2299 SmallVector<QualType, 4> ParamTypes;
2300 const FunctionProtoType *T = TL.getTypePtr();
2301
2302 // -- The types of the function parameters are those of the constructor.
2303 for (auto *OldParam : TL.getParams()) {
2304 ParmVarDecl *NewParam =
2305 transformFunctionTypeParam(OldParam, Args, MaterializedTypedefs);
2306 if (!NewParam)
2307 return QualType();
2308 ParamTypes.push_back(NewParam->getType());
2309 Params.push_back(NewParam);
2310 }
2311
2312 // -- The return type is the class template specialization designated by
2313 // the template-name and template arguments corresponding to the
2314 // template parameters obtained from the class template.
2315 //
2316 // We use the injected-class-name type of the primary template instead.
2317 // This has the convenient property that it is different from any type that
2318 // the user can write in a deduction-guide (because they cannot enter the
2319 // context of the template), so implicit deduction guides can never collide
2320 // with explicit ones.
2321 QualType ReturnType = DeducedType;
2322 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
2323
2324 // Resolving a wording defect, we also inherit the variadicness of the
2325 // constructor.
2326 FunctionProtoType::ExtProtoInfo EPI;
2327 EPI.Variadic = T->isVariadic();
2328 EPI.HasTrailingReturn = true;
2329
2330 QualType Result = SemaRef.BuildFunctionType(
2331 ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI);
2332 if (Result.isNull())
2333 return QualType();
2334
2335 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
2336 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
2337 NewTL.setLParenLoc(TL.getLParenLoc());
2338 NewTL.setRParenLoc(TL.getRParenLoc());
2339 NewTL.setExceptionSpecRange(SourceRange());
2340 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
2341 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
2342 NewTL.setParam(I, Params[I]);
2343
2344 return Result;
2345 }
2346
2347 ParmVarDecl *transformFunctionTypeParam(
2348 ParmVarDecl *OldParam, MultiLevelTemplateArgumentList &Args,
2349 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) {
2350 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
2351 TypeSourceInfo *NewDI;
2352 if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
2353 // Expand out the one and only element in each inner pack.
2354 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
2355 NewDI =
2356 SemaRef.SubstType(PackTL.getPatternLoc(), Args,
2357 OldParam->getLocation(), OldParam->getDeclName());
2358 if (!NewDI) return nullptr;
2359 NewDI =
2360 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
2361 PackTL.getTypePtr()->getNumExpansions());
2362 } else
2363 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
2364 OldParam->getDeclName());
2365 if (!NewDI)
2366 return nullptr;
2367
2368 // Extract the type. This (for instance) replaces references to typedef
2369 // members of the current instantiations with the definitions of those
2370 // typedefs, avoiding triggering instantiation of the deduced type during
2371 // deduction.
2372 NewDI = ExtractTypeForDeductionGuide(SemaRef, MaterializedTypedefs)
2373 .transform(NewDI);
2374
2375 // Resolving a wording defect, we also inherit default arguments from the
2376 // constructor.
2377 ExprResult NewDefArg;
2378 if (OldParam->hasDefaultArg()) {
2379 // We don't care what the value is (we won't use it); just create a
2380 // placeholder to indicate there is a default argument.
2381 QualType ParamTy = NewDI->getType();
2382 NewDefArg = new (SemaRef.Context)
2383 OpaqueValueExpr(OldParam->getDefaultArg()->getBeginLoc(),
2384 ParamTy.getNonLValueExprType(SemaRef.Context),
2385 ParamTy->isLValueReferenceType() ? VK_LValue :
2386 ParamTy->isRValueReferenceType() ? VK_XValue :
2387 VK_RValue);
2388 }
2389
2390 ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
2391 OldParam->getInnerLocStart(),
2392 OldParam->getLocation(),
2393 OldParam->getIdentifier(),
2394 NewDI->getType(),
2395 NewDI,
2396 OldParam->getStorageClass(),
2397 NewDefArg.get());
2398 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
2399 OldParam->getFunctionScopeIndex());
2400 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);
2401 return NewParam;
2402 }
2403
2404 FunctionTemplateDecl *buildDeductionGuide(
2405 TemplateParameterList *TemplateParams, ExplicitSpecifier ES,
2406 TypeSourceInfo *TInfo, SourceLocation LocStart, SourceLocation Loc,
2407 SourceLocation LocEnd,
2408 llvm::ArrayRef<TypedefNameDecl *> MaterializedTypedefs = {}) {
2409 DeclarationNameInfo Name(DeductionGuideName, Loc);
2410 ArrayRef<ParmVarDecl *> Params =
2411 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
2412
2413 // Build the implicit deduction guide template.
2414 auto *Guide =
2415 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, ES, Name,
2416 TInfo->getType(), TInfo, LocEnd);
2417 Guide->setImplicit();
2418 Guide->setParams(Params);
2419
2420 for (auto *Param : Params)
2421 Param->setDeclContext(Guide);
2422 for (auto *TD : MaterializedTypedefs)
2423 TD->setDeclContext(Guide);
2424
2425 auto *GuideTemplate = FunctionTemplateDecl::Create(
2426 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
2427 GuideTemplate->setImplicit();
2428 Guide->setDescribedFunctionTemplate(GuideTemplate);
2429
2430 if (isa<CXXRecordDecl>(DC)) {
2431 Guide->setAccess(AS_public);
2432 GuideTemplate->setAccess(AS_public);
2433 }
2434
2435 DC->addDecl(GuideTemplate);
2436 return GuideTemplate;
2437 }
2438};
2439}
2440
2441void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
2442 SourceLocation Loc) {
2443 if (CXXRecordDecl *DefRecord =
2444 cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
2445 TemplateDecl *DescribedTemplate = DefRecord->getDescribedClassTemplate();
2446 Template = DescribedTemplate ? DescribedTemplate : Template;
2447 }
2448
2449 DeclContext *DC = Template->getDeclContext();
2450 if (DC->isDependentContext())
2451 return;
2452
2453 ConvertConstructorToDeductionGuideTransform Transform(
2454 *this, cast<ClassTemplateDecl>(Template));
2455 if (!isCompleteType(Loc, Transform.DeducedType))
2456 return;
2457
2458 // Check whether we've already declared deduction guides for this template.
2459 // FIXME: Consider storing a flag on the template to indicate this.
2460 auto Existing = DC->lookup(Transform.DeductionGuideName);
2461 for (auto *D : Existing)
2462 if (D->isImplicit())
2463 return;
2464
2465 // In case we were expanding a pack when we attempted to declare deduction
2466 // guides, turn off pack expansion for everything we're about to do.
2467 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2468 // Create a template instantiation record to track the "instantiation" of
2469 // constructors into deduction guides.
2470 // FIXME: Add a kind for this to give more meaningful diagnostics. But can
2471 // this substitution process actually fail?
2472 InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
2473 if (BuildingDeductionGuides.isInvalid())
2474 return;
2475
2476 // Convert declared constructors into deduction guide templates.
2477 // FIXME: Skip constructors for which deduction must necessarily fail (those
2478 // for which some class template parameter without a default argument never
2479 // appears in a deduced context).
2480 bool AddedAny = false;
2481 for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
2482 D = D->getUnderlyingDecl();
2483 if (D->isInvalidDecl() || D->isImplicit())
2484 continue;
2485 D = cast<NamedDecl>(D->getCanonicalDecl());
2486
2487 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
2488 auto *CD =
2489 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
2490 // Class-scope explicit specializations (MS extension) do not result in
2491 // deduction guides.
2492 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
2493 continue;
2494
2495 Transform.transformConstructor(FTD, CD);
2496 AddedAny = true;
2497 }
2498
2499 // C++17 [over.match.class.deduct]
2500 // -- If C is not defined or does not declare any constructors, an
2501 // additional function template derived as above from a hypothetical
2502 // constructor C().
2503 if (!AddedAny)
2504 Transform.buildSimpleDeductionGuide(None);
2505
2506 // -- An additional function template derived as above from a hypothetical
2507 // constructor C(C), called the copy deduction candidate.
2508 cast<CXXDeductionGuideDecl>(
2509 cast<FunctionTemplateDecl>(
2510 Transform.buildSimpleDeductionGuide(Transform.DeducedType))
2511 ->getTemplatedDecl())
2512 ->setIsCopyDeductionCandidate();
2513}
2514
2515/// Diagnose the presence of a default template argument on a
2516/// template parameter, which is ill-formed in certain contexts.
2517///
2518/// \returns true if the default template argument should be dropped.
2519static bool DiagnoseDefaultTemplateArgument(Sema &S,
2520 Sema::TemplateParamListContext TPC,
2521 SourceLocation ParamLoc,
2522 SourceRange DefArgRange) {
2523 switch (TPC) {
2524 case Sema::TPC_ClassTemplate:
2525 case Sema::TPC_VarTemplate:
2526 case Sema::TPC_TypeAliasTemplate:
2527 return false;
2528
2529 case Sema::TPC_FunctionTemplate:
2530 case Sema::TPC_FriendFunctionTemplateDefinition:
2531 // C++ [temp.param]p9:
2532 // A default template-argument shall not be specified in a
2533 // function template declaration or a function template
2534 // definition [...]
2535 // If a friend function template declaration specifies a default
2536 // template-argument, that declaration shall be a definition and shall be
2537 // the only declaration of the function template in the translation unit.
2538 // (C++98/03 doesn't have this wording; see DR226).
2539 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
2540 diag::warn_cxx98_compat_template_parameter_default_in_function_template
2541 : diag::ext_template_parameter_default_in_function_template)
2542 << DefArgRange;
2543 return false;
2544
2545 case Sema::TPC_ClassTemplateMember:
2546 // C++0x [temp.param]p9:
2547 // A default template-argument shall not be specified in the
2548 // template-parameter-lists of the definition of a member of a
2549 // class template that appears outside of the member's class.
2550 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2551 << DefArgRange;
2552 return true;
2553
2554 case Sema::TPC_FriendClassTemplate:
2555 case Sema::TPC_FriendFunctionTemplate:
2556 // C++ [temp.param]p9:
2557 // A default template-argument shall not be specified in a
2558 // friend template declaration.
2559 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2560 << DefArgRange;
2561 return true;
2562
2563 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2564 // for friend function templates if there is only a single
2565 // declaration (and it is a definition). Strange!
2566 }
2567
2568 llvm_unreachable("Invalid TemplateParamListContext!")::llvm::llvm_unreachable_internal("Invalid TemplateParamListContext!"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 2568)
;
2569}
2570
2571/// Check for unexpanded parameter packs within the template parameters
2572/// of a template template parameter, recursively.
2573static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2574 TemplateTemplateParmDecl *TTP) {
2575 // A template template parameter which is a parameter pack is also a pack
2576 // expansion.
2577 if (TTP->isParameterPack())
2578 return false;
2579
2580 TemplateParameterList *Params = TTP->getTemplateParameters();
2581 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2582 NamedDecl *P = Params->getParam(I);
2583 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2584 if (!TTP->isParameterPack())
2585 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2586 if (TC->hasExplicitTemplateArgs())
2587 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2588 if (S.DiagnoseUnexpandedParameterPack(ArgLoc,
2589 Sema::UPPC_TypeConstraint))
2590 return true;
2591 continue;
2592 }
2593
2594 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2595 if (!NTTP->isParameterPack() &&
2596 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2597 NTTP->getTypeSourceInfo(),
2598 Sema::UPPC_NonTypeTemplateParameterType))
2599 return true;
2600
2601 continue;
2602 }
2603
2604 if (TemplateTemplateParmDecl *InnerTTP
2605 = dyn_cast<TemplateTemplateParmDecl>(P))
2606 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2607 return true;
2608 }
2609
2610 return false;
2611}
2612
2613/// Checks the validity of a template parameter list, possibly
2614/// considering the template parameter list from a previous
2615/// declaration.
2616///
2617/// If an "old" template parameter list is provided, it must be
2618/// equivalent (per TemplateParameterListsAreEqual) to the "new"
2619/// template parameter list.
2620///
2621/// \param NewParams Template parameter list for a new template
2622/// declaration. This template parameter list will be updated with any
2623/// default arguments that are carried through from the previous
2624/// template parameter list.
2625///
2626/// \param OldParams If provided, template parameter list from a
2627/// previous declaration of the same template. Default template
2628/// arguments will be merged from the old template parameter list to
2629/// the new template parameter list.
2630///
2631/// \param TPC Describes the context in which we are checking the given
2632/// template parameter list.
2633///
2634/// \param SkipBody If we might have already made a prior merged definition
2635/// of this template visible, the corresponding body-skipping information.
2636/// Default argument redefinition is not an error when skipping such a body,
2637/// because (under the ODR) we can assume the default arguments are the same
2638/// as the prior merged definition.
2639///
2640/// \returns true if an error occurred, false otherwise.
2641bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
2642 TemplateParameterList *OldParams,
2643 TemplateParamListContext TPC,
2644 SkipBodyInfo *SkipBody) {
2645 bool Invalid = false;
2646
2647 // C++ [temp.param]p10:
2648 // The set of default template-arguments available for use with a
2649 // template declaration or definition is obtained by merging the
2650 // default arguments from the definition (if in scope) and all
2651 // declarations in scope in the same way default function
2652 // arguments are (8.3.6).
2653 bool SawDefaultArgument = false;
2654 SourceLocation PreviousDefaultArgLoc;
2655
2656 // Dummy initialization to avoid warnings.
2657 TemplateParameterList::iterator OldParam = NewParams->end();
2658 if (OldParams)
2659 OldParam = OldParams->begin();
2660
2661 bool RemoveDefaultArguments = false;
2662 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2663 NewParamEnd = NewParams->end();
2664 NewParam != NewParamEnd; ++NewParam) {
2665 // Variables used to diagnose redundant default arguments
2666 bool RedundantDefaultArg = false;
2667 SourceLocation OldDefaultLoc;
2668 SourceLocation NewDefaultLoc;
2669
2670 // Variable used to diagnose missing default arguments
2671 bool MissingDefaultArg = false;
2672
2673 // Variable used to diagnose non-final parameter packs
2674 bool SawParameterPack = false;
2675
2676 if (TemplateTypeParmDecl *NewTypeParm
2677 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2678 // Check the presence of a default argument here.
2679 if (NewTypeParm->hasDefaultArgument() &&
2680 DiagnoseDefaultTemplateArgument(*this, TPC,
2681 NewTypeParm->getLocation(),
2682 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
2683 .getSourceRange()))
2684 NewTypeParm->removeDefaultArgument();
2685
2686 // Merge default arguments for template type parameters.
2687 TemplateTypeParmDecl *OldTypeParm
2688 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2689 if (NewTypeParm->isParameterPack()) {
2690 assert(!NewTypeParm->hasDefaultArgument() &&((!NewTypeParm->hasDefaultArgument() && "Parameter packs can't have a default argument!"
) ? static_cast<void> (0) : __assert_fail ("!NewTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 2691, __PRETTY_FUNCTION__))
2691 "Parameter packs can't have a default argument!")((!NewTypeParm->hasDefaultArgument() && "Parameter packs can't have a default argument!"
) ? static_cast<void> (0) : __assert_fail ("!NewTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 2691, __PRETTY_FUNCTION__))
;
2692 SawParameterPack = true;
2693 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2694 NewTypeParm->hasDefaultArgument() &&
2695 (!SkipBody || !SkipBody->ShouldSkip)) {
2696 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2697 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2698 SawDefaultArgument = true;
2699 RedundantDefaultArg = true;
2700 PreviousDefaultArgLoc = NewDefaultLoc;
2701 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2702 // Merge the default argument from the old declaration to the
2703 // new declaration.
2704 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2705 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2706 } else if (NewTypeParm->hasDefaultArgument()) {
2707 SawDefaultArgument = true;
2708 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2709 } else if (SawDefaultArgument)
2710 MissingDefaultArg = true;
2711 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2712 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2713 // Check for unexpanded parameter packs.
2714 if (!NewNonTypeParm->isParameterPack() &&
2715 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2716 NewNonTypeParm->getTypeSourceInfo(),
2717 UPPC_NonTypeTemplateParameterType)) {
2718 Invalid = true;
2719 continue;
2720 }
2721
2722 // Check the presence of a default argument here.
2723 if (NewNonTypeParm->hasDefaultArgument() &&
2724 DiagnoseDefaultTemplateArgument(*this, TPC,
2725 NewNonTypeParm->getLocation(),
2726 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
2727 NewNonTypeParm->removeDefaultArgument();
2728 }
2729
2730 // Merge default arguments for non-type template parameters
2731 NonTypeTemplateParmDecl *OldNonTypeParm
2732 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2733 if (NewNonTypeParm->isParameterPack()) {
2734 assert(!NewNonTypeParm->hasDefaultArgument() &&((!NewNonTypeParm->hasDefaultArgument() && "Parameter packs can't have a default argument!"
) ? static_cast<void> (0) : __assert_fail ("!NewNonTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 2735, __PRETTY_FUNCTION__))
2735 "Parameter packs can't have a default argument!")((!NewNonTypeParm->hasDefaultArgument() && "Parameter packs can't have a default argument!"
) ? static_cast<void> (0) : __assert_fail ("!NewNonTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 2735, __PRETTY_FUNCTION__))
;
2736 if (!NewNonTypeParm->isPackExpansion())
2737 SawParameterPack = true;
2738 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2739 NewNonTypeParm->hasDefaultArgument() &&
2740 (!SkipBody || !SkipBody->ShouldSkip)) {
2741 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2742 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2743 SawDefaultArgument = true;
2744 RedundantDefaultArg = true;
2745 PreviousDefaultArgLoc = NewDefaultLoc;
2746 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2747 // Merge the default argument from the old declaration to the
2748 // new declaration.
2749 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2750 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2751 } else if (NewNonTypeParm->hasDefaultArgument()) {
2752 SawDefaultArgument = true;
2753 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2754 } else if (SawDefaultArgument)
2755 MissingDefaultArg = true;
2756 } else {
2757 TemplateTemplateParmDecl *NewTemplateParm
2758 = cast<TemplateTemplateParmDecl>(*NewParam);
2759
2760 // Check for unexpanded parameter packs, recursively.
2761 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2762 Invalid = true;
2763 continue;
2764 }
2765
2766 // Check the presence of a default argument here.
2767 if (NewTemplateParm->hasDefaultArgument() &&
2768 DiagnoseDefaultTemplateArgument(*this, TPC,
2769 NewTemplateParm->getLocation(),
2770 NewTemplateParm->getDefaultArgument().getSourceRange()))
2771 NewTemplateParm->removeDefaultArgument();
2772
2773 // Merge default arguments for template template parameters
2774 TemplateTemplateParmDecl *OldTemplateParm
2775 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2776 if (NewTemplateParm->isParameterPack()) {
2777 assert(!NewTemplateParm->hasDefaultArgument() &&((!NewTemplateParm->hasDefaultArgument() && "Parameter packs can't have a default argument!"
) ? static_cast<void> (0) : __assert_fail ("!NewTemplateParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 2778, __PRETTY_FUNCTION__))
2778 "Parameter packs can't have a default argument!")((!NewTemplateParm->hasDefaultArgument() && "Parameter packs can't have a default argument!"
) ? static_cast<void> (0) : __assert_fail ("!NewTemplateParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 2778, __PRETTY_FUNCTION__))
;
2779 if (!NewTemplateParm->isPackExpansion())
2780 SawParameterPack = true;
2781 } else if (OldTemplateParm &&
2782 hasVisibleDefaultArgument(OldTemplateParm) &&
2783 NewTemplateParm->hasDefaultArgument() &&
2784 (!SkipBody || !SkipBody->ShouldSkip)) {
2785 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2786 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2787 SawDefaultArgument = true;
2788 RedundantDefaultArg = true;
2789 PreviousDefaultArgLoc = NewDefaultLoc;
2790 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2791 // Merge the default argument from the old declaration to the
2792 // new declaration.
2793 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2794 PreviousDefaultArgLoc
2795 = OldTemplateParm->getDefaultArgument().getLocation();
2796 } else if (NewTemplateParm->hasDefaultArgument()) {
2797 SawDefaultArgument = true;
2798 PreviousDefaultArgLoc
2799 = NewTemplateParm->getDefaultArgument().getLocation();
2800 } else if (SawDefaultArgument)
2801 MissingDefaultArg = true;
2802 }
2803
2804 // C++11 [temp.param]p11:
2805 // If a template parameter of a primary class template or alias template
2806 // is a template parameter pack, it shall be the last template parameter.
2807 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2808 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2809 TPC == TPC_TypeAliasTemplate)) {
2810 Diag((*NewParam)->getLocation(),
2811 diag::err_template_param_pack_must_be_last_template_parameter);
2812 Invalid = true;
2813 }
2814
2815 if (RedundantDefaultArg) {
2816 // C++ [temp.param]p12:
2817 // A template-parameter shall not be given default arguments
2818 // by two different declarations in the same scope.
2819 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2820 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2821 Invalid = true;
2822 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
2823 // C++ [temp.param]p11:
2824 // If a template-parameter of a class template has a default
2825 // template-argument, each subsequent template-parameter shall either
2826 // have a default template-argument supplied or be a template parameter
2827 // pack.
2828 Diag((*NewParam)->getLocation(),
2829 diag::err_template_param_default_arg_missing);
2830 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2831 Invalid = true;
2832 RemoveDefaultArguments = true;
2833 }
2834
2835 // If we have an old template parameter list that we're merging
2836 // in, move on to the next parameter.
2837 if (OldParams)
2838 ++OldParam;
2839 }
2840
2841 // We were missing some default arguments at the end of the list, so remove
2842 // all of the default arguments.
2843 if (RemoveDefaultArguments) {
2844 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2845 NewParamEnd = NewParams->end();
2846 NewParam != NewParamEnd; ++NewParam) {
2847 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2848 TTP->removeDefaultArgument();
2849 else if (NonTypeTemplateParmDecl *NTTP
2850 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2851 NTTP->removeDefaultArgument();
2852 else
2853 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2854 }
2855 }
2856
2857 return Invalid;
2858}
2859
2860namespace {
2861
2862/// A class which looks for a use of a certain level of template
2863/// parameter.
2864struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2865 typedef RecursiveASTVisitor<DependencyChecker> super;
2866
2867 unsigned Depth;
2868
2869 // Whether we're looking for a use of a template parameter that makes the
2870 // overall construct type-dependent / a dependent type. This is strictly
2871 // best-effort for now; we may fail to match at all for a dependent type
2872 // in some cases if this is set.
2873 bool IgnoreNonTypeDependent;
2874
2875 bool Match;
2876 SourceLocation MatchLoc;
2877
2878 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2879 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2880 Match(false) {}
2881
2882 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2883 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2884 NamedDecl *ND = Params->getParam(0);
2885 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2886 Depth = PD->getDepth();
2887 } else if (NonTypeTemplateParmDecl *PD =
2888 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2889 Depth = PD->getDepth();
2890 } else {
2891 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2892 }
2893 }
2894
2895 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2896 if (ParmDepth >= Depth) {
2897 Match = true;
2898 MatchLoc = Loc;
2899 return true;
2900 }
2901 return false;
2902 }
2903
2904 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2905 // Prune out non-type-dependent expressions if requested. This can
2906 // sometimes result in us failing to find a template parameter reference
2907 // (if a value-dependent expression creates a dependent type), but this
2908 // mode is best-effort only.
2909 if (auto *E = dyn_cast_or_null<Expr>(S))
2910 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2911 return true;
2912 return super::TraverseStmt(S, Q);
2913 }
2914
2915 bool TraverseTypeLoc(TypeLoc TL) {
2916 if (IgnoreNonTypeDependent && !TL.isNull() &&
2917 !TL.getType()->isDependentType())
2918 return true;
2919 return super::TraverseTypeLoc(TL);
2920 }
2921
2922 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2923 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2924 }
2925
2926 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
2927 // For a best-effort search, keep looking until we find a location.
2928 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2929 }
2930
2931 bool TraverseTemplateName(TemplateName N) {
2932 if (TemplateTemplateParmDecl *PD =
2933 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2934 if (Matches(PD->getDepth()))
2935 return false;
2936 return super::TraverseTemplateName(N);
2937 }
2938
2939 bool VisitDeclRefExpr(DeclRefExpr *E) {
2940 if (NonTypeTemplateParmDecl *PD =
2941 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2942 if (Matches(PD->getDepth(), E->getExprLoc()))
2943 return false;
2944 return super::VisitDeclRefExpr(E);
2945 }
2946
2947 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2948 return TraverseType(T->getReplacementType());
2949 }
2950
2951 bool
2952 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2953 return TraverseTemplateArgument(T->getArgumentPack());
2954 }
2955
2956 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2957 return TraverseType(T->getInjectedSpecializationType());
2958 }
2959};
2960} // end anonymous namespace
2961
2962/// Determines whether a given type depends on the given parameter
2963/// list.
2964static bool
2965DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
2966 if (!Params->size())
2967 return false;
2968
2969 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2970 Checker.TraverseType(T);
2971 return Checker.Match;
2972}
2973
2974// Find the source range corresponding to the named type in the given
2975// nested-name-specifier, if any.
2976static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2977 QualType T,
2978 const CXXScopeSpec &SS) {
2979 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2980 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2981 if (const Type *CurType = NNS->getAsType()) {
2982 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2983 return NNSLoc.getTypeLoc().getSourceRange();
2984 } else
2985 break;
2986
2987 NNSLoc = NNSLoc.getPrefix();
2988 }
2989
2990 return SourceRange();
2991}
2992
2993/// Match the given template parameter lists to the given scope
2994/// specifier, returning the template parameter list that applies to the
2995/// name.
2996///
2997/// \param DeclStartLoc the start of the declaration that has a scope
2998/// specifier or a template parameter list.
2999///
3000/// \param DeclLoc The location of the declaration itself.
3001///
3002/// \param SS the scope specifier that will be matched to the given template
3003/// parameter lists. This scope specifier precedes a qualified name that is
3004/// being declared.
3005///
3006/// \param TemplateId The template-id following the scope specifier, if there
3007/// is one. Used to check for a missing 'template<>'.
3008///
3009/// \param ParamLists the template parameter lists, from the outermost to the
3010/// innermost template parameter lists.
3011///
3012/// \param IsFriend Whether to apply the slightly different rules for
3013/// matching template parameters to scope specifiers in friend
3014/// declarations.
3015///
3016/// \param IsMemberSpecialization will be set true if the scope specifier
3017/// denotes a fully-specialized type, and therefore this is a declaration of
3018/// a member specialization.
3019///
3020/// \returns the template parameter list, if any, that corresponds to the
3021/// name that is preceded by the scope specifier @p SS. This template
3022/// parameter list may have template parameters (if we're declaring a
3023/// template) or may have no template parameters (if we're declaring a
3024/// template specialization), or may be NULL (if what we're declaring isn't
3025/// itself a template).
3026TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
3027 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
3028 TemplateIdAnnotation *TemplateId,
3029 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
3030 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
3031 IsMemberSpecialization = false;
3032 Invalid = false;
3033
3034 // The sequence of nested types to which we will match up the template
3035 // parameter lists. We first build this list by starting with the type named
3036 // by the nested-name-specifier and walking out until we run out of types.
3037 SmallVector<QualType, 4> NestedTypes;
3038 QualType T;
3039 if (SS.getScopeRep()) {
3040 if (CXXRecordDecl *Record
3041 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
3042 T = Context.getTypeDeclType(Record);
3043 else
3044 T = QualType(SS.getScopeRep()->getAsType(), 0);
3045 }
3046
3047 // If we found an explicit specialization that prevents us from needing
3048 // 'template<>' headers, this will be set to the location of that
3049 // explicit specialization.
3050 SourceLocation ExplicitSpecLoc;
3051
3052 while (!T.isNull()) {
3053 NestedTypes.push_back(T);
3054
3055 // Retrieve the parent of a record type.
3056 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3057 // If this type is an explicit specialization, we're done.
3058 if (ClassTemplateSpecializationDecl *Spec
3059 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3060 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
3061 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
3062 ExplicitSpecLoc = Spec->getLocation();
3063 break;
3064 }
3065 } else if (Record->getTemplateSpecializationKind()
3066 == TSK_ExplicitSpecialization) {
3067 ExplicitSpecLoc = Record->getLocation();
3068 break;
3069 }
3070
3071 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
3072 T = Context.getTypeDeclType(Parent);
3073 else
3074 T = QualType();
3075 continue;
3076 }
3077
3078 if (const TemplateSpecializationType *TST
3079 = T->getAs<TemplateSpecializationType>()) {
3080 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
3081 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
3082 T = Context.getTypeDeclType(Parent);
3083 else
3084 T = QualType();
3085 continue;
3086 }
3087 }
3088
3089 // Look one step prior in a dependent template specialization type.
3090 if (const DependentTemplateSpecializationType *DependentTST
3091 = T->getAs<DependentTemplateSpecializationType>()) {
3092 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
3093 T = QualType(NNS->getAsType(), 0);
3094 else
3095 T = QualType();
3096 continue;
3097 }
3098
3099 // Look one step prior in a dependent name type.
3100 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
3101 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
3102 T = QualType(NNS->getAsType(), 0);
3103 else
3104 T = QualType();
3105 continue;
3106 }
3107
3108 // Retrieve the parent of an enumeration type.
3109 if (const EnumType *EnumT = T->getAs<EnumType>()) {
3110 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
3111 // check here.
3112 EnumDecl *Enum = EnumT->getDecl();
3113
3114 // Get to the parent type.
3115 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
3116 T = Context.getTypeDeclType(Parent);
3117 else
3118 T = QualType();
3119 continue;
3120 }
3121
3122 T = QualType();
3123 }
3124 // Reverse the nested types list, since we want to traverse from the outermost
3125 // to the innermost while checking template-parameter-lists.
3126 std::reverse(NestedTypes.begin(), NestedTypes.end());
3127
3128 // C++0x [temp.expl.spec]p17:
3129 // A member or a member template may be nested within many
3130 // enclosing class templates. In an explicit specialization for
3131 // such a member, the member declaration shall be preceded by a
3132 // template<> for each enclosing class template that is
3133 // explicitly specialized.
3134 bool SawNonEmptyTemplateParameterList = false;
3135
3136 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
3137 if (SawNonEmptyTemplateParameterList) {
3138 if (!SuppressDiagnostic)
3139 Diag(DeclLoc, diag::err_specialize_member_of_template)
3140 << !Recovery << Range;
3141 Invalid = true;
3142 IsMemberSpecialization = false;
3143 return true;
3144 }
3145
3146 return false;
3147 };
3148
3149 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
3150 // Check that we can have an explicit specialization here.
3151 if (CheckExplicitSpecialization(Range, true))
3152 return true;
3153
3154 // We don't have a template header, but we should.
3155 SourceLocation ExpectedTemplateLoc;
3156 if (!ParamLists.empty())
3157 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
3158 else
3159 ExpectedTemplateLoc = DeclStartLoc;
3160
3161 if (!SuppressDiagnostic)
3162 Diag(DeclLoc, diag::err_template_spec_needs_header)
3163 << Range
3164 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
3165 return false;
3166 };
3167
3168 unsigned ParamIdx = 0;
3169 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
3170 ++TypeIdx) {
3171 T = NestedTypes[TypeIdx];
3172
3173 // Whether we expect a 'template<>' header.
3174 bool NeedEmptyTemplateHeader = false;
3175
3176 // Whether we expect a template header with parameters.
3177 bool NeedNonemptyTemplateHeader = false;
3178
3179 // For a dependent type, the set of template parameters that we
3180 // expect to see.
3181 TemplateParameterList *ExpectedTemplateParams = nullptr;
3182
3183 // C++0x [temp.expl.spec]p15:
3184 // A member or a member template may be nested within many enclosing
3185 // class templates. In an explicit specialization for such a member, the
3186 // member declaration shall be preceded by a template<> for each
3187 // enclosing class template that is explicitly specialized.
3188 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3189 if (ClassTemplatePartialSpecializationDecl *Partial
3190 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
3191 ExpectedTemplateParams = Partial->getTemplateParameters();
3192 NeedNonemptyTemplateHeader = true;
3193 } else if (Record->isDependentType()) {
3194 if (Record->getDescribedClassTemplate()) {
3195 ExpectedTemplateParams = Record->getDescribedClassTemplate()
3196 ->getTemplateParameters();
3197 NeedNonemptyTemplateHeader = true;
3198 }
3199 } else if (ClassTemplateSpecializationDecl *Spec
3200 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3201 // C++0x [temp.expl.spec]p4:
3202 // Members of an explicitly specialized class template are defined
3203 // in the same manner as members of normal classes, and not using
3204 // the template<> syntax.
3205 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
3206 NeedEmptyTemplateHeader = true;
3207 else
3208 continue;
3209 } else if (Record->getTemplateSpecializationKind()) {
3210 if (Record->getTemplateSpecializationKind()
3211 != TSK_ExplicitSpecialization &&
3212 TypeIdx == NumTypes - 1)
3213 IsMemberSpecialization = true;
3214
3215 continue;
3216 }
3217 } else if (const TemplateSpecializationType *TST
3218 = T->getAs<TemplateSpecializationType>()) {
3219 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
3220 ExpectedTemplateParams = Template->getTemplateParameters();
3221 NeedNonemptyTemplateHeader = true;
3222 }
3223 } else if (T->getAs<DependentTemplateSpecializationType>()) {
3224 // FIXME: We actually could/should check the template arguments here
3225 // against the corresponding template parameter list.
3226 NeedNonemptyTemplateHeader = false;
3227 }
3228
3229 // C++ [temp.expl.spec]p16:
3230 // In an explicit specialization declaration for a member of a class
3231 // template or a member template that ap- pears in namespace scope, the
3232 // member template and some of its enclosing class templates may remain
3233 // unspecialized, except that the declaration shall not explicitly
3234 // specialize a class member template if its en- closing class templates
3235 // are not explicitly specialized as well.
3236 if (ParamIdx < ParamLists.size()) {
3237 if (ParamLists[ParamIdx]->size() == 0) {
3238 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3239 false))
3240 return nullptr;
3241 } else
3242 SawNonEmptyTemplateParameterList = true;
3243 }
3244
3245 if (NeedEmptyTemplateHeader) {
3246 // If we're on the last of the types, and we need a 'template<>' header
3247 // here, then it's a member specialization.
3248 if (TypeIdx == NumTypes - 1)
3249 IsMemberSpecialization = true;
3250
3251 if (ParamIdx < ParamLists.size()) {
3252 if (ParamLists[ParamIdx]->size() > 0) {
3253 // The header has template parameters when it shouldn't. Complain.
3254 if (!SuppressDiagnostic)
3255 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3256 diag::err_template_param_list_matches_nontemplate)
3257 << T
3258 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3259 ParamLists[ParamIdx]->getRAngleLoc())
3260 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3261 Invalid = true;
3262 return nullptr;
3263 }
3264
3265 // Consume this template header.
3266 ++ParamIdx;
3267 continue;
3268 }
3269
3270 if (!IsFriend)
3271 if (DiagnoseMissingExplicitSpecialization(
3272 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
3273 return nullptr;
3274
3275 continue;
3276 }
3277
3278 if (NeedNonemptyTemplateHeader) {
3279 // In friend declarations we can have template-ids which don't
3280 // depend on the corresponding template parameter lists. But
3281 // assume that empty parameter lists are supposed to match this
3282 // template-id.
3283 if (IsFriend && T->isDependentType()) {
3284 if (ParamIdx < ParamLists.size() &&
3285 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
3286 ExpectedTemplateParams = nullptr;
3287 else
3288 continue;
3289 }
3290
3291 if (ParamIdx < ParamLists.size()) {
3292 // Check the template parameter list, if we can.
3293 if (ExpectedTemplateParams &&
3294 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
3295 ExpectedTemplateParams,
3296 !SuppressDiagnostic, TPL_TemplateMatch))
3297 Invalid = true;
3298
3299 if (!Invalid &&
3300 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
3301 TPC_ClassTemplateMember))
3302 Invalid = true;
3303
3304 ++ParamIdx;
3305 continue;
3306 }
3307
3308 if (!SuppressDiagnostic)
3309 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
3310 << T
3311 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3312 Invalid = true;
3313 continue;
3314 }
3315 }
3316
3317 // If there were at least as many template-ids as there were template
3318 // parameter lists, then there are no template parameter lists remaining for
3319 // the declaration itself.
3320 if (ParamIdx >= ParamLists.size()) {
3321 if (TemplateId && !IsFriend) {
3322 // We don't have a template header for the declaration itself, but we
3323 // should.
3324 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3325 TemplateId->RAngleLoc));
3326
3327 // Fabricate an empty template parameter list for the invented header.
3328 return TemplateParameterList::Create(Context, SourceLocation(),
3329 SourceLocation(), None,
3330 SourceLocation(), nullptr);
3331 }
3332
3333 return nullptr;
3334 }
3335
3336 // If there were too many template parameter lists, complain about that now.
3337 if (ParamIdx < ParamLists.size() - 1) {
3338 bool HasAnyExplicitSpecHeader = false;
3339 bool AllExplicitSpecHeaders = true;
3340 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3341 if (ParamLists[I]->size() == 0)
3342 HasAnyExplicitSpecHeader = true;
3343 else
3344 AllExplicitSpecHeaders = false;
3345 }
3346
3347 if (!SuppressDiagnostic)
3348 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3349 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
3350 : diag::err_template_spec_extra_headers)
3351 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3352 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3353
3354 // If there was a specialization somewhere, such that 'template<>' is
3355 // not required, and there were any 'template<>' headers, note where the
3356 // specialization occurred.
3357 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3358 !SuppressDiagnostic)
3359 Diag(ExplicitSpecLoc,
3360 diag::note_explicit_template_spec_does_not_need_header)
3361 << NestedTypes.back();
3362
3363 // We have a template parameter list with no corresponding scope, which
3364 // means that the resulting template declaration can't be instantiated
3365 // properly (we'll end up with dependent nodes when we shouldn't).
3366 if (!AllExplicitSpecHeaders)
3367 Invalid = true;
3368 }
3369
3370 // C++ [temp.expl.spec]p16:
3371 // In an explicit specialization declaration for a member of a class
3372 // template or a member template that ap- pears in namespace scope, the
3373 // member template and some of its enclosing class templates may remain
3374 // unspecialized, except that the declaration shall not explicitly
3375 // specialize a class member template if its en- closing class templates
3376 // are not explicitly specialized as well.
3377 if (ParamLists.back()->size() == 0 &&
3378 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3379 false))
3380 return nullptr;
3381
3382 // Return the last template parameter list, which corresponds to the
3383 // entity being declared.
3384 return ParamLists.back();
3385}
3386
3387void Sema::NoteAllFoundTemplates(TemplateName Name) {
3388 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3389 Diag(Template->getLocation(), diag::note_template_declared_here)
3390 << (isa<FunctionTemplateDecl>(Template)
3391 ? 0
3392 : isa<ClassTemplateDecl>(Template)
3393 ? 1
3394 : isa<VarTemplateDecl>(Template)
3395 ? 2
3396 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
3397 << Template->getDeclName();
3398 return;
3399 }
3400
3401 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3402 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3403 IEnd = OST->end();
3404 I != IEnd; ++I)
3405 Diag((*I)->getLocation(), diag::note_template_declared_here)
3406 << 0 << (*I)->getDeclName();
3407
3408 return;
3409 }
3410}
3411
3412static QualType
3413checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
3414 const SmallVectorImpl<TemplateArgument> &Converted,
3415 SourceLocation TemplateLoc,
3416 TemplateArgumentListInfo &TemplateArgs) {
3417 ASTContext &Context = SemaRef.getASTContext();
3418 switch (BTD->getBuiltinTemplateKind()) {
3419 case BTK__make_integer_seq: {
3420 // Specializations of __make_integer_seq<S, T, N> are treated like
3421 // S<T, 0, ..., N-1>.
3422
3423 // C++14 [inteseq.intseq]p1:
3424 // T shall be an integer type.
3425 if (!Converted[1].getAsType()->isIntegralType(Context)) {
3426 SemaRef.Diag(TemplateArgs[1].getLocation(),
3427 diag::err_integer_sequence_integral_element_type);
3428 return QualType();
3429 }
3430
3431 // C++14 [inteseq.make]p1:
3432 // If N is negative the program is ill-formed.
3433 TemplateArgument NumArgsArg = Converted[2];
3434 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
3435 if (NumArgs < 0) {
3436 SemaRef.Diag(TemplateArgs[2].getLocation(),
3437 diag::err_integer_sequence_negative_length);
3438 return QualType();
3439 }
3440
3441 QualType ArgTy = NumArgsArg.getIntegralType();
3442 TemplateArgumentListInfo SyntheticTemplateArgs;
3443 // The type argument gets reused as the first template argument in the
3444 // synthetic template argument list.
3445 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
3446 // Expand N into 0 ... N-1.
3447 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3448 I < NumArgs; ++I) {
3449 TemplateArgument TA(Context, I, ArgTy);
3450 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3451 TA, ArgTy, TemplateArgs[2].getLocation()));
3452 }
3453 // The first template argument will be reused as the template decl that
3454 // our synthetic template arguments will be applied to.
3455 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
3456 TemplateLoc, SyntheticTemplateArgs);
3457 }
3458
3459 case BTK__type_pack_element:
3460 // Specializations of
3461 // __type_pack_element<Index, T_1, ..., T_N>
3462 // are treated like T_Index.
3463 assert(Converted.size() == 2 &&((Converted.size() == 2 && "__type_pack_element should be given an index and a parameter pack"
) ? static_cast<void> (0) : __assert_fail ("Converted.size() == 2 && \"__type_pack_element should be given an index and a parameter pack\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 3464, __PRETTY_FUNCTION__))
3464 "__type_pack_element should be given an index and a parameter pack")((Converted.size() == 2 && "__type_pack_element should be given an index and a parameter pack"
) ? static_cast<void> (0) : __assert_fail ("Converted.size() == 2 && \"__type_pack_element should be given an index and a parameter pack\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 3464, __PRETTY_FUNCTION__))
;
3465
3466 // If the Index is out of bounds, the program is ill-formed.
3467 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3468 llvm::APSInt Index = IndexArg.getAsIntegral();
3469 assert(Index >= 0 && "the index used with __type_pack_element should be of "((Index >= 0 && "the index used with __type_pack_element should be of "
"type std::size_t, and hence be non-negative") ? static_cast
<void> (0) : __assert_fail ("Index >= 0 && \"the index used with __type_pack_element should be of \" \"type std::size_t, and hence be non-negative\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 3470, __PRETTY_FUNCTION__))
3470 "type std::size_t, and hence be non-negative")((Index >= 0 && "the index used with __type_pack_element should be of "
"type std::size_t, and hence be non-negative") ? static_cast
<void> (0) : __assert_fail ("Index >= 0 && \"the index used with __type_pack_element should be of \" \"type std::size_t, and hence be non-negative\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 3470, __PRETTY_FUNCTION__))
;
3471 if (Index >= Ts.pack_size()) {
3472 SemaRef.Diag(TemplateArgs[0].getLocation(),
3473 diag::err_type_pack_element_out_of_bounds);
3474 return QualType();
3475 }
3476
3477 // We simply return the type at index `Index`.
3478 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
3479 return Nth->getAsType();
3480 }
3481 llvm_unreachable("unexpected BuiltinTemplateDecl!")::llvm::llvm_unreachable_internal("unexpected BuiltinTemplateDecl!"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 3481)
;
3482}
3483
3484/// Determine whether this alias template is "enable_if_t".
3485static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3486 return AliasTemplate->getName().equals("enable_if_t");
3487}
3488
3489/// Collect all of the separable terms in the given condition, which
3490/// might be a conjunction.
3491///
3492/// FIXME: The right answer is to convert the logical expression into
3493/// disjunctive normal form, so we can find the first failed term
3494/// within each possible clause.
3495static void collectConjunctionTerms(Expr *Clause,
3496 SmallVectorImpl<Expr *> &Terms) {
3497 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3498 if (BinOp->getOpcode() == BO_LAnd) {
3499 collectConjunctionTerms(BinOp->getLHS(), Terms);
3500 collectConjunctionTerms(BinOp->getRHS(), Terms);
3501 }
3502
3503 return;
3504 }
3505
3506 Terms.push_back(Clause);
3507}
3508
3509// The ranges-v3 library uses an odd pattern of a top-level "||" with
3510// a left-hand side that is value-dependent but never true. Identify
3511// the idiom and ignore that term.
3512static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3513 // Top-level '||'.
3514 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3515 if (!BinOp) return Cond;
3516
3517 if (BinOp->getOpcode() != BO_LOr) return Cond;
3518
3519 // With an inner '==' that has a literal on the right-hand side.
3520 Expr *LHS = BinOp->getLHS();
3521 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3522 if (!InnerBinOp) return Cond;
3523
3524 if (InnerBinOp->getOpcode() != BO_EQ ||
3525 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3526 return Cond;
3527
3528 // If the inner binary operation came from a macro expansion named
3529 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3530 // of the '||', which is the real, user-provided condition.
3531 SourceLocation Loc = InnerBinOp->getExprLoc();
3532 if (!Loc.isMacroID()) return Cond;
3533
3534 StringRef MacroName = PP.getImmediateMacroName(Loc);
3535 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3536 return BinOp->getRHS();
3537
3538 return Cond;
3539}
3540
3541namespace {
3542
3543// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3544// within failing boolean expression, such as substituting template parameters
3545// for actual types.
3546class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3547public:
3548 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3549 : Policy(P) {}
3550
3551 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3552 const auto *DR = dyn_cast<DeclRefExpr>(E);
3553 if (DR && DR->getQualifier()) {
3554 // If this is a qualified name, expand the template arguments in nested
3555 // qualifiers.
3556 DR->getQualifier()->print(OS, Policy, true);
3557 // Then print the decl itself.
3558 const ValueDecl *VD = DR->getDecl();
3559 OS << VD->getName();
3560 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3561 // This is a template variable, print the expanded template arguments.
3562 printTemplateArgumentList(OS, IV->getTemplateArgs().asArray(), Policy);
3563 }
3564 return true;
3565 }
3566 return false;
3567 }
3568
3569private:
3570 const PrintingPolicy Policy;
3571};
3572
3573} // end anonymous namespace
3574
3575std::pair<Expr *, std::string>
3576Sema::findFailedBooleanCondition(Expr *Cond) {
3577 Cond = lookThroughRangesV3Condition(PP, Cond);
3578
3579 // Separate out all of the terms in a conjunction.
3580 SmallVector<Expr *, 4> Terms;
3581 collectConjunctionTerms(Cond, Terms);
3582
3583 // Determine which term failed.
3584 Expr *FailedCond = nullptr;
3585 for (Expr *Term : Terms) {
3586 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3587
3588 // Literals are uninteresting.
3589 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3590 isa<IntegerLiteral>(TermAsWritten))
3591 continue;
3592
3593 // The initialization of the parameter from the argument is
3594 // a constant-evaluated context.
3595 EnterExpressionEvaluationContext ConstantEvaluated(
3596 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3597
3598 bool Succeeded;
3599 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3600 !Succeeded) {
3601 FailedCond = TermAsWritten;
3602 break;
3603 }
3604 }
3605 if (!FailedCond)
3606 FailedCond = Cond->IgnoreParenImpCasts();
3607
3608 std::string Description;
3609 {
3610 llvm::raw_string_ostream Out(Description);
3611 PrintingPolicy Policy = getPrintingPolicy();
3612 Policy.PrintCanonicalTypes = true;
3613 FailedBooleanConditionPrinterHelper Helper(Policy);
3614 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3615 }
3616 return { FailedCond, Description };
3617}
3618
3619QualType Sema::CheckTemplateIdType(TemplateName Name,
3620 SourceLocation TemplateLoc,
3621 TemplateArgumentListInfo &TemplateArgs) {
3622 DependentTemplateName *DTN
3623 = Name.getUnderlying().getAsDependentTemplateName();
3624 if (DTN && DTN->isIdentifier())
3625 // When building a template-id where the template-name is dependent,
3626 // assume the template is a type template. Either our assumption is
3627 // correct, or the code is ill-formed and will be diagnosed when the
3628 // dependent name is substituted.
3629 return Context.getDependentTemplateSpecializationType(ETK_None,
3630 DTN->getQualifier(),
3631 DTN->getIdentifier(),
3632 TemplateArgs);
3633
3634 if (Name.getAsAssumedTemplateName() &&
3635 resolveAssumedTemplateNameAsType(/*Scope*/nullptr, Name, TemplateLoc))
3636 return QualType();
3637
3638 TemplateDecl *Template = Name.getAsTemplateDecl();
3639 if (!Template || isa<FunctionTemplateDecl>(Template) ||
3640 isa<VarTemplateDecl>(Template) || isa<ConceptDecl>(Template)) {
3641 // We might have a substituted template template parameter pack. If so,
3642 // build a template specialization type for it.
3643 if (Name.getAsSubstTemplateTemplateParmPack())
3644 return Context.getTemplateSpecializationType(Name, TemplateArgs);
3645
3646 Diag(TemplateLoc, diag::err_template_id_not_a_type)
3647 << Name;
3648 NoteAllFoundTemplates(Name);
3649 return QualType();
3650 }
3651
3652 // Check that the template argument list is well-formed for this
3653 // template.
3654 SmallVector<TemplateArgument, 4> Converted;
3655 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3656 false, Converted,
3657 /*UpdateArgsWithConversion=*/true))
3658 return QualType();
3659
3660 QualType CanonType;
3661
3662 bool InstantiationDependent = false;
3663 if (TypeAliasTemplateDecl *AliasTemplate =
3664 dyn_cast<TypeAliasTemplateDecl>(Template)) {
3665
3666 // Find the canonical type for this type alias template specialization.
3667 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3668 if (Pattern->isInvalidDecl())
3669 return QualType();
3670
3671 TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack,
3672 Converted);
3673
3674 // Only substitute for the innermost template argument list.
3675 MultiLevelTemplateArgumentList TemplateArgLists;
3676 TemplateArgLists.addOuterTemplateArguments(&StackTemplateArgs);
3677 TemplateArgLists.addOuterRetainedLevels(
3678 AliasTemplate->getTemplateParameters()->getDepth());
3679
3680 LocalInstantiationScope Scope(*this);
3681 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
3682 if (Inst.isInvalid())
3683 return QualType();
3684
3685 CanonType = SubstType(Pattern->getUnderlyingType(),
3686 TemplateArgLists, AliasTemplate->getLocation(),
3687 AliasTemplate->getDeclName());
3688 if (CanonType.isNull()) {
3689 // If this was enable_if and we failed to find the nested type
3690 // within enable_if in a SFINAE context, dig out the specific
3691 // enable_if condition that failed and present that instead.
3692 if (isEnableIfAliasTemplate(AliasTemplate)) {
3693 if (auto DeductionInfo = isSFINAEContext()) {
3694 if (*DeductionInfo &&
3695 (*DeductionInfo)->hasSFINAEDiagnostic() &&
3696 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3697 diag::err_typename_nested_not_found_enable_if &&
3698 TemplateArgs[0].getArgument().getKind()
3699 == TemplateArgument::Expression) {
3700 Expr *FailedCond;
3701 std::string FailedDescription;
3702 std::tie(FailedCond, FailedDescription) =
3703 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3704
3705 // Remove the old SFINAE diagnostic.
3706 PartialDiagnosticAt OldDiag =
3707 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3708 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3709
3710 // Add a new SFINAE diagnostic specifying which condition
3711 // failed.
3712 (*DeductionInfo)->addSFINAEDiagnostic(
3713 OldDiag.first,
3714 PDiag(diag::err_typename_nested_not_found_requirement)
3715 << FailedDescription
3716 << FailedCond->getSourceRange());
3717 }
3718 }
3719 }
3720
3721 return QualType();
3722 }
3723 } else if (Name.isDependent() ||
3724 TemplateSpecializationType::anyDependentTemplateArguments(
3725 TemplateArgs, InstantiationDependent)) {
3726 // This class template specialization is a dependent
3727 // type. Therefore, its canonical type is another class template
3728 // specialization type that contains all of the converted
3729 // arguments in canonical form. This ensures that, e.g., A<T> and
3730 // A<T, T> have identical types when A is declared as:
3731 //
3732 // template<typename T, typename U = T> struct A;
3733 CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
3734
3735 // This might work out to be a current instantiation, in which
3736 // case the canonical type needs to be the InjectedClassNameType.
3737 //
3738 // TODO: in theory this could be a simple hashtable lookup; most
3739 // changes to CurContext don't change the set of current
3740 // instantiations.
3741 if (isa<ClassTemplateDecl>(Template)) {
3742 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3743 // If we get out to a namespace, we're done.
3744 if (Ctx->isFileContext()) break;
3745
3746 // If this isn't a record, keep looking.
3747 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3748 if (!Record) continue;
3749
3750 // Look for one of the two cases with InjectedClassNameTypes
3751 // and check whether it's the same template.
3752 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3753 !Record->getDescribedClassTemplate())
3754 continue;
3755
3756 // Fetch the injected class name type and check whether its
3757 // injected type is equal to the type we just built.
3758 QualType ICNT = Context.getTypeDeclType(Record);
3759 QualType Injected = cast<InjectedClassNameType>(ICNT)
3760 ->getInjectedSpecializationType();
3761
3762 if (CanonType != Injected->getCanonicalTypeInternal())
3763 continue;
3764
3765 // If so, the canonical type of this TST is the injected
3766 // class name type of the record we just found.
3767 assert(ICNT.isCanonical())((ICNT.isCanonical()) ? static_cast<void> (0) : __assert_fail
("ICNT.isCanonical()", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 3767, __PRETTY_FUNCTION__))
;
3768 CanonType = ICNT;
3769 break;
3770 }
3771 }
3772 } else if (ClassTemplateDecl *ClassTemplate
3773 = dyn_cast<ClassTemplateDecl>(Template)) {
3774 // Find the class template specialization declaration that
3775 // corresponds to these arguments.
3776 void *InsertPos = nullptr;
3777 ClassTemplateSpecializationDecl *Decl
3778 = ClassTemplate->findSpecialization(Converted, InsertPos);
3779 if (!Decl) {
3780 // This is the first time we have referenced this class template
3781 // specialization. Create the canonical declaration and add it to
3782 // the set of specializations.
3783 Decl = ClassTemplateSpecializationDecl::Create(
3784 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3785 ClassTemplate->getDeclContext(),
3786 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3787 ClassTemplate->getLocation(), ClassTemplate, Converted, nullptr);
3788 ClassTemplate->AddSpecialization(Decl, InsertPos);
3789 if (ClassTemplate->isOutOfLine())
3790 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3791 }
3792
3793 if (Decl->getSpecializationKind() == TSK_Undeclared) {
3794 MultiLevelTemplateArgumentList TemplateArgLists;
3795 TemplateArgLists.addOuterTemplateArguments(Converted);
3796 InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(),
3797 Decl);
3798 }
3799
3800 // Diagnose uses of this specialization.
3801 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3802
3803 CanonType = Context.getTypeDeclType(Decl);
3804 assert(isa<RecordType>(CanonType) &&((isa<RecordType>(CanonType) && "type of non-dependent specialization is not a RecordType"
) ? static_cast<void> (0) : __assert_fail ("isa<RecordType>(CanonType) && \"type of non-dependent specialization is not a RecordType\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 3805, __PRETTY_FUNCTION__))
3805 "type of non-dependent specialization is not a RecordType")((isa<RecordType>(CanonType) && "type of non-dependent specialization is not a RecordType"
) ? static_cast<void> (0) : __assert_fail ("isa<RecordType>(CanonType) && \"type of non-dependent specialization is not a RecordType\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 3805, __PRETTY_FUNCTION__))
;
3806 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3807 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
3808 TemplateArgs);
3809 }
3810
3811 // Build the fully-sugared type for this class template
3812 // specialization, which refers back to the class template
3813 // specialization we created or found.
3814 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
3815}
3816
3817void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,
3818 TemplateNameKind &TNK,
3819 SourceLocation NameLoc,
3820 IdentifierInfo *&II) {
3821 assert(TNK == TNK_Undeclared_template && "not an undeclared template name")((TNK == TNK_Undeclared_template && "not an undeclared template name"
) ? static_cast<void> (0) : __assert_fail ("TNK == TNK_Undeclared_template && \"not an undeclared template name\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 3821, __PRETTY_FUNCTION__))
;
3822
3823 TemplateName Name = ParsedName.get();
3824 auto *ATN = Name.getAsAssumedTemplateName();
3825 assert(ATN && "not an assumed template name")((ATN && "not an assumed template name") ? static_cast
<void> (0) : __assert_fail ("ATN && \"not an assumed template name\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 3825, __PRETTY_FUNCTION__))
;
3826 II = ATN->getDeclName().getAsIdentifierInfo();
3827
3828 if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
3829 // Resolved to a type template name.
3830 ParsedName = TemplateTy::make(Name);
3831 TNK = TNK_Type_template;
3832 }
3833}
3834
3835bool Sema::resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
3836 SourceLocation NameLoc,
3837 bool Diagnose) {
3838 // We assumed this undeclared identifier to be an (ADL-only) function
3839 // template name, but it was used in a context where a type was required.
3840 // Try to typo-correct it now.
3841 AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
3842 assert(ATN && "not an assumed template name")((ATN && "not an assumed template name") ? static_cast
<void> (0) : __assert_fail ("ATN && \"not an assumed template name\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 3842, __PRETTY_FUNCTION__))
;
3843
3844 LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
3845 struct CandidateCallback : CorrectionCandidateCallback {
3846 bool ValidateCandidate(const TypoCorrection &TC) override {
3847 return TC.getCorrectionDecl() &&
3848 getAsTypeTemplateDecl(TC.getCorrectionDecl());
3849 }
3850 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3851 return std::make_unique<CandidateCallback>(*this);
3852 }
3853 } FilterCCC;
3854
3855 TypoCorrection Corrected =
3856 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
3857 FilterCCC, CTK_ErrorRecovery);
3858 if (Corrected && Corrected.getFoundDecl()) {
3859 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
3860 << ATN->getDeclName());
3861 Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>());
3862 return false;
3863 }
3864
3865 if (Diagnose)
3866 Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
3867 return true;
3868}
3869
3870TypeResult Sema::ActOnTemplateIdType(
3871 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3872 TemplateTy TemplateD, IdentifierInfo *TemplateII,
3873 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
3874 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
3875 bool IsCtorOrDtorName, bool IsClassName) {
3876 if (SS.isInvalid())
3877 return true;
3878
3879 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3880 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3881
3882 // C++ [temp.res]p3:
3883 // A qualified-id that refers to a type and in which the
3884 // nested-name-specifier depends on a template-parameter (14.6.2)
3885 // shall be prefixed by the keyword typename to indicate that the
3886 // qualified-id denotes a type, forming an
3887 // elaborated-type-specifier (7.1.5.3).
3888 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
3889 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
3890 << SS.getScopeRep() << TemplateII->getName();
3891 // Recover as if 'typename' were specified.
3892 // FIXME: This is not quite correct recovery as we don't transform SS
3893 // into the corresponding dependent form (and we don't diagnose missing
3894 // 'template' keywords within SS as a result).
3895 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3896 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3897 TemplateArgsIn, RAngleLoc);
3898 }
3899
3900 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3901 // it's not actually allowed to be used as a type in most cases. Because
3902 // we annotate it before we know whether it's valid, we have to check for
3903 // this case here.
3904 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
3905 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3906 Diag(TemplateIILoc,
3907 TemplateKWLoc.isInvalid()
3908 ? diag::err_out_of_line_qualified_id_type_names_constructor
3909 : diag::ext_out_of_line_qualified_id_type_names_constructor)
3910 << TemplateII << 0 /*injected-class-name used as template name*/
3911 << 1 /*if any keyword was present, it was 'template'*/;
3912 }
3913 }
3914
3915 TemplateName Template = TemplateD.get();
3916 if (Template.getAsAssumedTemplateName() &&
3917 resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
3918 return true;
3919
3920 // Translate the parser's template argument list in our AST format.
3921 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3922 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3923
3924 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3925 QualType T
3926 = Context.getDependentTemplateSpecializationType(ETK_None,
3927 DTN->getQualifier(),
3928 DTN->getIdentifier(),
3929 TemplateArgs);
3930 // Build type-source information.
3931 TypeLocBuilder TLB;
3932 DependentTemplateSpecializationTypeLoc SpecTL
3933 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3934 SpecTL.setElaboratedKeywordLoc(SourceLocation());
3935 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3936 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3937 SpecTL.setTemplateNameLoc(TemplateIILoc);
3938 SpecTL.setLAngleLoc(LAngleLoc);
3939 SpecTL.setRAngleLoc(RAngleLoc);
3940 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3941 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3942 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3943 }
3944
3945 QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
3946 if (Result.isNull())
3947 return true;
3948
3949 // Build type-source information.
3950 TypeLocBuilder TLB;
3951 TemplateSpecializationTypeLoc SpecTL
3952 = TLB.push<TemplateSpecializationTypeLoc>(Result);
3953 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3954 SpecTL.setTemplateNameLoc(TemplateIILoc);
3955 SpecTL.setLAngleLoc(LAngleLoc);
3956 SpecTL.setRAngleLoc(RAngleLoc);
3957 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3958 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3959
3960 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
3961 // constructor or destructor name (in such a case, the scope specifier
3962 // will be attached to the enclosing Decl or Expr node).
3963 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
3964 // Create an elaborated-type-specifier containing the nested-name-specifier.
3965 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
3966 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3967 ElabTL.setElaboratedKeywordLoc(SourceLocation());
3968 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3969 }
3970
3971 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3972}
3973
3974TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
3975 TypeSpecifierType TagSpec,
3976 SourceLocation TagLoc,
3977 CXXScopeSpec &SS,
3978 SourceLocation TemplateKWLoc,
3979 TemplateTy TemplateD,
3980 SourceLocation TemplateLoc,
3981 SourceLocation LAngleLoc,
3982 ASTTemplateArgsPtr TemplateArgsIn,
3983 SourceLocation RAngleLoc) {
3984 if (SS.isInvalid())
3985 return TypeResult(true);
3986
3987 TemplateName Template = TemplateD.get();
3988
3989 // Translate the parser's template argument list in our AST format.
3990 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3991 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3992
3993 // Determine the tag kind
3994 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3995 ElaboratedTypeKeyword Keyword
3996 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
3997
3998 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3999 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
4000 DTN->getQualifier(),
4001 DTN->getIdentifier(),
4002 TemplateArgs);
4003
4004 // Build type-source information.
4005 TypeLocBuilder TLB;
4006 DependentTemplateSpecializationTypeLoc SpecTL
4007 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
4008 SpecTL.setElaboratedKeywordLoc(TagLoc);
4009 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
4010 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4011 SpecTL.setTemplateNameLoc(TemplateLoc);
4012 SpecTL.setLAngleLoc(LAngleLoc);
4013 SpecTL.setRAngleLoc(RAngleLoc);
4014 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
4015 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
4016 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
4017 }
4018
4019 if (TypeAliasTemplateDecl *TAT =
4020 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
4021 // C++0x [dcl.type.elab]p2:
4022 // If the identifier resolves to a typedef-name or the simple-template-id
4023 // resolves to an alias template specialization, the
4024 // elaborated-type-specifier is ill-formed.
4025 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
4026 << TAT << NTK_TypeAliasTemplate << TagKind;
4027 Diag(TAT->getLocation(), diag::note_declared_at);
4028 }
4029
4030 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
4031 if (Result.isNull())
4032 return TypeResult(true);
4033
4034 // Check the tag kind
4035 if (const RecordType *RT = Result->getAs<RecordType>()) {
4036 RecordDecl *D = RT->getDecl();
4037
4038 IdentifierInfo *Id = D->getIdentifier();
4039 assert(Id && "templated class must have an identifier")((Id && "templated class must have an identifier") ? static_cast
<void> (0) : __assert_fail ("Id && \"templated class must have an identifier\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 4039, __PRETTY_FUNCTION__))
;
4040
4041 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
4042 TagLoc, Id)) {
4043 Diag(TagLoc, diag::err_use_with_wrong_tag)
4044 << Result
4045 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
4046 Diag(D->getLocation(), diag::note_previous_use);
4047 }
4048 }
4049
4050 // Provide source-location information for the template specialization.
4051 TypeLocBuilder TLB;
4052 TemplateSpecializationTypeLoc SpecTL
4053 = TLB.push<TemplateSpecializationTypeLoc>(Result);
4054 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4055 SpecTL.setTemplateNameLoc(TemplateLoc);
4056 SpecTL.setLAngleLoc(LAngleLoc);
4057 SpecTL.setRAngleLoc(RAngleLoc);
4058 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
4059 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
4060
4061 // Construct an elaborated type containing the nested-name-specifier (if any)
4062 // and tag keyword.
4063 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
4064 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
4065 ElabTL.setElaboratedKeywordLoc(TagLoc);
4066 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
4067 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
4068}
4069
4070static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4071 NamedDecl *PrevDecl,
4072 SourceLocation Loc,
4073 bool IsPartialSpecialization);
4074
4075static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
4076
4077static bool isTemplateArgumentTemplateParameter(
4078 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
4079 switch (Arg.getKind()) {
4080 case TemplateArgument::Null:
4081 case TemplateArgument::NullPtr:
4082 case TemplateArgument::Integral:
4083 case TemplateArgument::Declaration:
4084 case TemplateArgument::Pack:
4085 case TemplateArgument::TemplateExpansion:
4086 return false;
4087
4088 case TemplateArgument::Type: {
4089 QualType Type = Arg.getAsType();
4090 const TemplateTypeParmType *TPT =
4091 Arg.getAsType()->getAs<TemplateTypeParmType>();
4092 return TPT && !Type.hasQualifiers() &&
4093 TPT->getDepth() == Depth && TPT->getIndex() == Index;
4094 }
4095
4096 case TemplateArgument::Expression: {
4097 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
4098 if (!DRE || !DRE->getDecl())
4099 return false;
4100 const NonTypeTemplateParmDecl *NTTP =
4101 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4102 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4103 }
4104
4105 case TemplateArgument::Template:
4106 const TemplateTemplateParmDecl *TTP =
4107 dyn_cast_or_null<TemplateTemplateParmDecl>(
4108 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
4109 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4110 }
4111 llvm_unreachable("unexpected kind of template argument")::llvm::llvm_unreachable_internal("unexpected kind of template argument"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 4111)
;
4112}
4113
4114static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
4115 ArrayRef<TemplateArgument> Args) {
4116 if (Params->size() != Args.size())
4117 return false;
4118
4119 unsigned Depth = Params->getDepth();
4120
4121 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4122 TemplateArgument Arg = Args[I];
4123
4124 // If the parameter is a pack expansion, the argument must be a pack
4125 // whose only element is a pack expansion.
4126 if (Params->getParam(I)->isParameterPack()) {
4127 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4128 !Arg.pack_begin()->isPackExpansion())
4129 return false;
4130 Arg = Arg.pack_begin()->getPackExpansionPattern();
4131 }
4132
4133 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
4134 return false;
4135 }
4136
4137 return true;
4138}
4139
4140template<typename PartialSpecDecl>
4141static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4142 if (Partial->getDeclContext()->isDependentContext())
4143 return;
4144
4145 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4146 // for non-substitution-failure issues?
4147 TemplateDeductionInfo Info(Partial->getLocation());
4148 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4149 return;
4150
4151 auto *Template = Partial->getSpecializedTemplate();
4152 S.Diag(Partial->getLocation(),
4153 diag::ext_partial_spec_not_more_specialized_than_primary)
4154 << isa<VarTemplateDecl>(Template);
4155
4156 if (Info.hasSFINAEDiagnostic()) {
4157 PartialDiagnosticAt Diag = {SourceLocation(),
4158 PartialDiagnostic::NullDiagnostic()};
4159 Info.takeSFINAEDiagnostic(Diag);
4160 SmallString<128> SFINAEArgString;
4161 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4162 S.Diag(Diag.first,
4163 diag::note_partial_spec_not_more_specialized_than_primary)
4164 << SFINAEArgString;
4165 }
4166
4167 S.Diag(Template->getLocation(), diag::note_template_decl_here);
4168 SmallVector<const Expr *, 3> PartialAC, TemplateAC;
4169 Template->getAssociatedConstraints(TemplateAC);
4170 Partial->getAssociatedConstraints(PartialAC);
4171 S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template,
4172 TemplateAC);
4173}
4174
4175static void
4176noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
4177 const llvm::SmallBitVector &DeducibleParams) {
4178 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4179 if (!DeducibleParams[I]) {
4180 NamedDecl *Param = TemplateParams->getParam(I);
4181 if (Param->getDeclName())
4182 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4183 << Param->getDeclName();
4184 else
4185 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4186 << "(anonymous)";
4187 }
4188 }
4189}
4190
4191
4192template<typename PartialSpecDecl>
4193static void checkTemplatePartialSpecialization(Sema &S,
4194 PartialSpecDecl *Partial) {
4195 // C++1z [temp.class.spec]p8: (DR1495)
4196 // - The specialization shall be more specialized than the primary
4197 // template (14.5.5.2).
4198 checkMoreSpecializedThanPrimary(S, Partial);
4199
4200 // C++ [temp.class.spec]p8: (DR1315)
4201 // - Each template-parameter shall appear at least once in the
4202 // template-id outside a non-deduced context.
4203 // C++1z [temp.class.spec.match]p3 (P0127R2)
4204 // If the template arguments of a partial specialization cannot be
4205 // deduced because of the structure of its template-parameter-list
4206 // and the template-id, the program is ill-formed.
4207 auto *TemplateParams = Partial->getTemplateParameters();
4208 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4209 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4210 TemplateParams->getDepth(), DeducibleParams);
4211
4212 if (!DeducibleParams.all()) {
4213 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4214 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4215 << isa<VarTemplatePartialSpecializationDecl>(Partial)
4216 << (NumNonDeducible > 1)
4217 << SourceRange(Partial->getLocation(),
4218 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4219 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4220 }
4221}
4222
4223void Sema::CheckTemplatePartialSpecialization(
4224 ClassTemplatePartialSpecializationDecl *Partial) {
4225 checkTemplatePartialSpecialization(*this, Partial);
4226}
4227
4228void Sema::CheckTemplatePartialSpecialization(
4229 VarTemplatePartialSpecializationDecl *Partial) {
4230 checkTemplatePartialSpecialization(*this, Partial);
4231}
4232
4233void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
4234 // C++1z [temp.param]p11:
4235 // A template parameter of a deduction guide template that does not have a
4236 // default-argument shall be deducible from the parameter-type-list of the
4237 // deduction guide template.
4238 auto *TemplateParams = TD->getTemplateParameters();
4239 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4240 MarkDeducedTemplateParameters(TD, DeducibleParams);
4241 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4242 // A parameter pack is deducible (to an empty pack).
4243 auto *Param = TemplateParams->getParam(I);
4244 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
4245 DeducibleParams[I] = true;
4246 }
4247
4248 if (!DeducibleParams.all()) {
4249 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4250 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4251 << (NumNonDeducible > 1);
4252 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4253 }
4254}
4255
4256DeclResult Sema::ActOnVarTemplateSpecialization(
4257 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
4258 TemplateParameterList *TemplateParams, StorageClass SC,
4259 bool IsPartialSpecialization) {
4260 // D must be variable template id.
4261 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&((D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
"Variable template specialization is declared with a template it."
) ? static_cast<void> (0) : __assert_fail ("D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId && \"Variable template specialization is declared with a template it.\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 4262, __PRETTY_FUNCTION__))
4262 "Variable template specialization is declared with a template it.")((D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
"Variable template specialization is declared with a template it."
) ? static_cast<void> (0) : __assert_fail ("D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId && \"Variable template specialization is declared with a template it.\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 4262, __PRETTY_FUNCTION__))
;
4263
4264 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4265 TemplateArgumentListInfo TemplateArgs =
4266 makeTemplateArgumentListInfo(*this, *TemplateId);
4267 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4268 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4269 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4270
4271 TemplateName Name = TemplateId->Template.get();
4272
4273 // The template-id must name a variable template.
4274 VarTemplateDecl *VarTemplate =
4275 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4276 if (!VarTemplate) {
4277 NamedDecl *FnTemplate;
4278 if (auto *OTS = Name.getAsOverloadedTemplate())
4279 FnTemplate = *OTS->begin();
4280 else
4281 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4282 if (FnTemplate)
4283 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4284 << FnTemplate->getDeclName();
4285 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4286 << IsPartialSpecialization;
4287 }
4288
4289 // Check for unexpanded parameter packs in any of the template arguments.
4290 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4291 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4292 UPPC_PartialSpecialization))
4293 return true;
4294
4295 // Check that the template argument list is well-formed for this
4296 // template.
4297 SmallVector<TemplateArgument, 4> Converted;
4298 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4299 false, Converted,
4300 /*UpdateArgsWithConversion=*/true))
4301 return true;
4302
4303 // Find the variable template (partial) specialization declaration that
4304 // corresponds to these arguments.
4305 if (IsPartialSpecialization) {
4306 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
4307 TemplateArgs.size(), Converted))
4308 return true;
4309
4310 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
4311 // also do them during instantiation.
4312 bool InstantiationDependent;
4313 if (!Name.isDependent() &&
4314 !TemplateSpecializationType::anyDependentTemplateArguments(
4315 TemplateArgs.arguments(),
4316 InstantiationDependent)) {
4317 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4318 << VarTemplate->getDeclName();
4319 IsPartialSpecialization = false;
4320 }
4321
4322 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4323 Converted) &&
4324 (!Context.getLangOpts().CPlusPlus20 ||
4325 !TemplateParams->hasAssociatedConstraints())) {
4326 // C++ [temp.class.spec]p9b3:
4327 //
4328 // -- The argument list of the specialization shall not be identical
4329 // to the implicit argument list of the primary template.
4330 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4331 << /*variable template*/ 1
4332 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
4333 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4334 // FIXME: Recover from this by treating the declaration as a redeclaration
4335 // of the primary template.
4336 return true;
4337 }
4338 }
4339
4340 void *InsertPos = nullptr;
4341 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4342
4343 if (IsPartialSpecialization)
4344 PrevDecl = VarTemplate->findPartialSpecialization(Converted, TemplateParams,
4345 InsertPos);
4346 else
4347 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
4348
4349 VarTemplateSpecializationDecl *Specialization = nullptr;
4350
4351 // Check whether we can declare a variable template specialization in
4352 // the current scope.
4353 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4354 TemplateNameLoc,
4355 IsPartialSpecialization))
4356 return true;
4357
4358 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4359 // Since the only prior variable template specialization with these
4360 // arguments was referenced but not declared, reuse that
4361 // declaration node as our own, updating its source location and
4362 // the list of outer template parameters to reflect our new declaration.
4363 Specialization = PrevDecl;
4364 Specialization->setLocation(TemplateNameLoc);
4365 PrevDecl = nullptr;
4366 } else if (IsPartialSpecialization) {
4367 // Create a new class template partial specialization declaration node.
4368 VarTemplatePartialSpecializationDecl *PrevPartial =
4369 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4370 VarTemplatePartialSpecializationDecl *Partial =
4371 VarTemplatePartialSpecializationDecl::Create(
4372 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4373 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
4374 Converted, TemplateArgs);
4375
4376 if (!PrevPartial)
4377 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4378 Specialization = Partial;
4379
4380 // If we are providing an explicit specialization of a member variable
4381 // template specialization, make a note of that.
4382 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4383 PrevPartial->setMemberSpecialization();
4384
4385 CheckTemplatePartialSpecialization(Partial);
4386 } else {
4387 // Create a new class template specialization declaration node for
4388 // this explicit specialization or friend declaration.
4389 Specialization = VarTemplateSpecializationDecl::Create(
4390 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4391 VarTemplate, DI->getType(), DI, SC, Converted);
4392 Specialization->setTemplateArgsInfo(TemplateArgs);
4393
4394 if (!PrevDecl)
4395 VarTemplate->AddSpecialization(Specialization, InsertPos);
4396 }
4397
4398 // C++ [temp.expl.spec]p6:
4399 // If a template, a member template or the member of a class template is
4400 // explicitly specialized then that specialization shall be declared
4401 // before the first use of that specialization that would cause an implicit
4402 // instantiation to take place, in every translation unit in which such a
4403 // use occurs; no diagnostic is required.
4404 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4405 bool Okay = false;
4406 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4407 // Is there any previous explicit specialization declaration?
4408 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
4409 Okay = true;
4410 break;
4411 }
4412 }
4413
4414 if (!Okay) {
4415 SourceRange Range(TemplateNameLoc, RAngleLoc);
4416 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4417 << Name << Range;
4418
4419 Diag(PrevDecl->getPointOfInstantiation(),
4420 diag::note_instantiation_required_here)
4421 << (PrevDecl->getTemplateSpecializationKind() !=
4422 TSK_ImplicitInstantiation);
4423 return true;
4424 }
4425 }
4426
4427 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
4428 Specialization->setLexicalDeclContext(CurContext);
4429
4430 // Add the specialization into its lexical context, so that it can
4431 // be seen when iterating through the list of declarations in that
4432 // context. However, specializations are not found by name lookup.
4433 CurContext->addDecl(Specialization);
4434
4435 // Note that this is an explicit specialization.
4436 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4437
4438 if (PrevDecl) {
4439 // Check that this isn't a redefinition of this specialization,
4440 // merging with previous declarations.
4441 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
4442 forRedeclarationInCurContext());
4443 PrevSpec.addDecl(PrevDecl);
4444 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
4445 } else if (Specialization->isStaticDataMember() &&
4446 Specialization->isOutOfLine()) {
4447 Specialization->setAccess(VarTemplate->getAccess());
4448 }
4449
4450 return Specialization;
4451}
4452
4453namespace {
4454/// A partial specialization whose template arguments have matched
4455/// a given template-id.
4456struct PartialSpecMatchResult {
4457 VarTemplatePartialSpecializationDecl *Partial;
4458 TemplateArgumentList *Args;
4459};
4460} // end anonymous namespace
4461
4462DeclResult
4463Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
4464 SourceLocation TemplateNameLoc,
4465 const TemplateArgumentListInfo &TemplateArgs) {
4466 assert(Template && "A variable template id without template?")((Template && "A variable template id without template?"
) ? static_cast<void> (0) : __assert_fail ("Template && \"A variable template id without template?\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 4466, __PRETTY_FUNCTION__))
;
4467
4468 // Check that the template argument list is well-formed for this template.
4469 SmallVector<TemplateArgument, 4> Converted;
4470 if (CheckTemplateArgumentList(
4471 Template, TemplateNameLoc,
4472 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
4473 Converted, /*UpdateArgsWithConversion=*/true))
4474 return true;
4475
4476 // Produce a placeholder value if the specialization is dependent.
4477 bool InstantiationDependent = false;
4478 if (Template->getDeclContext()->isDependentContext() ||
4479 TemplateSpecializationType::anyDependentTemplateArguments(
4480 TemplateArgs, InstantiationDependent))
4481 return DeclResult();
4482
4483 // Find the variable template specialization declaration that
4484 // corresponds to these arguments.
4485 void *InsertPos = nullptr;
4486 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
4487 Converted, InsertPos)) {
4488 checkSpecializationVisibility(TemplateNameLoc, Spec);
4489 // If we already have a variable template specialization, return it.
4490 return Spec;
4491 }
4492
4493 // This is the first time we have referenced this variable template
4494 // specialization. Create the canonical declaration and add it to
4495 // the set of specializations, based on the closest partial specialization
4496 // that it represents. That is,
4497 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4498 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
4499 Converted);
4500 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
4501 bool AmbiguousPartialSpec = false;
4502 typedef PartialSpecMatchResult MatchResult;
4503 SmallVector<MatchResult, 4> Matched;
4504 SourceLocation PointOfInstantiation = TemplateNameLoc;
4505 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4506 /*ForTakingAddress=*/false);
4507
4508 // 1. Attempt to find the closest partial specialization that this
4509 // specializes, if any.
4510 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4511 // Perhaps better after unification of DeduceTemplateArguments() and
4512 // getMoreSpecializedPartialSpecialization().
4513 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4514 Template->getPartialSpecializations(PartialSpecs);
4515
4516 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
4517 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
4518 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4519
4520 if (TemplateDeductionResult Result =
4521 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
4522 // Store the failed-deduction information for use in diagnostics, later.
4523 // TODO: Actually use the failed-deduction info?
4524 FailedCandidates.addCandidate().set(
4525 DeclAccessPair::make(Template, AS_public), Partial,
4526 MakeDeductionFailureInfo(Context, Result, Info));
4527 (void)Result;
4528 } else {
4529 Matched.push_back(PartialSpecMatchResult());
4530 Matched.back().Partial = Partial;
4531 Matched.back().Args = Info.take();
4532 }
4533 }
4534
4535 if (Matched.size() >= 1) {
4536 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4537 if (Matched.size() == 1) {
4538 // -- If exactly one matching specialization is found, the
4539 // instantiation is generated from that specialization.
4540 // We don't need to do anything for this.
4541 } else {
4542 // -- If more than one matching specialization is found, the
4543 // partial order rules (14.5.4.2) are used to determine
4544 // whether one of the specializations is more specialized
4545 // than the others. If none of the specializations is more
4546 // specialized than all of the other matching
4547 // specializations, then the use of the variable template is
4548 // ambiguous and the program is ill-formed.
4549 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4550 PEnd = Matched.end();
4551 P != PEnd; ++P) {
4552 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4553 PointOfInstantiation) ==
4554 P->Partial)
4555 Best = P;
4556 }
4557
4558 // Determine if the best partial specialization is more specialized than
4559 // the others.
4560 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4561 PEnd = Matched.end();
4562 P != PEnd; ++P) {
4563 if (P != Best && getMoreSpecializedPartialSpecialization(
4564 P->Partial, Best->Partial,
4565 PointOfInstantiation) != Best->Partial) {
4566 AmbiguousPartialSpec = true;
4567 break;
4568 }
4569 }
4570 }
4571
4572 // Instantiate using the best variable template partial specialization.
4573 InstantiationPattern = Best->Partial;
4574 InstantiationArgs = Best->Args;
4575 } else {
4576 // -- If no match is found, the instantiation is generated
4577 // from the primary template.
4578 // InstantiationPattern = Template->getTemplatedDecl();
4579 }
4580
4581 // 2. Create the canonical declaration.
4582 // Note that we do not instantiate a definition until we see an odr-use
4583 // in DoMarkVarDeclReferenced().
4584 // FIXME: LateAttrs et al.?
4585 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4586 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
4587 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
4588 if (!Decl)
4589 return true;
4590
4591 if (AmbiguousPartialSpec) {
4592 // Partial ordering did not produce a clear winner. Complain.
4593 Decl->setInvalidDecl();
4594 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4595 << Decl;
4596
4597 // Print the matching partial specializations.
4598 for (MatchResult P : Matched)
4599 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4600 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4601 *P.Args);
4602 return true;
4603 }
4604
4605 if (VarTemplatePartialSpecializationDecl *D =
4606 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4607 Decl->setInstantiationOf(D, InstantiationArgs);
4608
4609 checkSpecializationVisibility(TemplateNameLoc, Decl);
4610
4611 assert(Decl && "No variable template specialization?")((Decl && "No variable template specialization?") ? static_cast
<void> (0) : __assert_fail ("Decl && \"No variable template specialization?\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 4611, __PRETTY_FUNCTION__))
;
4612 return Decl;
4613}
4614
4615ExprResult
4616Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
4617 const DeclarationNameInfo &NameInfo,
4618 VarTemplateDecl *Template, SourceLocation TemplateLoc,
4619 const TemplateArgumentListInfo *TemplateArgs) {
4620
4621 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4622 *TemplateArgs);
4623 if (Decl.isInvalid())
4624 return ExprError();
4625
4626 if (!Decl.get())
4627 return ExprResult();
4628
4629 VarDecl *Var = cast<VarDecl>(Decl.get());
4630 if (!Var->getTemplateSpecializationKind())
4631 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
4632 NameInfo.getLoc());
4633
4634 // Build an ordinary singleton decl ref.
4635 return BuildDeclarationNameExpr(SS, NameInfo, Var,
4636 /*FoundD=*/nullptr, TemplateArgs);
4637}
4638
4639void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4640 SourceLocation Loc) {
4641 Diag(Loc, diag::err_template_missing_args)
4642 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4643 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4644 Diag(TD->getLocation(), diag::note_template_decl_here)
4645 << TD->getTemplateParameters()->getSourceRange();
4646 }
4647}
4648
4649ExprResult
4650Sema::CheckConceptTemplateId(const CXXScopeSpec &SS,
4651 SourceLocation TemplateKWLoc,
4652 const DeclarationNameInfo &ConceptNameInfo,
4653 NamedDecl *FoundDecl,
4654 ConceptDecl *NamedConcept,
4655 const TemplateArgumentListInfo *TemplateArgs) {
4656 assert(NamedConcept && "A concept template id without a template?")((NamedConcept && "A concept template id without a template?"
) ? static_cast<void> (0) : __assert_fail ("NamedConcept && \"A concept template id without a template?\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 4656, __PRETTY_FUNCTION__))
;
4657
4658 llvm::SmallVector<TemplateArgument, 4> Converted;
4659 if (CheckTemplateArgumentList(NamedConcept, ConceptNameInfo.getLoc(),
4660 const_cast<TemplateArgumentListInfo&>(*TemplateArgs),
4661 /*PartialTemplateArgs=*/false, Converted,
4662 /*UpdateArgsWithConversion=*/false))
4663 return ExprError();
4664
4665 ConstraintSatisfaction Satisfaction;
4666 bool AreArgsDependent = false;
4667 for (TemplateArgument &Arg : Converted) {
4668 if (Arg.isDependent()) {
4669 AreArgsDependent = true;
4670 break;
4671 }
4672 }
4673 if (!AreArgsDependent &&
4674 CheckConstraintSatisfaction(NamedConcept,
4675 {NamedConcept->getConstraintExpr()},
4676 Converted,
4677 SourceRange(SS.isSet() ? SS.getBeginLoc() :
4678 ConceptNameInfo.getLoc(),
4679 TemplateArgs->getRAngleLoc()),
4680 Satisfaction))
4681 return ExprError();
4682
4683 return ConceptSpecializationExpr::Create(Context,
4684 SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc{},
4685 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4686 ASTTemplateArgumentListInfo::Create(Context, *TemplateArgs), Converted,
4687 AreArgsDependent ? nullptr : &Satisfaction);
4688}
4689
4690ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
4691 SourceLocation TemplateKWLoc,
4692 LookupResult &R,
4693 bool RequiresADL,
4694 const TemplateArgumentListInfo *TemplateArgs) {
4695 // FIXME: Can we do any checking at this point? I guess we could check the
4696 // template arguments that we have against the template name, if the template
4697 // name refers to a single template. That's not a terribly common case,
4698 // though.
4699 // foo<int> could identify a single function unambiguously
4700 // This approach does NOT work, since f<int>(1);
4701 // gets resolved prior to resorting to overload resolution
4702 // i.e., template<class T> void f(double);
4703 // vs template<class T, class U> void f(U);
4704
4705 // These should be filtered out by our callers.
4706 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid")((!R.isAmbiguous() && "ambiguous lookup when building templateid"
) ? static_cast<void> (0) : __assert_fail ("!R.isAmbiguous() && \"ambiguous lookup when building templateid\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 4706, __PRETTY_FUNCTION__))
;
4707
4708 // Non-function templates require a template argument list.
4709 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4710 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4711 diagnoseMissingTemplateArguments(TemplateName(TD), R.getNameLoc());
4712 return ExprError();
4713 }
4714 }
4715
4716 // In C++1y, check variable template ids.
4717 if (R.getAsSingle<VarTemplateDecl>()) {
4718 ExprResult Res = CheckVarTemplateId(SS, R.getLookupNameInfo(),
4719 R.getAsSingle<VarTemplateDecl>(),
4720 TemplateKWLoc, TemplateArgs);
4721 if (Res.isInvalid() || Res.isUsable())
4722 return Res;
4723 // Result is dependent. Carry on to build an UnresolvedLookupEpxr.
4724 }
4725
4726 if (R.getAsSingle<ConceptDecl>()) {
4727 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
4728 R.getFoundDecl(),
4729 R.getAsSingle<ConceptDecl>(), TemplateArgs);
4730 }
4731
4732 // We don't want lookup warnings at this point.
4733 R.suppressDiagnostics();
4734
4735 UnresolvedLookupExpr *ULE
4736 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
4737 SS.getWithLocInContext(Context),
4738 TemplateKWLoc,
4739 R.getLookupNameInfo(),
4740 RequiresADL, TemplateArgs,
4741 R.begin(), R.end());
4742
4743 return ULE;
4744}
4745
4746// We actually only call this from template instantiation.
4747ExprResult
4748Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
4749 SourceLocation TemplateKWLoc,
4750 const DeclarationNameInfo &NameInfo,
4751 const TemplateArgumentListInfo *TemplateArgs) {
4752
4753 assert(TemplateArgs || TemplateKWLoc.isValid())((TemplateArgs || TemplateKWLoc.isValid()) ? static_cast<void
> (0) : __assert_fail ("TemplateArgs || TemplateKWLoc.isValid()"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 4753, __PRETTY_FUNCTION__))
;
4754 DeclContext *DC;
4755 if (!(DC = computeDeclContext(SS, false)) ||
4756 DC->isDependentContext() ||
4757 RequireCompleteDeclContext(SS, DC))
4758 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
4759
4760 bool MemberOfUnknownSpecialization;
4761 LookupResult R(*this, NameInfo, LookupOrdinaryName);
4762 if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(),
4763 /*Entering*/false, MemberOfUnknownSpecialization,
4764 TemplateKWLoc))
4765 return ExprError();
4766
4767 if (R.isAmbiguous())
4768 return ExprError();
4769
4770 if (R.empty()) {
4771 Diag(NameInfo.getLoc(), diag::err_no_member)
4772 << NameInfo.getName() << DC << SS.getRange();
4773 return ExprError();
4774 }
4775
4776 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
4777 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
4778 << SS.getScopeRep()
4779 << NameInfo.getName().getAsString() << SS.getRange();
4780 Diag(Temp->getLocation(), diag::note_referenced_class_template);
4781 return ExprError();
4782 }
4783
4784 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
4785}
4786
4787/// Form a template name from a name that is syntactically required to name a
4788/// template, either due to use of the 'template' keyword or because a name in
4789/// this syntactic context is assumed to name a template (C++ [temp.names]p2-4).
4790///
4791/// This action forms a template name given the name of the template and its
4792/// optional scope specifier. This is used when the 'template' keyword is used
4793/// or when the parsing context unambiguously treats a following '<' as
4794/// introducing a template argument list. Note that this may produce a
4795/// non-dependent template name if we can perform the lookup now and identify
4796/// the named template.
4797///
4798/// For example, given "x.MetaFun::template apply", the scope specifier
4799/// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location
4800/// of the "template" keyword, and "apply" is the \p Name.
4801TemplateNameKind Sema::ActOnTemplateName(Scope *S,
4802 CXXScopeSpec &SS,
4803 SourceLocation TemplateKWLoc,
4804 const UnqualifiedId &Name,
4805 ParsedType ObjectType,
4806 bool EnteringContext,
4807 TemplateTy &Result,
4808 bool AllowInjectedClassName) {
4809 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4810 Diag(TemplateKWLoc,
4811 getLangOpts().CPlusPlus11 ?
4812 diag::warn_cxx98_compat_template_outside_of_template :
4813 diag::ext_template_outside_of_template)
4814 << FixItHint::CreateRemoval(TemplateKWLoc);
4815
4816 if (SS.isInvalid())
4817 return TNK_Non_template;
4818
4819 // Figure out where isTemplateName is going to look.
4820 DeclContext *LookupCtx = nullptr;
4821 if (SS.isNotEmpty())
4822 LookupCtx = computeDeclContext(SS, EnteringContext);
4823 else if (ObjectType)
4824 LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
4825
4826 // C++0x [temp.names]p5:
4827 // If a name prefixed by the keyword template is not the name of
4828 // a template, the program is ill-formed. [Note: the keyword
4829 // template may not be applied to non-template members of class
4830 // templates. -end note ] [ Note: as is the case with the
4831 // typename prefix, the template prefix is allowed in cases
4832 // where it is not strictly necessary; i.e., when the
4833 // nested-name-specifier or the expression on the left of the ->
4834 // or . is not dependent on a template-parameter, or the use
4835 // does not appear in the scope of a template. -end note]
4836 //
4837 // Note: C++03 was more strict here, because it banned the use of
4838 // the "template" keyword prior to a template-name that was not a
4839 // dependent name. C++ DR468 relaxed this requirement (the
4840 // "template" keyword is now permitted). We follow the C++0x
4841 // rules, even in C++03 mode with a warning, retroactively applying the DR.
4842 bool MemberOfUnknownSpecialization;
4843 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
4844 ObjectType, EnteringContext, Result,
4845 MemberOfUnknownSpecialization);
4846 if (TNK != TNK_Non_template) {
4847 // We resolved this to a (non-dependent) template name. Return it.
4848 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4849 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
4850 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4851 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
4852 // C++14 [class.qual]p2:
4853 // In a lookup in which function names are not ignored and the
4854 // nested-name-specifier nominates a class C, if the name specified
4855 // [...] is the injected-class-name of C, [...] the name is instead
4856 // considered to name the constructor
4857 //
4858 // We don't get here if naming the constructor would be valid, so we
4859 // just reject immediately and recover by treating the
4860 // injected-class-name as naming the template.
4861 Diag(Name.getBeginLoc(),
4862 diag::ext_out_of_line_qualified_id_type_names_constructor)
4863 << Name.Identifier
4864 << 0 /*injected-class-name used as template name*/
4865 << TemplateKWLoc.isValid();
4866 }
4867 return TNK;
4868 }
4869
4870 if (!MemberOfUnknownSpecialization) {
4871 // Didn't find a template name, and the lookup wasn't dependent.
4872 // Do the lookup again to determine if this is a "nothing found" case or
4873 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
4874 // need to do this.
4875 DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
4876 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
4877 LookupOrdinaryName);
4878 bool MOUS;
4879 // Tell LookupTemplateName that we require a template so that it diagnoses
4880 // cases where it finds a non-template.
4881 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
4882 ? RequiredTemplateKind(TemplateKWLoc)
4883 : TemplateNameIsRequired;
4884 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, MOUS,
4885 RTK, nullptr, /*AllowTypoCorrection=*/false) &&
4886 !R.isAmbiguous()) {
4887 if (LookupCtx)
4888 Diag(Name.getBeginLoc(), diag::err_no_member)
4889 << DNI.getName() << LookupCtx << SS.getRange();
4890 else
4891 Diag(Name.getBeginLoc(), diag::err_undeclared_use)
4892 << DNI.getName() << SS.getRange();
4893 }
4894 return TNK_Non_template;
4895 }
4896
4897 NestedNameSpecifier *Qualifier = SS.getScopeRep();
4898
4899 switch (Name.getKind()) {
4900 case UnqualifiedIdKind::IK_Identifier:
4901 Result = TemplateTy::make(
4902 Context.getDependentTemplateName(Qualifier, Name.Identifier));
4903 return TNK_Dependent_template_name;
4904
4905 case UnqualifiedIdKind::IK_OperatorFunctionId:
4906 Result = TemplateTy::make(Context.getDependentTemplateName(
4907 Qualifier, Name.OperatorFunctionId.Operator));
4908 return TNK_Function_template;
4909
4910 case UnqualifiedIdKind::IK_LiteralOperatorId:
4911 // This is a kind of template name, but can never occur in a dependent
4912 // scope (literal operators can only be declared at namespace scope).
4913 break;
4914
4915 default:
4916 break;
4917 }
4918
4919 // This name cannot possibly name a dependent template. Diagnose this now
4920 // rather than building a dependent template name that can never be valid.
4921 Diag(Name.getBeginLoc(),
4922 diag::err_template_kw_refers_to_dependent_non_template)
4923 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
4924 << TemplateKWLoc.isValid() << TemplateKWLoc;
4925 return TNK_Non_template;
4926}
4927
4928bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
4929 TemplateArgumentLoc &AL,
4930 SmallVectorImpl<TemplateArgument> &Converted) {
4931 const TemplateArgument &Arg = AL.getArgument();
4932 QualType ArgType;
4933 TypeSourceInfo *TSI = nullptr;
4934
4935 // Check template type parameter.
4936 switch(Arg.getKind()) {
4937 case TemplateArgument::Type:
4938 // C++ [temp.arg.type]p1:
4939 // A template-argument for a template-parameter which is a
4940 // type shall be a type-id.
4941 ArgType = Arg.getAsType();
4942 TSI = AL.getTypeSourceInfo();
4943 break;
4944 case TemplateArgument::Template:
4945 case TemplateArgument::TemplateExpansion: {
4946 // We have a template type parameter but the template argument
4947 // is a template without any arguments.
4948 SourceRange SR = AL.getSourceRange();
4949 TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
4950 diagnoseMissingTemplateArguments(Name, SR.getEnd());
4951 return true;
4952 }
4953 case TemplateArgument::Expression: {
4954 // We have a template type parameter but the template argument is an
4955 // expression; see if maybe it is missing the "typename" keyword.
4956 CXXScopeSpec SS;
4957 DeclarationNameInfo NameInfo;
4958
4959 if (DependentScopeDeclRefExpr *ArgExpr =
4960 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4961 SS.Adopt(ArgExpr->getQualifierLoc());
4962 NameInfo = ArgExpr->getNameInfo();
4963 } else if (CXXDependentScopeMemberExpr *ArgExpr =
4964 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
4965 if (ArgExpr->isImplicitAccess()) {
4966 SS.Adopt(ArgExpr->getQualifierLoc());
4967 NameInfo = ArgExpr->getMemberNameInfo();
4968 }
4969 }
4970
4971 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
4972 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4973 LookupParsedName(Result, CurScope, &SS);
4974
4975 if (Result.getAsSingle<TypeDecl>() ||
4976 Result.getResultKind() ==
4977 LookupResult::NotFoundInCurrentInstantiation) {
4978 assert(SS.getScopeRep() && "dependent scope expr must has a scope!")((SS.getScopeRep() && "dependent scope expr must has a scope!"
) ? static_cast<void> (0) : __assert_fail ("SS.getScopeRep() && \"dependent scope expr must has a scope!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 4978, __PRETTY_FUNCTION__))
;
4979 // Suggest that the user add 'typename' before the NNS.
4980 SourceLocation Loc = AL.getSourceRange().getBegin();
4981 Diag(Loc, getLangOpts().MSVCCompat
4982 ? diag::ext_ms_template_type_arg_missing_typename
4983 : diag::err_template_arg_must_be_type_suggest)
4984 << FixItHint::CreateInsertion(Loc, "typename ");
4985 Diag(Param->getLocation(), diag::note_template_param_here);
4986
4987 // Recover by synthesizing a type using the location information that we
4988 // already have.
4989 ArgType =
4990 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
4991 TypeLocBuilder TLB;
4992 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
4993 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4994 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4995 TL.setNameLoc(NameInfo.getLoc());
4996 TSI = TLB.getTypeSourceInfo(Context, ArgType);
4997
4998 // Overwrite our input TemplateArgumentLoc so that we can recover
4999 // properly.
5000 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
5001 TemplateArgumentLocInfo(TSI));
5002
5003 break;
5004 }
5005 }
5006 // fallthrough
5007 LLVM_FALLTHROUGH[[gnu::fallthrough]];
5008 }
5009 default: {
5010 // We have a template type parameter but the template argument
5011 // is not a type.
5012 SourceRange SR = AL.getSourceRange();
5013 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
5014 Diag(Param->getLocation(), diag::note_template_param_here);
5015
5016 return true;
5017 }
5018 }
5019
5020 if (CheckTemplateArgument(Param, TSI))
5021 return true;
5022
5023 // Add the converted template type argument.
5024 ArgType = Context.getCanonicalType(ArgType);
5025
5026 // Objective-C ARC:
5027 // If an explicitly-specified template argument type is a lifetime type
5028 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5029 if (getLangOpts().ObjCAutoRefCount &&
5030 ArgType->isObjCLifetimeType() &&
5031 !ArgType.getObjCLifetime()) {
5032 Qualifiers Qs;
5033 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
5034 ArgType = Context.getQualifiedType(ArgType, Qs);
5035 }
5036
5037 Converted.push_back(TemplateArgument(ArgType));
5038 return false;
5039}
5040
5041/// Substitute template arguments into the default template argument for
5042/// the given template type parameter.
5043///
5044/// \param SemaRef the semantic analysis object for which we are performing
5045/// the substitution.
5046///
5047/// \param Template the template that we are synthesizing template arguments
5048/// for.
5049///
5050/// \param TemplateLoc the location of the template name that started the
5051/// template-id we are checking.
5052///
5053/// \param RAngleLoc the location of the right angle bracket ('>') that
5054/// terminates the template-id.
5055///
5056/// \param Param the template template parameter whose default we are
5057/// substituting into.
5058///
5059/// \param Converted the list of template arguments provided for template
5060/// parameters that precede \p Param in the template parameter list.
5061/// \returns the substituted template argument, or NULL if an error occurred.
5062static TypeSourceInfo *
5063SubstDefaultTemplateArgument(Sema &SemaRef,
5064 TemplateDecl *Template,
5065 SourceLocation TemplateLoc,
5066 SourceLocation RAngleLoc,
5067 TemplateTypeParmDecl *Param,
5068 SmallVectorImpl<TemplateArgument> &Converted) {
5069 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
5070
5071 // If the argument type is dependent, instantiate it now based
5072 // on the previously-computed template arguments.
5073 if (ArgType->getType()->isInstantiationDependentType()) {
5074 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
5075 Param, Template, Converted,
5076 SourceRange(TemplateLoc, RAngleLoc));
5077 if (Inst.isInvalid())
5078 return nullptr;
5079
5080 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
5081
5082 // Only substitute for the innermost template argument list.
5083 MultiLevelTemplateArgumentList TemplateArgLists;
5084 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
5085 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5086 TemplateArgLists.addOuterTemplateArguments(None);
5087
5088 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5089 ArgType =
5090 SemaRef.SubstType(ArgType, TemplateArgLists,
5091 Param->getDefaultArgumentLoc(), Param->getDeclName());
5092 }
5093
5094 return ArgType;
5095}
5096
5097/// Substitute template arguments into the default template argument for
5098/// the given non-type template parameter.
5099///
5100/// \param SemaRef the semantic analysis object for which we are performing
5101/// the substitution.
5102///
5103/// \param Template the template that we are synthesizing template arguments
5104/// for.
5105///
5106/// \param TemplateLoc the location of the template name that started the
5107/// template-id we are checking.
5108///
5109/// \param RAngleLoc the location of the right angle bracket ('>') that
5110/// terminates the template-id.
5111///
5112/// \param Param the non-type template parameter whose default we are
5113/// substituting into.
5114///
5115/// \param Converted the list of template arguments provided for template
5116/// parameters that precede \p Param in the template parameter list.
5117///
5118/// \returns the substituted template argument, or NULL if an error occurred.
5119static ExprResult
5120SubstDefaultTemplateArgument(Sema &SemaRef,
5121 TemplateDecl *Template,
5122 SourceLocation TemplateLoc,
5123 SourceLocation RAngleLoc,
5124 NonTypeTemplateParmDecl *Param,
5125 SmallVectorImpl<TemplateArgument> &Converted) {
5126 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
5127 Param, Template, Converted,
5128 SourceRange(TemplateLoc, RAngleLoc));
5129 if (Inst.isInvalid())
5130 return ExprError();
5131
5132 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
5133
5134 // Only substitute for the innermost template argument list.
5135 MultiLevelTemplateArgumentList TemplateArgLists;
5136 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
5137 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5138 TemplateArgLists.addOuterTemplateArguments(None);
5139
5140 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5141 EnterExpressionEvaluationContext ConstantEvaluated(
5142 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5143 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
5144}
5145
5146/// Substitute template arguments into the default template argument for
5147/// the given template template parameter.
5148///
5149/// \param SemaRef the semantic analysis object for which we are performing
5150/// the substitution.
5151///
5152/// \param Template the template that we are synthesizing template arguments
5153/// for.
5154///
5155/// \param TemplateLoc the location of the template name that started the
5156/// template-id we are checking.
5157///
5158/// \param RAngleLoc the location of the right angle bracket ('>') that
5159/// terminates the template-id.
5160///
5161/// \param Param the template template parameter whose default we are
5162/// substituting into.
5163///
5164/// \param Converted the list of template arguments provided for template
5165/// parameters that precede \p Param in the template parameter list.
5166///
5167/// \param QualifierLoc Will be set to the nested-name-specifier (with
5168/// source-location information) that precedes the template name.
5169///
5170/// \returns the substituted template argument, or NULL if an error occurred.
5171static TemplateName
5172SubstDefaultTemplateArgument(Sema &SemaRef,
5173 TemplateDecl *Template,
5174 SourceLocation TemplateLoc,
5175 SourceLocation RAngleLoc,
5176 TemplateTemplateParmDecl *Param,
5177 SmallVectorImpl<TemplateArgument> &Converted,
5178 NestedNameSpecifierLoc &QualifierLoc) {
5179 Sema::InstantiatingTemplate Inst(
5180 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
5181 SourceRange(TemplateLoc, RAngleLoc));
5182 if (Inst.isInvalid())
5183 return TemplateName();
5184
5185 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
5186
5187 // Only substitute for the innermost template argument list.
5188 MultiLevelTemplateArgumentList TemplateArgLists;
5189 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
5190 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5191 TemplateArgLists.addOuterTemplateArguments(None);
5192
5193 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5194 // Substitute into the nested-name-specifier first,
5195 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
5196 if (QualifierLoc) {
5197 QualifierLoc =
5198 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
5199 if (!QualifierLoc)
5200 return TemplateName();
5201 }
5202
5203 return SemaRef.SubstTemplateName(
5204 QualifierLoc,
5205 Param->getDefaultArgument().getArgument().getAsTemplate(),
5206 Param->getDefaultArgument().getTemplateNameLoc(),
5207 TemplateArgLists);
5208}
5209
5210/// If the given template parameter has a default template
5211/// argument, substitute into that default template argument and
5212/// return the corresponding template argument.
5213TemplateArgumentLoc
5214Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
5215 SourceLocation TemplateLoc,
5216 SourceLocation RAngleLoc,
5217 Decl *Param,
5218 SmallVectorImpl<TemplateArgument>
5219 &Converted,
5220 bool &HasDefaultArg) {
5221 HasDefaultArg = false;
5222
5223 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
5224 if (!hasVisibleDefaultArgument(TypeParm))
5225 return TemplateArgumentLoc();
5226
5227 HasDefaultArg = true;
5228 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
5229 TemplateLoc,
5230 RAngleLoc,
5231 TypeParm,
5232 Converted);
5233 if (DI)
5234 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
5235
5236 return TemplateArgumentLoc();
5237 }
5238
5239 if (NonTypeTemplateParmDecl *NonTypeParm
5240 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5241 if (!hasVisibleDefaultArgument(NonTypeParm))
5242 return TemplateArgumentLoc();
5243
5244 HasDefaultArg = true;
5245 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
5246 TemplateLoc,
5247 RAngleLoc,
5248 NonTypeParm,
5249 Converted);
5250 if (Arg.isInvalid())
5251 return TemplateArgumentLoc();
5252
5253 Expr *ArgE = Arg.getAs<Expr>();
5254 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
5255 }
5256
5257 TemplateTemplateParmDecl *TempTempParm
5258 = cast<TemplateTemplateParmDecl>(Param);
5259 if (!hasVisibleDefaultArgument(TempTempParm))
5260 return TemplateArgumentLoc();
5261
5262 HasDefaultArg = true;
5263 NestedNameSpecifierLoc QualifierLoc;
5264 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
5265 TemplateLoc,
5266 RAngleLoc,
5267 TempTempParm,
5268 Converted,
5269 QualifierLoc);
5270 if (TName.isNull())
5271 return TemplateArgumentLoc();
5272
5273 return TemplateArgumentLoc(
5274 Context, TemplateArgument(TName),
5275 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
5276 TempTempParm->getDefaultArgument().getTemplateNameLoc());
5277}
5278
5279/// Convert a template-argument that we parsed as a type into a template, if
5280/// possible. C++ permits injected-class-names to perform dual service as
5281/// template template arguments and as template type arguments.
5282static TemplateArgumentLoc
5283convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc) {
5284 // Extract and step over any surrounding nested-name-specifier.
5285 NestedNameSpecifierLoc QualLoc;
5286 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
5287 if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
5288 return TemplateArgumentLoc();
5289
5290 QualLoc = ETLoc.getQualifierLoc();
5291 TLoc = ETLoc.getNamedTypeLoc();
5292 }
5293 // If this type was written as an injected-class-name, it can be used as a
5294 // template template argument.
5295 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
5296 return TemplateArgumentLoc(Context, InjLoc.getTypePtr()->getTemplateName(),
5297 QualLoc, InjLoc.getNameLoc());
5298
5299 // If this type was written as an injected-class-name, it may have been
5300 // converted to a RecordType during instantiation. If the RecordType is
5301 // *not* wrapped in a TemplateSpecializationType and denotes a class
5302 // template specialization, it must have come from an injected-class-name.
5303 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
5304 if (auto *CTSD =
5305 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
5306 return TemplateArgumentLoc(Context,
5307 TemplateName(CTSD->getSpecializedTemplate()),
5308 QualLoc, RecLoc.getNameLoc());
5309
5310 return TemplateArgumentLoc();
5311}
5312
5313/// Check that the given template argument corresponds to the given
5314/// template parameter.
5315///
5316/// \param Param The template parameter against which the argument will be
5317/// checked.
5318///
5319/// \param Arg The template argument, which may be updated due to conversions.
5320///
5321/// \param Template The template in which the template argument resides.
5322///
5323/// \param TemplateLoc The location of the template name for the template
5324/// whose argument list we're matching.
5325///
5326/// \param RAngleLoc The location of the right angle bracket ('>') that closes
5327/// the template argument list.
5328///
5329/// \param ArgumentPackIndex The index into the argument pack where this
5330/// argument will be placed. Only valid if the parameter is a parameter pack.
5331///
5332/// \param Converted The checked, converted argument will be added to the
5333/// end of this small vector.
5334///
5335/// \param CTAK Describes how we arrived at this particular template argument:
5336/// explicitly written, deduced, etc.
5337///
5338/// \returns true on error, false otherwise.
5339bool Sema::CheckTemplateArgument(NamedDecl *Param,
5340 TemplateArgumentLoc &Arg,
5341 NamedDecl *Template,
5342 SourceLocation TemplateLoc,
5343 SourceLocation RAngleLoc,
5344 unsigned ArgumentPackIndex,
5345 SmallVectorImpl<TemplateArgument> &Converted,
5346 CheckTemplateArgumentKind CTAK) {
5347 // Check template type parameters.
5348 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5349 return CheckTemplateTypeArgument(TTP, Arg, Converted);
5350
5351 // Check non-type template parameters.
5352 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5353 // Do substitution on the type of the non-type template parameter
5354 // with the template arguments we've seen thus far. But if the
5355 // template has a dependent context then we cannot substitute yet.
5356 QualType NTTPType = NTTP->getType();
5357 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5358 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5359
5360 if (NTTPType->isInstantiationDependentType() &&
5361 !isa<TemplateTemplateParmDecl>(Template) &&
5362 !Template->getDeclContext()->isDependentContext()) {
5363 // Do substitution on the type of the non-type template parameter.
5364 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
5365 NTTP, Converted,
5366 SourceRange(TemplateLoc, RAngleLoc));
5367 if (Inst.isInvalid())
5368 return true;
5369
5370 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
5371 Converted);
5372
5373 // If the parameter is a pack expansion, expand this slice of the pack.
5374 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5375 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this,
5376 ArgumentPackIndex);
5377 NTTPType = SubstType(PET->getPattern(),
5378 MultiLevelTemplateArgumentList(TemplateArgs),
5379 NTTP->getLocation(),
5380 NTTP->getDeclName());
5381 } else {
5382 NTTPType = SubstType(NTTPType,
5383 MultiLevelTemplateArgumentList(TemplateArgs),
5384 NTTP->getLocation(),
5385 NTTP->getDeclName());
5386 }
5387
5388 // If that worked, check the non-type template parameter type
5389 // for validity.
5390 if (!NTTPType.isNull())
5391 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5392 NTTP->getLocation());
5393 if (NTTPType.isNull())
5394 return true;
5395 }
5396
5397 switch (Arg.getArgument().getKind()) {
5398 case TemplateArgument::Null:
5399 llvm_unreachable("Should never see a NULL template argument here")::llvm::llvm_unreachable_internal("Should never see a NULL template argument here"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 5399)
;
5400
5401 case TemplateArgument::Expression: {
5402 TemplateArgument Result;
5403 unsigned CurSFINAEErrors = NumSFINAEErrors;
5404 ExprResult Res =
5405 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
5406 Result, CTAK);
5407 if (Res.isInvalid())
5408 return true;
5409 // If the current template argument causes an error, give up now.
5410 if (CurSFINAEErrors < NumSFINAEErrors)
5411 return true;
5412
5413 // If the resulting expression is new, then use it in place of the
5414 // old expression in the template argument.
5415 if (Res.get() != Arg.getArgument().getAsExpr()) {
5416 TemplateArgument TA(Res.get());
5417 Arg = TemplateArgumentLoc(TA, Res.get());
5418 }
5419
5420 Converted.push_back(Result);
5421 break;
5422 }
5423
5424 case TemplateArgument::Declaration:
5425 case TemplateArgument::Integral:
5426 case TemplateArgument::NullPtr:
5427 // We've already checked this template argument, so just copy
5428 // it to the list of converted arguments.
5429 Converted.push_back(Arg.getArgument());
5430 break;
5431
5432 case TemplateArgument::Template:
5433 case TemplateArgument::TemplateExpansion:
5434 // We were given a template template argument. It may not be ill-formed;
5435 // see below.
5436 if (DependentTemplateName *DTN
5437 = Arg.getArgument().getAsTemplateOrTemplatePattern()
5438 .getAsDependentTemplateName()) {
5439 // We have a template argument such as \c T::template X, which we
5440 // parsed as a template template argument. However, since we now
5441 // know that we need a non-type template argument, convert this
5442 // template name into an expression.
5443
5444 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
5445 Arg.getTemplateNameLoc());
5446
5447 CXXScopeSpec SS;
5448 SS.Adopt(Arg.getTemplateQualifierLoc());
5449 // FIXME: the template-template arg was a DependentTemplateName,
5450 // so it was provided with a template keyword. However, its source
5451 // location is not stored in the template argument structure.
5452 SourceLocation TemplateKWLoc;
5453 ExprResult E = DependentScopeDeclRefExpr::Create(
5454 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5455 nullptr);
5456
5457 // If we parsed the template argument as a pack expansion, create a
5458 // pack expansion expression.
5459 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
5460 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
5461 if (E.isInvalid())
5462 return true;
5463 }
5464
5465 TemplateArgument Result;
5466 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
5467 if (E.isInvalid())
5468 return true;
5469
5470 Converted.push_back(Result);
5471 break;
5472 }
5473
5474 // We have a template argument that actually does refer to a class
5475 // template, alias template, or template template parameter, and
5476 // therefore cannot be a non-type template argument.
5477 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
5478 << Arg.getSourceRange();
5479
5480 Diag(Param->getLocation(), diag::note_template_param_here);
5481 return true;
5482
5483 case TemplateArgument::Type: {
5484 // We have a non-type template parameter but the template
5485 // argument is a type.
5486
5487 // C++ [temp.arg]p2:
5488 // In a template-argument, an ambiguity between a type-id and
5489 // an expression is resolved to a type-id, regardless of the
5490 // form of the corresponding template-parameter.
5491 //
5492 // We warn specifically about this case, since it can be rather
5493 // confusing for users.
5494 QualType T = Arg.getArgument().getAsType();
5495 SourceRange SR = Arg.getSourceRange();
5496 if (T->isFunctionType())
5497 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5498 else
5499 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5500 Diag(Param->getLocation(), diag::note_template_param_here);
5501 return true;
5502 }
5503
5504 case TemplateArgument::Pack:
5505 llvm_unreachable("Caller must expand template argument packs")::llvm::llvm_unreachable_internal("Caller must expand template argument packs"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 5505)
;
5506 }
5507
5508 return false;
5509 }
5510
5511
5512 // Check template template parameters.
5513 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
5514
5515 TemplateParameterList *Params = TempParm->getTemplateParameters();
5516 if (TempParm->isExpandedParameterPack())
5517 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5518
5519 // Substitute into the template parameter list of the template
5520 // template parameter, since previously-supplied template arguments
5521 // may appear within the template template parameter.
5522 //
5523 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5524 {
5525 // Set up a template instantiation context.
5526 LocalInstantiationScope Scope(*this);
5527 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
5528 TempParm, Converted,
5529 SourceRange(TemplateLoc, RAngleLoc));
5530 if (Inst.isInvalid())
5531 return true;
5532
5533 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
5534 Params = SubstTemplateParams(Params, CurContext,
5535 MultiLevelTemplateArgumentList(TemplateArgs));
5536 if (!Params)
5537 return true;
5538 }
5539
5540 // C++1z [temp.local]p1: (DR1004)
5541 // When [the injected-class-name] is used [...] as a template-argument for
5542 // a template template-parameter [...] it refers to the class template
5543 // itself.
5544 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
5545 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
5546 Context, Arg.getTypeSourceInfo()->getTypeLoc());
5547 if (!ConvertedArg.getArgument().isNull())
5548 Arg = ConvertedArg;
5549 }
5550
5551 switch (Arg.getArgument().getKind()) {
5552 case TemplateArgument::Null:
5553 llvm_unreachable("Should never see a NULL template argument here")::llvm::llvm_unreachable_internal("Should never see a NULL template argument here"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 5553)
;
5554
5555 case TemplateArgument::Template:
5556 case TemplateArgument::TemplateExpansion:
5557 if (CheckTemplateTemplateArgument(TempParm, Params, Arg))
5558 return true;
5559
5560 Converted.push_back(Arg.getArgument());
5561 break;
5562
5563 case TemplateArgument::Expression:
5564 case TemplateArgument::Type:
5565 // We have a template template parameter but the template
5566 // argument does not refer to a template.
5567 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
5568 << getLangOpts().CPlusPlus11;
5569 return true;
5570
5571 case TemplateArgument::Declaration:
5572 llvm_unreachable("Declaration argument with template template parameter")::llvm::llvm_unreachable_internal("Declaration argument with template template parameter"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 5572)
;
5573 case TemplateArgument::Integral:
5574 llvm_unreachable("Integral argument with template template parameter")::llvm::llvm_unreachable_internal("Integral argument with template template parameter"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 5574)
;
5575 case TemplateArgument::NullPtr:
5576 llvm_unreachable("Null pointer argument with template template parameter")::llvm::llvm_unreachable_internal("Null pointer argument with template template parameter"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 5576)
;
5577
5578 case TemplateArgument::Pack:
5579 llvm_unreachable("Caller must expand template argument packs")::llvm::llvm_unreachable_internal("Caller must expand template argument packs"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 5579)
;
5580 }
5581
5582 return false;
5583}
5584
5585/// Check whether the template parameter is a pack expansion, and if so,
5586/// determine the number of parameters produced by that expansion. For instance:
5587///
5588/// \code
5589/// template<typename ...Ts> struct A {
5590/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
5591/// };
5592/// \endcode
5593///
5594/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
5595/// is not a pack expansion, so returns an empty Optional.
5596static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
5597 if (TemplateTypeParmDecl *TTP
5598 = dyn_cast<TemplateTypeParmDecl>(Param)) {
5599 if (TTP->isExpandedParameterPack())
5600 return TTP->getNumExpansionParameters();
5601 }
5602
5603 if (NonTypeTemplateParmDecl *NTTP
5604 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5605 if (NTTP->isExpandedParameterPack())
5606 return NTTP->getNumExpansionTypes();
5607 }
5608
5609 if (TemplateTemplateParmDecl *TTP
5610 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
5611 if (TTP->isExpandedParameterPack())
5612 return TTP->getNumExpansionTemplateParameters();
5613 }
5614
5615 return None;
5616}
5617
5618/// Diagnose a missing template argument.
5619template<typename TemplateParmDecl>
5620static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
5621 TemplateDecl *TD,
5622 const TemplateParmDecl *D,
5623 TemplateArgumentListInfo &Args) {
5624 // Dig out the most recent declaration of the template parameter; there may be
5625 // declarations of the template that are more recent than TD.
5626 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
5627 ->getTemplateParameters()
5628 ->getParam(D->getIndex()));
5629
5630 // If there's a default argument that's not visible, diagnose that we're
5631 // missing a module import.
5632 llvm::SmallVector<Module*, 8> Modules;
5633 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
5634 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
5635 D->getDefaultArgumentLoc(), Modules,
5636 Sema::MissingImportKind::DefaultArgument,
5637 /*Recover*/true);
5638 return true;
5639 }
5640
5641 // FIXME: If there's a more recent default argument that *is* visible,
5642 // diagnose that it was declared too late.
5643
5644 TemplateParameterList *Params = TD->getTemplateParameters();
5645
5646 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5647 << /*not enough args*/0
5648 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD))
5649 << TD;
5650 S.Diag(TD->getLocation(), diag::note_template_decl_here)
5651 << Params->getSourceRange();
5652 return true;
5653}
5654
5655/// Check that the given template argument list is well-formed
5656/// for specializing the given template.
5657bool Sema::CheckTemplateArgumentList(
5658 TemplateDecl *Template, SourceLocation TemplateLoc,
5659 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
5660 SmallVectorImpl<TemplateArgument> &Converted,
5661 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5662
5663 if (ConstraintsNotSatisfied)
5664 *ConstraintsNotSatisfied = false;
5665
5666 // Make a copy of the template arguments for processing. Only make the
5667 // changes at the end when successful in matching the arguments to the
5668 // template.
5669 TemplateArgumentListInfo NewArgs = TemplateArgs;
5670
5671 // Make sure we get the template parameter list from the most
5672 // recentdeclaration, since that is the only one that has is guaranteed to
5673 // have all the default template argument information.
5674 TemplateParameterList *Params =
5675 cast<TemplateDecl>(Template->getMostRecentDecl())
5676 ->getTemplateParameters();
5677
5678 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5679
5680 // C++ [temp.arg]p1:
5681 // [...] The type and form of each template-argument specified in
5682 // a template-id shall match the type and form specified for the
5683 // corresponding parameter declared by the template in its
5684 // template-parameter-list.
5685 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5686 SmallVector<TemplateArgument, 2> ArgumentPack;
5687 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5688 LocalInstantiationScope InstScope(*this, true);
5689 for (TemplateParameterList::iterator Param = Params->begin(),
5690 ParamEnd = Params->end();
5691 Param != ParamEnd; /* increment in loop */) {
5692 // If we have an expanded parameter pack, make sure we don't have too
5693 // many arguments.
5694 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
5695 if (*Expansions == ArgumentPack.size()) {
5696 // We're done with this parameter pack. Pack up its arguments and add
5697 // them to the list.
5698 Converted.push_back(
5699 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5700 ArgumentPack.clear();
5701
5702 // This argument is assigned to the next parameter.
5703 ++Param;
5704 continue;
5705 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5706 // Not enough arguments for this parameter pack.
5707 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5708 << /*not enough args*/0
5709 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5710 << Template;
5711 Diag(Template->getLocation(), diag::note_template_decl_here)
5712 << Params->getSourceRange();
5713 return true;
5714 }
5715 }
5716
5717 if (ArgIdx < NumArgs) {
5718 // Check the template argument we were given.
5719 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
5720 TemplateLoc, RAngleLoc,
5721 ArgumentPack.size(), Converted))
5722 return true;
5723
5724 bool PackExpansionIntoNonPack =
5725 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
5726 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
5727 if (PackExpansionIntoNonPack && (isa<TypeAliasTemplateDecl>(Template) ||
5728 isa<ConceptDecl>(Template))) {
5729 // Core issue 1430: we have a pack expansion as an argument to an
5730 // alias template, and it's not part of a parameter pack. This
5731 // can't be canonicalized, so reject it now.
5732 // As for concepts - we cannot normalize constraints where this
5733 // situation exists.
5734 Diag(NewArgs[ArgIdx].getLocation(),
5735 diag::err_template_expansion_into_fixed_list)
5736 << (isa<ConceptDecl>(Template) ? 1 : 0)
5737 << NewArgs[ArgIdx].getSourceRange();
5738 Diag((*Param)->getLocation(), diag::note_template_param_here);
5739 return true;
5740 }
5741
5742 // We're now done with this argument.
5743 ++ArgIdx;
5744
5745 if ((*Param)->isTemplateParameterPack()) {
5746 // The template parameter was a template parameter pack, so take the
5747 // deduced argument and place it on the argument pack. Note that we
5748 // stay on the same template parameter so that we can deduce more
5749 // arguments.
5750 ArgumentPack.push_back(Converted.pop_back_val());
5751 } else {
5752 // Move to the next template parameter.
5753 ++Param;
5754 }
5755
5756 // If we just saw a pack expansion into a non-pack, then directly convert
5757 // the remaining arguments, because we don't know what parameters they'll
5758 // match up with.
5759 if (PackExpansionIntoNonPack) {
5760 if (!ArgumentPack.empty()) {
5761 // If we were part way through filling in an expanded parameter pack,
5762 // fall back to just producing individual arguments.
5763 Converted.insert(Converted.end(),
5764 ArgumentPack.begin(), ArgumentPack.end());
5765 ArgumentPack.clear();
5766 }
5767
5768 while (ArgIdx < NumArgs) {
5769 Converted.push_back(NewArgs[ArgIdx].getArgument());
5770 ++ArgIdx;
5771 }
5772
5773 return false;
5774 }
5775
5776 continue;
5777 }
5778
5779 // If we're checking a partial template argument list, we're done.
5780 if (PartialTemplateArgs) {
5781 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
5782 Converted.push_back(
5783 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5784 return false;
5785 }
5786
5787 // If we have a template parameter pack with no more corresponding
5788 // arguments, just break out now and we'll fill in the argument pack below.
5789 if ((*Param)->isTemplateParameterPack()) {
5790 assert(!getExpandedPackSize(*Param) &&((!getExpandedPackSize(*Param) && "Should have dealt with this already"
) ? static_cast<void> (0) : __assert_fail ("!getExpandedPackSize(*Param) && \"Should have dealt with this already\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 5791, __PRETTY_FUNCTION__))
5791 "Should have dealt with this already")((!getExpandedPackSize(*Param) && "Should have dealt with this already"
) ? static_cast<void> (0) : __assert_fail ("!getExpandedPackSize(*Param) && \"Should have dealt with this already\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaTemplate.cpp"
, 5791, __PRETTY_FUNCTION__))
;
5792
5793 // A non-expanded parameter pack before the end of the parameter list
5794 // only occurs for an ill-formed template parameter list, unless we've
5795 // got a partial argument list for a function template, so just bail out.
5796 if (Param + 1 != ParamEnd)
5797 return true;
5798
5799 Converted.push_back(
5800 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5801 ArgumentPack.clear();
5802
5803 ++Param;
5804 continue;
5805 }
5806
5807 // Check whether we have a default argument.
5808 TemplateArgumentLoc Arg;
5809
5810 // Retrieve the default template argument from the template
5811 // parameter. For each kind of template parameter, we substitute the
5812 // template arguments provided thus far and any "outer" template arguments
5813 // (when the template parameter was part of a nested template) into
5814 // the default argument.
5815 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
5816 if (!hasVisibleDefaultArgument(TTP))
5817 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
5818 NewArgs);
5819
5820 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
5821 Template,
5822 TemplateLoc,
5823 RAngleLoc,
5824 TTP,
5825 Converted);
5826 if (!ArgType)
5827 return true;
5828
5829 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
5830 ArgType);
5831 } else if (NonTypeTemplateParmDecl *NTTP
5832 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
5833 if (!hasVisibleDefaultArgument(NTTP))
5834 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
5835 NewArgs);
5836
5837 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
5838 TemplateLoc,
5839 RAngleLoc,
5840 NTTP,
5841 Converted);
5842 if (E.isInvalid())
5843 return true;
5844
5845 Expr *Ex = E.getAs<Expr>();
5846 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
5847 } else {
5848 TemplateTemplateParmDecl *TempParm
5849 = cast<TemplateTemplateParmDecl>(*Param);
5850
5851 if (!hasVisibleDefaultArgument(TempParm))
5852 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
5853 NewArgs);
5854
5855 NestedNameSpecifierLoc QualifierLoc;
5856 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
5857 TemplateLoc,
5858 RAngleLoc,
5859 TempParm,
5860 Converted,
5861 QualifierLoc);
5862 if (Name.isNull())
5863 return true;
5864
5865 Arg = TemplateArgumentLoc(
5866 Context, TemplateArgument(Name), QualifierLoc,
5867 TempParm->getDefaultArgument().getTemplateNameLoc());
5868 }
5869
5870 // Introduce an instantiation record that describes where we are using
5871 // the default template argument. We're not actually instantiating a
5872 // template here, we just create this object to put a note into the
5873 // context stack.
5874 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
5875 SourceRange(TemplateLoc, RAngleLoc));
5876 if (Inst.isInvalid())
5877 return true;
5878
5879 // Check the default template argument.
5880 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
5881 RAngleLoc, 0, Converted))
5882 return true;
5883
5884 // Core issue 150 (assumed resolution): if this is a template template
5885 // parameter, keep track of the default template arguments from the
5886 // template definition.
5887 if (isTemplateTemplateParameter)
5888 NewArgs.addArgument(Arg);
5889
5890 // Move to the next template parameter and argument.
5891 ++Param;
5892 ++ArgIdx;
5893 }
5894
5895 // If we're performing a partial argument substitution, allow any trailing
5896 // pack expansions; they might be empty. This can happen even if
5897 // PartialTemplateArgs is false (the list of arguments is complete but
5898 // still dependent).
5899 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5900 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
5901 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
5902 Converted.push_back(NewArgs[ArgIdx++].getArgument());
5903 }
5904
5905 // If we have any leftover arguments, then there were too many arguments.
5906 // Complain and fail.
5907 if (ArgIdx < NumArgs) {
5908 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5909 << /*too many args*/1
5910 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5911 << Template
5912 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
5913 Diag(Template->getLocation(), diag::note_template_decl_here)
5914 << Params->getSourceRange();
5915 return true;
5916 }
5917
5918 // No problems found with the new argument list, propagate changes back
5919 // to caller.
5920 if (UpdateArgsWithConversions)
5921 TemplateArgs = std::move(NewArgs);
5922
5923 if (!PartialTemplateArgs &&
5924 EnsureTemplateArgumentListConstraints(
5925 Template, Converted, SourceRange(TemplateLoc,
5926 TemplateArgs.getRAngleLoc()))) {
5927 if (ConstraintsNotSatisfied)
5928 *ConstraintsNotSatisfied = true;
5929 return true;
5930 }
5931
5932 return false;
5933}
5934
5935namespace {
5936 class UnnamedLocalNoLinkageFinder
5937 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
5938 {
5939 Sema &S;
5940 SourceRange SR;
5941
5942 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
5943
5944 public:
5945 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5946
5947 bool Visit(QualType T) {
5948 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
5949 }
5950
5951#define TYPE(Class, Parent) \
5952 bool Visit##Class##Type(const Class##Type *);
5953#define ABSTRACT_TYPE(Class, Parent) \
5954 bool Visit##Class##Type(const Class##Type *) { return false; }
5955#define NON_CANONICAL_TYPE(Class, Parent) \
5956 bool Visit##Class##Type(const Class##Type *) { return false; }
5957#include "clang/AST/TypeNodes.inc"
5958
5959 bool VisitTagDecl(const TagDecl *Tag);
5960 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5961 };
5962} // end anonymous namespace
5963
5964bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
5965 return false;
5966}
5967
5968bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5969 return Visit(T->getElementType());
5970}
5971
5972bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
5973 return Visit(T->getPointeeType());
5974}
5975
5976bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
5977 const BlockPointerType* T) {
5978 return Visit(T->getPointeeType());
5979}
5980
5981bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
5982 const LValueReferenceType* T) {
5983 return Visit(T->getPointeeType());
5984}
5985
5986bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
5987 const RValueReferenceType* T) {
5988 return Visit(T->getPointeeType());
5989}
5990
5991bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
5992 const MemberPointerType* T) {
5993 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5994}
5995
5996bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
5997 const ConstantArrayType* T) {
5998 return Visit(T->getElementType());
5999}
6000
6001bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6002 const IncompleteArrayType* T) {
6003 return Visit(T->getElementType());
6004}
6005
6006bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6007 const VariableArrayType* T) {
6008 return Visit(T->getElementType());
6009}
6010
6011bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6012 const DependentSizedArrayType* T) {
6013 return Visit(T->getElementType());
6014}
6015
6016bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6017 const DependentSizedExtVectorType* T) {
6018 return Visit(T->getElementType());
6019}
6020
6021bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6022 const DependentSizedMatrixType *T) {
6023 return Visit(T->getElementType());
6024}
6025
6026bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6027 const DependentAddressSpaceType *T) {
6028 return Visit(T->getPointeeType());
6029}
6030
6031bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6032 return Visit(T->getElementType());
6033}
6034
6035bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6036 const DependentVectorType *T) {
6037