Bug Summary

File:tools/clang/include/clang/AST/DeclTemplate.h
Warning:line 2659, column 31
Access to field 'PartialSpecialization' results in a dereference of a null pointer (loaded from variable 'PS')

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 -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-8/lib/clang/8.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-8~svn350071/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include -I /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/include -I /build/llvm-toolchain-snapshot-8~svn350071/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/include/clang/8.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-8/lib/clang/8.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++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-8~svn350071=. -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 -o /tmp/scan-build-2018-12-27-042839-1215-1 -x c++ /build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaTemplate.cpp -faddrsig

/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaTemplate.cpp

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