Bug Summary

File:tools/clang/lib/Sema/SemaTemplate.cpp
Warning:line 6753, column 8
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name 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 -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn373517/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn373517=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-10-02-234743-9763-1 -x c++ /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp

/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp

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