Bug Summary

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