blob: fd66c798654abe8be40c39471d04db5ebea5a4f2 [file] [log] [blame]
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
Douglas Gregor5101c242008-12-05 18:15:24 +00002//
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.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007//===----------------------------------------------------------------------===//
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010//===----------------------------------------------------------------------===//
Douglas Gregor5101c242008-12-05 18:15:24 +000011
Douglas Gregor15acfb92009-08-06 16:20:37 +000012#include "TreeTransform.h"
Larisse Voufo39a1e502013-08-06 01:03:05 +000013#include "clang/AST/ASTConsumer.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000014#include "clang/AST/ASTContext.h"
John McCallbbbbe4e2010-03-11 07:50:04 +000015#include "clang/AST/DeclFriend.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000016#include "clang/AST/DeclTemplate.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
John McCalla020a012010-10-20 05:44:58 +000019#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor7731d3f2010-10-13 00:27:52 +000020#include "clang/AST/TypeVisitor.h"
David Majnemerd9b1a4f2015-11-04 03:40:30 +000021#include "clang/Basic/Builtins.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000022#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000023#include "clang/Basic/PartialDiagnostic.h"
David Majnemer763584d2014-02-06 10:59:19 +000024#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#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"
Benjamin Kramere0513cb2012-01-30 16:17:39 +000032#include "llvm/ADT/SmallBitVector.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000033#include "llvm/ADT/SmallString.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000034#include "llvm/ADT/StringExtras.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000035
Eric Fiselier6ad68552016-07-01 01:24:09 +000036#include <iterator>
Douglas Gregor5101c242008-12-05 18:15:24 +000037using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000038using namespace sema;
Douglas Gregor5101c242008-12-05 18:15:24 +000039
John McCall9b72f892010-11-10 02:40:36 +000040// 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
Hubert Tong5a8ec4e2017-02-10 02:46:19 +000048namespace clang {
49/// \brief [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.");
65 return Params->getRequiresClause();
66}
67
Douglas Gregorb7bfe792009-09-02 22:59:36 +000068/// \brief 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.
John McCalle9cccd82010-06-16 08:42:20 +000071static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000072 NamedDecl *Orig,
73 bool AllowFunctionTemplates) {
John McCalle9cccd82010-06-16 08:42:20 +000074 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +000075
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000076 if (isa<TemplateDecl>(D)) {
77 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +000078 return nullptr;
79
John McCalle9cccd82010-06-16 08:42:20 +000080 return Orig;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000081 }
Mike Stump11289f42009-09-09 15:08:12 +000082
Douglas Gregorb7bfe792009-09-02 22:59:36 +000083 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()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000096 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000097 if (Record->getDescribedClassTemplate())
98 return Record->getDescribedClassTemplate();
99
100 if (ClassTemplateSpecializationDecl *Spec
101 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
102 return Spec->getSpecializedTemplate();
103 }
Mike Stump11289f42009-09-09 15:08:12 +0000104
Craig Topperc3ec1492014-05-26 06:22:03 +0000105 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000106 }
Mike Stump11289f42009-09-09 15:08:12 +0000107
Craig Topperc3ec1492014-05-26 06:22:03 +0000108 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000109}
110
Simon Pilgrim6905d222016-12-30 22:55:33 +0000111void Sema::FilterAcceptableTemplateNames(LookupResult &R,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000112 bool AllowFunctionTemplates) {
Douglas Gregor41f90302010-04-12 20:54:26 +0000113 // The set of class templates we've already seen.
114 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCalle66edc12009-11-24 19:00:30 +0000115 LookupResult::Filter filter = R.makeFilter();
116 while (filter.hasNext()) {
117 NamedDecl *Orig = filter.next();
Simon Pilgrim6905d222016-12-30 22:55:33 +0000118 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000119 AllowFunctionTemplates);
John McCalle66edc12009-11-24 19:00:30 +0000120 if (!Repl)
121 filter.erase();
Douglas Gregor41f90302010-04-12 20:54:26 +0000122 else if (Repl != Orig) {
123
124 // C++ [temp.local]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000125 // A lookup that finds an injected-class-name (10.2) can result in an
Douglas Gregor41f90302010-04-12 20:54:26 +0000126 // ambiguity in certain cases (for example, if it is found in more than
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000127 // one base class). If all of the injected-class-names that are found
128 // refer to specializations of the same class template, and if the name
Richard Smith3f1b5d02011-05-05 21:57:07 +0000129 // is used as a template-name, the reference refers to the class
130 // template itself and not a specialization thereof, and is not
Douglas Gregor41f90302010-04-12 20:54:26 +0000131 // ambiguous.
Douglas Gregor41f90302010-04-12 20:54:26 +0000132 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
David Blaikie82e95a32014-11-19 07:49:47 +0000133 if (!ClassTemplates.insert(ClassTmpl).second) {
Douglas Gregor41f90302010-04-12 20:54:26 +0000134 filter.erase();
135 continue;
136 }
John McCallbd8062d2010-08-13 07:02:08 +0000137
138 // FIXME: we promote access to public here as a workaround to
139 // the fact that LookupResult doesn't let us remember that we
140 // found this template through a particular injected class name,
141 // which means we end up doing nasty things to the invariants.
142 // Pretending that access is public is *much* safer.
143 filter.replace(Repl, AS_public);
Douglas Gregor41f90302010-04-12 20:54:26 +0000144 }
John McCalle66edc12009-11-24 19:00:30 +0000145 }
146 filter.done();
147}
148
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000149bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
150 bool AllowFunctionTemplates) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000151 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000152 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000153 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +0000154
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000155 return false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000156}
157
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000158TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000159 CXXScopeSpec &SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000160 bool hasTemplateKeyword,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000161 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +0000162 ParsedType ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000163 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000164 TemplateTy &TemplateResult,
165 bool &MemberOfUnknownSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000166 assert(getLangOpts().CPlusPlus && "No template names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000167
Douglas Gregor3cf81312009-11-03 23:16:33 +0000168 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000169 MemberOfUnknownSpecialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000170
Douglas Gregor3cf81312009-11-03 23:16:33 +0000171 switch (Name.getKind()) {
172 case UnqualifiedId::IK_Identifier:
173 TName = DeclarationName(Name.Identifier);
174 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000175
Douglas Gregor3cf81312009-11-03 23:16:33 +0000176 case UnqualifiedId::IK_OperatorFunctionId:
177 TName = Context.DeclarationNames.getCXXOperatorName(
178 Name.OperatorFunctionId.Operator);
179 break;
180
Alexis Hunted0530f2009-11-28 08:58:14 +0000181 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000182 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
183 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000184
Douglas Gregor3cf81312009-11-03 23:16:33 +0000185 default:
186 return TNK_Non_template;
187 }
Mike Stump11289f42009-09-09 15:08:12 +0000188
John McCallba7bf592010-08-24 05:47:05 +0000189 QualType ObjectType = ObjectTypePtr.get();
Mike Stump11289f42009-09-09 15:08:12 +0000190
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000191 LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +0000192 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
193 MemberOfUnknownSpecialization);
John McCallfb3f9ba2010-08-28 20:17:00 +0000194 if (R.empty()) return TNK_Non_template;
195 if (R.isAmbiguous()) {
196 // Suppress diagnostics; we'll redo this lookup later.
John McCalldcc71402010-08-13 02:23:42 +0000197 R.suppressDiagnostics();
John McCallfb3f9ba2010-08-28 20:17:00 +0000198
199 // FIXME: we might have ambiguous templates, in which case we
200 // should at least parse them properly!
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000201 return TNK_Non_template;
John McCalldcc71402010-08-13 02:23:42 +0000202 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000203
John McCalld28ae272009-12-02 08:04:21 +0000204 TemplateName Template;
205 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000206
John McCalld28ae272009-12-02 08:04:21 +0000207 unsigned ResultCount = R.end() - R.begin();
208 if (ResultCount > 1) {
209 // We assume that we'll preserve the qualifier from a function
210 // template name in other ways.
211 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
212 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000213
214 // We'll do this lookup again later.
215 R.suppressDiagnostics();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000216 } else {
John McCalld28ae272009-12-02 08:04:21 +0000217 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
218
219 if (SS.isSet() && !SS.isInvalid()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000220 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000221 Template = Context.getQualifiedTemplateName(Qualifier,
222 hasTemplateKeyword, TD);
John McCalld28ae272009-12-02 08:04:21 +0000223 } else {
224 Template = TemplateName(TD);
225 }
226
John McCalldcc71402010-08-13 02:23:42 +0000227 if (isa<FunctionTemplateDecl>(TD)) {
John McCalld28ae272009-12-02 08:04:21 +0000228 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000229
230 // We'll do this lookup again later.
231 R.suppressDiagnostics();
232 } else {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000233 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000234 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
235 isa<BuiltinTemplateDecl>(TD));
Larisse Voufo39a1e502013-08-06 01:03:05 +0000236 TemplateKind =
237 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
John McCalld28ae272009-12-02 08:04:21 +0000238 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000239 }
Mike Stump11289f42009-09-09 15:08:12 +0000240
John McCalld28ae272009-12-02 08:04:21 +0000241 TemplateResult = TemplateTy::make(Template);
242 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000243}
244
Richard Smith278890f2017-02-10 20:39:58 +0000245bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
246 SourceLocation NameLoc,
247 ParsedTemplateTy *Template) {
248 CXXScopeSpec SS;
249 bool MemberOfUnknownSpecialization = false;
250
251 // We could use redeclaration lookup here, but we don't need to: the
252 // syntactic form of a deduction guide is enough to identify it even
253 // if we can't look up the template name at all.
254 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
255 LookupTemplateName(R, S, SS, /*ObjectType*/QualType(),
256 /*EnteringContext*/false, MemberOfUnknownSpecialization);
257
258 if (R.empty()) return false;
259 if (R.isAmbiguous()) {
260 // FIXME: Diagnose an ambiguity if we find at least one template.
261 R.suppressDiagnostics();
262 return false;
263 }
264
265 // We only treat template-names that name type templates as valid deduction
266 // guide names.
267 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
268 if (!TD || !getAsTypeTemplateDecl(TD))
269 return false;
270
271 if (Template)
272 *Template = TemplateTy::make(TemplateName(TD));
273 return true;
274}
275
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000276bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
Douglas Gregor18473f32010-01-12 21:28:44 +0000277 SourceLocation IILoc,
278 Scope *S,
279 const CXXScopeSpec *SS,
280 TemplateTy &SuggestedTemplate,
281 TemplateNameKind &SuggestedKind) {
282 // We can't recover unless there's a dependent scope specifier preceding the
283 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000284 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000285 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
286 computeDeclContext(*SS))
287 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000288
Douglas Gregor18473f32010-01-12 21:28:44 +0000289 // The code is missing a 'template' keyword prior to the dependent template
290 // name.
291 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
292 Diag(IILoc, diag::err_template_kw_missing)
293 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000294 << FixItHint::CreateInsertion(IILoc, "template ");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000295 SuggestedTemplate
Douglas Gregor18473f32010-01-12 21:28:44 +0000296 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
297 SuggestedKind = TNK_Dependent_template_name;
298 return true;
299}
300
John McCalle66edc12009-11-24 19:00:30 +0000301void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000302 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000303 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000304 bool EnteringContext,
305 bool &MemberOfUnknownSpecialization) {
John McCalle66edc12009-11-24 19:00:30 +0000306 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000307 MemberOfUnknownSpecialization = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000308 DeclContext *LookupCtx = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000309 bool isDependent = false;
310 if (!ObjectType.isNull()) {
311 // This nested-name-specifier occurs in a member access expression, e.g.,
312 // x->B::f, and we are looking into the type of the object.
313 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
314 LookupCtx = computeDeclContext(ObjectType);
315 isDependent = ObjectType->isDependentType();
Richard Smith5ed79562013-06-07 20:03:01 +0000316 assert((isDependent || !ObjectType->isIncompleteType() ||
317 ObjectType->castAs<TagType>()->isBeingDefined()) &&
John McCalle66edc12009-11-24 19:00:30 +0000318 "Caller should have completed object type");
Simon Pilgrim6905d222016-12-30 22:55:33 +0000319
Douglas Gregorbf3a8262012-01-12 16:11:24 +0000320 // Template names cannot appear inside an Objective-C class or object type.
321 if (ObjectType->isObjCObjectOrInterfaceType()) {
322 Found.clear();
323 return;
324 }
John McCalle66edc12009-11-24 19:00:30 +0000325 } else if (SS.isSet()) {
326 // This nested-name-specifier occurs after another nested-name-specifier,
327 // so long into the context associated with the prior nested-name-specifier.
328 LookupCtx = computeDeclContext(SS, EnteringContext);
329 isDependent = isDependentScopeSpecifier(SS);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000330
John McCalle66edc12009-11-24 19:00:30 +0000331 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000332 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCalle66edc12009-11-24 19:00:30 +0000333 return;
334 }
335
336 bool ObjectTypeSearchedInScope = false;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000337 bool AllowFunctionTemplatesInLookup = true;
John McCalle66edc12009-11-24 19:00:30 +0000338 if (LookupCtx) {
339 // Perform "qualified" name lookup into the declaration context we
340 // computed, which is either the type of the base of a member access
341 // expression or the declaration context associated with a prior
342 // nested-name-specifier.
343 LookupQualifiedName(Found, LookupCtx);
John McCalle66edc12009-11-24 19:00:30 +0000344 if (!ObjectType.isNull() && Found.empty()) {
345 // C++ [basic.lookup.classref]p1:
346 // In a class member access expression (5.2.5), if the . or -> token is
347 // immediately followed by an identifier followed by a <, the
348 // identifier must be looked up to determine whether the < is the
349 // beginning of a template argument list (14.2) or a less-than operator.
350 // The identifier is first looked up in the class of the object
351 // expression. If the identifier is not found, it is then looked up in
352 // the context of the entire postfix-expression and shall name a class
353 // or function template.
John McCalle66edc12009-11-24 19:00:30 +0000354 if (S) LookupName(Found, S);
355 ObjectTypeSearchedInScope = true;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000356 AllowFunctionTemplatesInLookup = false;
John McCalle66edc12009-11-24 19:00:30 +0000357 }
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000358 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregorc119dd52010-01-12 17:06:20 +0000359 // We cannot look into a dependent object type or nested nme
360 // specifier.
Douglas Gregor786123d2010-05-21 23:18:07 +0000361 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000362 return;
363 } else {
364 // Perform unqualified name lookup in the current scope.
365 LookupName(Found, S);
Simon Pilgrim6905d222016-12-30 22:55:33 +0000366
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000367 if (!ObjectType.isNull())
368 AllowFunctionTemplatesInLookup = false;
John McCalle66edc12009-11-24 19:00:30 +0000369 }
370
Douglas Gregorc119dd52010-01-12 17:06:20 +0000371 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000372 // If we did not find any names, attempt to correct any typos.
373 DeclarationName Name = Found.getLookupName();
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000374 Found.clear();
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000375 // Simple filter callback that, for keywords, only accepts the C++ *_cast
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000376 auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
377 FilterCCC->WantTypeSpecifiers = false;
378 FilterCCC->WantExpressionKeywords = false;
379 FilterCCC->WantRemainingKeywords = false;
380 FilterCCC->WantCXXNamedCasts = true;
381 if (TypoCorrection Corrected = CorrectTypo(
382 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
383 std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000384 Found.setLookupName(Corrected.getCorrection());
Richard Smithde6d6c42015-12-29 19:43:10 +0000385 if (auto *ND = Corrected.getFoundDecl())
386 Found.addDecl(ND);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000387 FilterAcceptableTemplateNames(Found);
John McCalle9cccd82010-06-16 08:42:20 +0000388 if (!Found.empty()) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000389 if (LookupCtx) {
Richard Smithf9b15102013-08-17 00:46:16 +0000390 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
391 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000392 Name.getAsString() == CorrectedStr;
Richard Smithf9b15102013-08-17 00:46:16 +0000393 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
394 << Name << LookupCtx << DroppedSpecifier
395 << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000396 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000397 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000398 }
John McCalle9cccd82010-06-16 08:42:20 +0000399 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000400 } else {
Douglas Gregorc048c522010-06-29 19:27:42 +0000401 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000402 }
403 }
404
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000405 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000406 if (Found.empty()) {
407 if (isDependent)
408 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000409 return;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000410 }
John McCalle66edc12009-11-24 19:00:30 +0000411
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000412 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
Richard Smithe7d67f22013-09-03 21:22:41 +0000413 !getLangOpts().CPlusPlus11) {
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000414 // C++03 [basic.lookup.classref]p1:
John McCalle66edc12009-11-24 19:00:30 +0000415 // [...] If the lookup in the class of the object expression finds a
416 // template, the name is also looked up in the context of the entire
417 // postfix-expression and [...]
418 //
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000419 // Note: C++11 does not perform this second lookup.
John McCalle66edc12009-11-24 19:00:30 +0000420 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
421 LookupOrdinaryName);
422 LookupName(FoundOuter, S);
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000423 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000424
John McCalle66edc12009-11-24 19:00:30 +0000425 if (FoundOuter.empty()) {
426 // - if the name is not found, the name found in the class of the
427 // object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000428 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
429 FoundOuter.isAmbiguous()) {
John McCalle66edc12009-11-24 19:00:30 +0000430 // - if the name is found in the context of the entire
431 // postfix-expression and does not name a class template, the name
432 // found in the class of the object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000433 FoundOuter.clear();
John McCalle9cccd82010-06-16 08:42:20 +0000434 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000435 // - if the name found is a class template, it must refer to the same
436 // entity as the one found in the class of the object expression,
437 // otherwise the program is ill-formed.
438 if (!Found.isSingleResult() ||
439 Found.getFoundDecl()->getCanonicalDecl()
440 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000441 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000442 diag::ext_nested_name_member_ref_lookup_ambiguous)
443 << Found.getLookupName()
444 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000445 Diag(Found.getRepresentativeDecl()->getLocation(),
446 diag::note_ambig_member_ref_object_type)
447 << ObjectType;
448 Diag(FoundOuter.getFoundDecl()->getLocation(),
449 diag::note_ambig_member_ref_scope);
450
451 // Recover by taking the template that we found in the object
452 // expression's type.
453 }
454 }
455 }
456}
457
John McCallcd4b4772009-12-02 03:53:29 +0000458/// ActOnDependentIdExpression - Handle a dependent id-expression that
459/// was just parsed. This is only possible with an explicit scope
460/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000461ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000462Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000463 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000464 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000465 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000466 const TemplateArgumentListInfo *TemplateArgs) {
John McCall87fe5d52010-05-20 01:18:31 +0000467 DeclContext *DC = getFunctionLevelDeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000468
Reid Kleckner1af391df2016-03-11 18:59:12 +0000469 // C++11 [expr.prim.general]p12:
470 // An id-expression that denotes a non-static data member or non-static
471 // member function of a class can only be used:
472 // (...)
473 // - if that id-expression denotes a non-static data member and it
474 // appears in an unevaluated operand.
475 //
476 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
477 // CXXDependentScopeMemberExpr. The former can instantiate to either
478 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
479 // always a MemberExpr.
480 bool MightBeCxx11UnevalField =
481 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
482
Akira Hatanakad644e022016-12-16 03:19:41 +0000483 // Check if the nested name specifier is an enum type.
484 bool IsEnum = false;
485 if (NestedNameSpecifier *NNS = SS.getScopeRep())
486 IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
487
488 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
Reid Kleckner1af391df2016-03-11 18:59:12 +0000489 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
John McCall87fe5d52010-05-20 01:18:31 +0000490 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000491
John McCalle66edc12009-11-24 19:00:30 +0000492 // Since the 'this' expression is synthesized, we don't need to
493 // perform the double-lookup check.
Craig Topperc3ec1492014-05-26 06:22:03 +0000494 NamedDecl *FirstQualifierInScope = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000495
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000496 return CXXDependentScopeMemberExpr::Create(
497 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
498 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
499 FirstQualifierInScope, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000500 }
501
Abramo Bagnara7945c982012-01-27 09:46:47 +0000502 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000503}
504
John McCalldadc5752010-08-24 06:29:42 +0000505ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000506Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000507 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000508 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000509 const TemplateArgumentListInfo *TemplateArgs) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000510 return DependentScopeDeclRefExpr::Create(
511 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
512 TemplateArgs);
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000513}
514
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000515
516/// Determine whether we would be unable to instantiate this template (because
517/// it either has no definition, or is in the process of being instantiated).
518bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
519 NamedDecl *Instantiation,
520 bool InstantiatedFromMember,
521 const NamedDecl *Pattern,
522 const NamedDecl *PatternDef,
523 TemplateSpecializationKind TSK,
524 bool Complain /*= true*/) {
Richard Smithedbc6e92016-10-14 21:41:24 +0000525 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
526 isa<VarDecl>(Instantiation));
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000527
Richard Smithedbc6e92016-10-14 21:41:24 +0000528 bool IsEntityBeingDefined = false;
529 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
530 IsEntityBeingDefined = TD->isBeingDefined();
531
532 if (PatternDef && !IsEntityBeingDefined) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000533 NamedDecl *SuggestedDef = nullptr;
534 if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
535 /*OnlyNeedComplete*/false)) {
536 // If we're allowed to diagnose this and recover, do so.
537 bool Recover = Complain && !isSFINAEContext();
538 if (Complain)
539 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
540 Sema::MissingImportKind::Definition, Recover);
541 return !Recover;
542 }
543 return false;
544 }
545
Richard Smith6f4e2e02016-08-23 19:41:39 +0000546 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
547 return true;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000548
Richard Smithedbc6e92016-10-14 21:41:24 +0000549 llvm::Optional<unsigned> Note;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000550 QualType InstantiationTy;
551 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
552 InstantiationTy = Context.getTypeDeclType(TD);
Richard Smith6f4e2e02016-08-23 19:41:39 +0000553 if (PatternDef) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000554 Diag(PointOfInstantiation,
555 diag::err_template_instantiate_within_definition)
Richard Smithedbc6e92016-10-14 21:41:24 +0000556 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000557 << InstantiationTy;
558 // Not much point in noting the template declaration here, since
559 // we're lexically inside it.
560 Instantiation->setInvalidDecl();
561 } else if (InstantiatedFromMember) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000562 if (isa<FunctionDecl>(Instantiation)) {
563 Diag(PointOfInstantiation,
564 diag::err_explicit_instantiation_undefined_member)
Richard Smithedbc6e92016-10-14 21:41:24 +0000565 << /*member function*/ 1 << Instantiation->getDeclName()
566 << Instantiation->getDeclContext();
567 Note = diag::note_explicit_instantiation_here;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000568 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000569 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
Richard Smith6f4e2e02016-08-23 19:41:39 +0000570 Diag(PointOfInstantiation,
571 diag::err_implicit_instantiate_member_undefined)
572 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000573 Note = diag::note_member_declared_at;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000574 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000575 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000576 if (isa<FunctionDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000577 Diag(PointOfInstantiation,
578 diag::err_explicit_instantiation_undefined_func_template)
579 << Pattern;
Richard Smithedbc6e92016-10-14 21:41:24 +0000580 Note = diag::note_explicit_instantiation_here;
581 } else if (isa<TagDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000582 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
583 << (TSK != TSK_ImplicitInstantiation)
584 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000585 Note = diag::note_template_decl_here;
586 } else {
587 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
588 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
589 Diag(PointOfInstantiation,
590 diag::err_explicit_instantiation_undefined_var_template)
591 << Instantiation;
592 Instantiation->setInvalidDecl();
593 } else
594 Diag(PointOfInstantiation,
595 diag::err_explicit_instantiation_undefined_member)
596 << /*static data member*/ 2 << Instantiation->getDeclName()
597 << Instantiation->getDeclContext();
598 Note = diag::note_explicit_instantiation_here;
599 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000600 }
Richard Smithedbc6e92016-10-14 21:41:24 +0000601 if (Note) // Diagnostics were emitted.
602 Diag(Pattern->getLocation(), Note.getValue());
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000603
604 // In general, Instantiation isn't marked invalid to get more than one
605 // error for multiple undefined instantiations. But the code that does
606 // explicit declaration -> explicit definition conversion can't handle
607 // invalid declarations, so mark as invalid in that case.
608 if (TSK == TSK_ExplicitInstantiationDeclaration)
609 Instantiation->setInvalidDecl();
610 return true;
611}
612
Douglas Gregor5101c242008-12-05 18:15:24 +0000613/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
614/// that the template parameter 'PrevDecl' is being shadowed by a new
615/// declaration at location Loc. Returns true to indicate that this is
616/// an error, and false otherwise.
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000617void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000618 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000619
620 // Microsoft Visual C++ permits template parameters to be shadowed.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000621 if (getLangOpts().MicrosoftExt)
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000622 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000623
624 // C++ [temp.local]p4:
625 // A template-parameter shall not be redeclared within its
626 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000627 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000628 << cast<NamedDecl>(PrevDecl)->getDeclName();
629 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregor5101c242008-12-05 18:15:24 +0000630}
631
Douglas Gregor463421d2009-03-03 04:44:36 +0000632/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000633/// the parameter D to reference the templated declaration and return a pointer
634/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000635TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
636 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
637 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000638 return Temp;
639 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000640 return nullptr;
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000641}
642
Douglas Gregoreb29d182011-01-05 17:40:24 +0000643ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
644 SourceLocation EllipsisLoc) const {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000645 assert(Kind == Template &&
Douglas Gregoreb29d182011-01-05 17:40:24 +0000646 "Only template template arguments can be pack expansions here");
647 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
648 "Template template argument pack expansion without packs");
649 ParsedTemplateArgument Result(*this);
650 Result.EllipsisLoc = EllipsisLoc;
651 return Result;
652}
653
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000654static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
655 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000656
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000657 switch (Arg.getKind()) {
658 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000659 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000660 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000661 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000662 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000663 return TemplateArgumentLoc(TemplateArgument(T), DI);
664 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000665
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000666 case ParsedTemplateArgument::NonType: {
667 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
668 return TemplateArgumentLoc(TemplateArgument(E), E);
669 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000670
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000671 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000672 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregore1d60df2011-01-14 23:41:42 +0000673 TemplateArgument TArg;
674 if (Arg.getEllipsisLoc().isValid())
David Blaikie05785d12013-02-20 22:23:23 +0000675 TArg = TemplateArgument(Template, Optional<unsigned int>());
Douglas Gregore1d60df2011-01-14 23:41:42 +0000676 else
677 TArg = Template;
678 return TemplateArgumentLoc(TArg,
Douglas Gregor9d802122011-03-02 17:09:35 +0000679 Arg.getScopeSpec().getWithLocInContext(
680 SemaRef.Context),
Douglas Gregoreb29d182011-01-05 17:40:24 +0000681 Arg.getLocation(),
682 Arg.getEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000683 }
684 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000685
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000686 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000687}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000688
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000689/// \brief Translates template arguments as provided by the parser
690/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000691void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
692 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000693 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000694 TemplateArgs.addArgument(translateTemplateArgument(*this,
695 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000696}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000697
Richard Smithb80d5402013-06-25 22:21:36 +0000698static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
699 SourceLocation Loc,
700 IdentifierInfo *Name) {
701 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
702 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
703 if (PrevDecl && PrevDecl->isTemplateParameter())
704 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
705}
706
Douglas Gregor5101c242008-12-05 18:15:24 +0000707/// ActOnTypeParameter - Called when a C++ template type parameter
708/// (e.g., "typename T") has been parsed. Typename specifies whether
709/// the keyword "typename" was used to declare the type parameter
710/// (otherwise, "class" was used), and KeyLoc is the location of the
711/// "class" or "typename" keyword. ParamName is the name of the
712/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth08836322011-05-01 00:51:33 +0000713/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000714/// If the type parameter has a default argument, it will be added
715/// later via ActOnTypeParameterDefault.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000716Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
John McCall48871652010-08-21 09:40:31 +0000717 SourceLocation EllipsisLoc,
718 SourceLocation KeyLoc,
719 IdentifierInfo *ParamName,
720 SourceLocation ParamNameLoc,
721 unsigned Depth, unsigned Position,
722 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000723 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000724 assert(S->isTemplateParamScope() &&
725 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000726
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000727 SourceLocation Loc = ParamNameLoc;
728 if (!ParamName)
729 Loc = KeyLoc;
730
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000731 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregor5101c242008-12-05 18:15:24 +0000732 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000733 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000734 KeyLoc, Loc, Depth, Position, ParamName,
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000735 Typename, IsParameterPack);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000736 Param->setAccess(AS_public);
Douglas Gregor5101c242008-12-05 18:15:24 +0000737
738 if (ParamName) {
Richard Smithb80d5402013-06-25 22:21:36 +0000739 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
740
Douglas Gregor5101c242008-12-05 18:15:24 +0000741 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000742 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000743 IdResolver.AddDecl(Param);
744 }
745
Douglas Gregorf5500772011-01-05 15:48:55 +0000746 // C++0x [temp.param]p9:
747 // A default template-argument may be specified for any kind of
748 // template-parameter that is not a template parameter pack.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000749 if (DefaultArg && IsParameterPack) {
Douglas Gregorf5500772011-01-05 15:48:55 +0000750 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
David Blaikieefdccaa2016-01-15 23:43:34 +0000751 DefaultArg = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000752 }
753
Douglas Gregordc13ded2010-07-01 00:00:45 +0000754 // Handle the default argument, if provided.
755 if (DefaultArg) {
756 TypeSourceInfo *DefaultTInfo;
757 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000758
Douglas Gregordc13ded2010-07-01 00:00:45 +0000759 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000760
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000761 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000762 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000763 UPPC_DefaultArgument))
764 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000765
Douglas Gregordc13ded2010-07-01 00:00:45 +0000766 // Check the template argument itself.
767 if (CheckTemplateArgument(Param, DefaultTInfo)) {
768 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000769 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000770 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000771
Richard Smith1469b912015-06-10 00:29:03 +0000772 Param->setDefaultArgument(DefaultTInfo);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000773 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000774
John McCall48871652010-08-21 09:40:31 +0000775 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000776}
777
Douglas Gregor463421d2009-03-03 04:44:36 +0000778/// \brief Check that the type of a non-type template parameter is
779/// well-formed.
780///
781/// \returns the (possibly-promoted) parameter type if valid;
782/// otherwise, produces a diagnostic and returns a NULL type.
Richard Smith15361a22016-12-28 06:27:18 +0000783QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
784 SourceLocation Loc) {
785 if (TSI->getType()->isUndeducedType()) {
786 // C++1z [temp.dep.expr]p3:
787 // An id-expression is type-dependent if it contains
788 // - an identifier associated by name lookup with a non-type
789 // template-parameter declared with a type that contains a
790 // placeholder type (7.1.7.4),
791 TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
792 }
793
794 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
795}
796
797QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
798 SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000799 // We don't allow variably-modified types as the type of non-type template
800 // parameters.
801 if (T->isVariablyModifiedType()) {
802 Diag(Loc, diag::err_variably_modified_nontype_template_param)
803 << T;
804 return QualType();
805 }
806
Douglas Gregor463421d2009-03-03 04:44:36 +0000807 // C++ [temp.param]p4:
808 //
809 // A non-type template-parameter shall have one of the following
810 // (optionally cv-qualified) types:
811 //
812 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000813 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000814 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000815 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000816 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000817 T->isReferenceType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000818 // -- pointer to member,
Douglas Gregor463421d2009-03-03 04:44:36 +0000819 T->isMemberPointerType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000820 // -- std::nullptr_t.
821 T->isNullPtrType() ||
Douglas Gregor463421d2009-03-03 04:44:36 +0000822 // If T is a dependent type, we can't do the check now, so we
823 // assume that it is well-formed.
Richard Smith5f274382016-09-28 23:55:27 +0000824 T->isDependentType() ||
825 // Allow use of auto in template parameter declarations.
826 T->isUndeducedType()) {
Richard Smithd0e1c952012-03-13 07:21:50 +0000827 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
828 // are ignored when determining its type.
829 return T.getUnqualifiedType();
830 }
831
Douglas Gregor463421d2009-03-03 04:44:36 +0000832 // C++ [temp.param]p8:
833 //
834 // A non-type template-parameter of type "array of T" or
835 // "function returning T" is adjusted to be of type "pointer to
836 // T" or "pointer to function returning T", respectively.
Richard Smithd663fdd2014-12-17 20:42:37 +0000837 else if (T->isArrayType() || T->isFunctionType())
838 return Context.getDecayedType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000839
Douglas Gregor463421d2009-03-03 04:44:36 +0000840 Diag(Loc, diag::err_template_nontype_parm_bad_type)
841 << T;
842
843 return QualType();
844}
845
John McCall48871652010-08-21 09:40:31 +0000846Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
847 unsigned Depth,
848 unsigned Position,
849 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000850 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000851 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Richard Smith15361a22016-12-28 06:27:18 +0000852
853 if (TInfo->getType()->isUndeducedType()) {
854 Diag(D.getIdentifierLoc(),
855 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
856 << QualType(TInfo->getType()->getContainedAutoType(), 0);
857 }
Douglas Gregor5101c242008-12-05 18:15:24 +0000858
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000859 assert(S->isTemplateParamScope() &&
860 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000861 bool Invalid = false;
862
Richard Smith15361a22016-12-28 06:27:18 +0000863 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
Douglas Gregor38ee75e2010-12-16 15:36:43 +0000864 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000865 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000866 Invalid = true;
867 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000868
Richard Smithb80d5402013-06-25 22:21:36 +0000869 IdentifierInfo *ParamName = D.getIdentifier();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000870 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor5101c242008-12-05 18:15:24 +0000871 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000872 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000873 D.getLocStart(),
John McCallf7b2fb52010-01-22 00:28:27 +0000874 D.getIdentifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000875 Depth, Position, ParamName, T,
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000876 IsParameterPack, TInfo);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000877 Param->setAccess(AS_public);
Richard Smithb80d5402013-06-25 22:21:36 +0000878
Douglas Gregor5101c242008-12-05 18:15:24 +0000879 if (Invalid)
880 Param->setInvalidDecl();
881
Richard Smithb80d5402013-06-25 22:21:36 +0000882 if (ParamName) {
883 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
884 ParamName);
885
Douglas Gregor5101c242008-12-05 18:15:24 +0000886 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000887 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000888 IdResolver.AddDecl(Param);
889 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000890
Douglas Gregorf5500772011-01-05 15:48:55 +0000891 // C++0x [temp.param]p9:
892 // A default template-argument may be specified for any kind of
893 // template-parameter that is not a template parameter pack.
894 if (Default && IsParameterPack) {
895 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
Craig Topperc3ec1492014-05-26 06:22:03 +0000896 Default = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000897 }
898
Douglas Gregordc13ded2010-07-01 00:00:45 +0000899 // Check the well-formedness of the default template argument, if provided.
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000900 if (Default) {
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000901 // Check for unexpanded parameter packs.
902 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
903 return Param;
904
Douglas Gregordc13ded2010-07-01 00:00:45 +0000905 TemplateArgument Converted;
Richard Smithd663fdd2014-12-17 20:42:37 +0000906 ExprResult DefaultRes =
907 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
John Wiegley01296292011-04-08 18:41:53 +0000908 if (DefaultRes.isInvalid()) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000909 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000910 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000911 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000912 Default = DefaultRes.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000913
Richard Smith1469b912015-06-10 00:29:03 +0000914 Param->setDefaultArgument(Default);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000915 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000916
John McCall48871652010-08-21 09:40:31 +0000917 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000918}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000919
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000920/// ActOnTemplateTemplateParameter - Called when a C++ template template
James Dennett2a4d13c2012-06-15 07:13:21 +0000921/// parameter (e.g. T in template <template \<typename> class T> class array)
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000922/// has been parsed. S is the current scope.
John McCall48871652010-08-21 09:40:31 +0000923Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
924 SourceLocation TmpLoc,
Richard Trieu9becef62011-09-09 03:18:59 +0000925 TemplateParameterList *Params,
Douglas Gregorf5500772011-01-05 15:48:55 +0000926 SourceLocation EllipsisLoc,
John McCall48871652010-08-21 09:40:31 +0000927 IdentifierInfo *Name,
928 SourceLocation NameLoc,
929 unsigned Depth,
930 unsigned Position,
931 SourceLocation EqualLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +0000932 ParsedTemplateArgument Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000933 assert(S->isTemplateParamScope() &&
934 "Template template parameter not in template parameter scope!");
935
936 // Construct the parameter object.
Douglas Gregorf5500772011-01-05 15:48:55 +0000937 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000938 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000939 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000940 NameLoc.isInvalid()? TmpLoc : NameLoc,
941 Depth, Position, IsParameterPack,
Douglas Gregorf5500772011-01-05 15:48:55 +0000942 Name, Params);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000943 Param->setAccess(AS_public);
Simon Pilgrim6905d222016-12-30 22:55:33 +0000944
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000945 // If the template template parameter has a name, then link the identifier
Douglas Gregordc13ded2010-07-01 00:00:45 +0000946 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000947 if (Name) {
Richard Smithb80d5402013-06-25 22:21:36 +0000948 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
949
John McCall48871652010-08-21 09:40:31 +0000950 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000951 IdResolver.AddDecl(Param);
952 }
953
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000954 if (Params->size() == 0) {
955 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
956 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
957 Param->setInvalidDecl();
958 }
959
Douglas Gregorf5500772011-01-05 15:48:55 +0000960 // C++0x [temp.param]p9:
961 // A default template-argument may be specified for any kind of
962 // template-parameter that is not a template parameter pack.
963 if (IsParameterPack && !Default.isInvalid()) {
964 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
965 Default = ParsedTemplateArgument();
966 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000967
Douglas Gregordc13ded2010-07-01 00:00:45 +0000968 if (!Default.isInvalid()) {
969 // Check only that we have a template template argument. We don't want to
970 // try to check well-formedness now, because our template template parameter
971 // might have dependent types in its template parameters, which we wouldn't
972 // be able to match now.
973 //
974 // If none of the template template parameter's template arguments mention
975 // other template parameters, we could actually perform more checking here.
976 // However, it isn't worth doing.
977 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
978 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
Faisal Valib8b04f82016-03-26 20:46:45 +0000979 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
Douglas Gregordc13ded2010-07-01 00:00:45 +0000980 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +0000981 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000982 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000983
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000984 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000985 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000986 DefaultArg.getArgument().getAsTemplate(),
987 UPPC_DefaultArgument))
988 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000989
Richard Smith1469b912015-06-10 00:29:03 +0000990 Param->setDefaultArgument(Context, DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000991 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000992
John McCall48871652010-08-21 09:40:31 +0000993 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +0000994}
995
Hubert Tongf608c052016-04-29 18:05:37 +0000996/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
997/// constrained by RequiresClause, that contains the template parameters in
998/// Params.
Richard Trieu9becef62011-09-09 03:18:59 +0000999TemplateParameterList *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001000Sema::ActOnTemplateParameterList(unsigned Depth,
1001 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001002 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001003 SourceLocation LAngleLoc,
Craig Topper96225a52015-12-24 23:58:25 +00001004 ArrayRef<Decl *> Params,
Hubert Tongf608c052016-04-29 18:05:37 +00001005 SourceLocation RAngleLoc,
1006 Expr *RequiresClause) {
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001007 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001008 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001009
David Majnemer902f8c62015-12-27 07:16:27 +00001010 return TemplateParameterList::Create(
1011 Context, TemplateLoc, LAngleLoc,
1012 llvm::makeArrayRef((NamedDecl *const *)Params.data(), Params.size()),
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00001013 RAngleLoc, RequiresClause);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001014}
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001015
John McCall3e11ebe2010-03-15 10:12:16 +00001016static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
1017 if (SS.isSet())
Douglas Gregor14454802011-02-25 02:25:35 +00001018 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +00001019}
1020
John McCallfaf5fb42010-08-26 23:41:50 +00001021DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00001022Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001023 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001024 IdentifierInfo *Name, SourceLocation NameLoc,
1025 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001026 TemplateParameterList *TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00001027 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001028 SourceLocation FriendLoc,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001029 unsigned NumOuterTemplateParamLists,
Richard Smithbe3980b2015-03-27 00:41:57 +00001030 TemplateParameterList** OuterTemplateParamLists,
Richard Smithd9ba2242015-05-07 03:54:19 +00001031 SkipBodyInfo *SkipBody) {
Mike Stump11289f42009-09-09 15:08:12 +00001032 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001033 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +00001034 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +00001035 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001036
1037 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001038 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001039 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001040
Abramo Bagnara6150c882010-05-11 21:36:43 +00001041 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1042 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001043
1044 // There is no such thing as an unnamed class template.
1045 if (!Name) {
1046 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001047 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001048 }
1049
Richard Smith6483d222012-04-21 01:27:54 +00001050 // Find any previous declaration with this name. For a friend with no
1051 // scope explicitly specified, we only look for tag declarations (per
1052 // C++11 [basic.lookup.elab]p2).
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001053 DeclContext *SemanticContext;
Richard Smith6483d222012-04-21 01:27:54 +00001054 LookupResult Previous(*this, Name, NameLoc,
1055 (SS.isEmpty() && TUK == TUK_Friend)
1056 ? LookupTagName : LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +00001057 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001058 if (SS.isNotEmpty() && !SS.isInvalid()) {
1059 SemanticContext = computeDeclContext(SS, true);
1060 if (!SemanticContext) {
Douglas Gregor67daacb2012-03-30 16:20:47 +00001061 // FIXME: Horrible, horrible hack! We can't currently represent this
1062 // in the AST, and historically we have just ignored such friend
1063 // class templates, so don't complain here.
Richard Smithcd556eb2013-11-08 18:59:56 +00001064 Diag(NameLoc, TUK == TUK_Friend
1065 ? diag::warn_template_qualified_friend_ignored
1066 : diag::err_template_qualified_declarator_no_match)
Douglas Gregor67daacb2012-03-30 16:20:47 +00001067 << SS.getScopeRep() << SS.getRange();
Richard Smithcd556eb2013-11-08 18:59:56 +00001068 return TUK != TUK_Friend;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001069 }
Mike Stump11289f42009-09-09 15:08:12 +00001070
John McCall0b66eb32010-05-01 00:40:08 +00001071 if (RequireCompleteDeclContext(SS, SemanticContext))
1072 return true;
1073
Simon Pilgrim6905d222016-12-30 22:55:33 +00001074 // If we're adding a template to a dependent context, we may need to
1075 // rebuilding some of the types used within the template parameter list,
Douglas Gregor041b0842011-10-14 15:31:12 +00001076 // now that we know what the current instantiation is.
1077 if (SemanticContext->isDependentContext()) {
1078 ContextRAII SavedContext(*this, SemanticContext);
1079 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1080 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00001081 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1082 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
Richard Smith6483d222012-04-21 01:27:54 +00001083
John McCall27b18f82009-11-17 02:14:36 +00001084 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001085 } else {
1086 SemanticContext = CurContext;
Richard Smith88fe69c2015-07-06 01:45:27 +00001087
1088 // C++14 [class.mem]p14:
1089 // If T is the name of a class, then each of the following shall have a
1090 // name different from T:
1091 // -- every member template of class T
1092 if (TUK != TUK_Friend &&
1093 DiagnoseClassNameShadow(SemanticContext,
1094 DeclarationNameInfo(Name, NameLoc)))
1095 return true;
1096
John McCall27b18f82009-11-17 02:14:36 +00001097 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001098 }
Mike Stump11289f42009-09-09 15:08:12 +00001099
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001100 if (Previous.isAmbiguous())
1101 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001102
Craig Topperc3ec1492014-05-26 06:22:03 +00001103 NamedDecl *PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001104 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001105 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001106
Serge Pavlove50bf752016-06-10 04:39:07 +00001107 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1108 // Maybe we will complain about the shadowed template parameter.
1109 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1110 // Just pretend that we didn't see the previous declaration.
1111 PrevDecl = nullptr;
1112 }
1113
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001114 // If there is a previous declaration with the same name, check
1115 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +00001116 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001117 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001118
1119 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001120 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001121 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001122 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001123 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1124 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001125 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001126 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1127 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1128 PrevClassTemplate
1129 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1130 ->getSpecializedTemplate();
1131 }
1132 }
1133
John McCalld43784f2009-12-18 11:25:59 +00001134 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +00001135 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001136 // [...] When looking for a prior declaration of a class or a function
1137 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +00001138 // function is neither a qualified name nor a template-id, scopes outside
1139 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +00001140 if (!SS.isSet()) {
1141 DeclContext *OutermostContext = CurContext;
1142 while (!OutermostContext->isFileContext())
1143 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +00001144
Richard Smith61e582f2012-04-20 07:12:26 +00001145 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +00001146 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1147 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1148 SemanticContext = PrevDecl->getDeclContext();
1149 } else {
1150 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001151 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +00001152 // declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00001153 PrevDecl = PrevClassTemplate = nullptr;
Douglas Gregorb74b1032010-04-18 17:37:40 +00001154 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +00001155
1156 // Check that the chosen semantic context doesn't already contain a
1157 // declaration of this name as a non-tag type.
Richard Smithfc805ca2015-07-06 04:43:58 +00001158 Previous.clear(LookupOrdinaryName);
Richard Smith6483d222012-04-21 01:27:54 +00001159 DeclContext *LookupContext = SemanticContext;
1160 while (LookupContext->isTransparentContext())
1161 LookupContext = LookupContext->getLookupParent();
1162 LookupQualifiedName(Previous, LookupContext);
1163
1164 if (Previous.isAmbiguous())
1165 return true;
1166
1167 if (Previous.begin() != Previous.end())
1168 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +00001169 }
John McCall90d3bb92009-12-17 23:21:11 +00001170 }
Richard Smith72bcaec2013-12-05 04:30:04 +00001171 } else if (PrevDecl &&
Richard Smithfc805ca2015-07-06 04:43:58 +00001172 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1173 S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +00001174 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001175
Richard Smithfc805ca2015-07-06 04:43:58 +00001176 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1177 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1178 if (SS.isEmpty() &&
1179 !(PrevClassTemplate &&
1180 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1181 SemanticContext->getRedeclContext()))) {
1182 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1183 Diag(Shadow->getTargetDecl()->getLocation(),
1184 diag::note_using_decl_target);
1185 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1186 // Recover by ignoring the old declaration.
1187 PrevDecl = PrevClassTemplate = nullptr;
1188 }
1189 }
1190
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001191 // TODO Memory management; associated constraints are not always stored.
1192 Expr *const CurAC = formAssociatedConstraints(TemplateParams, nullptr);
1193
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001194 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +00001195 // Ensure that the template parameter lists are compatible. Skip this check
1196 // for a friend in a dependent context: the template parameter list itself
1197 // could be dependent.
1198 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1199 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001200 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001201 /*Complain=*/true,
1202 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001203 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001204
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001205 // Check for matching associated constraints on redeclarations.
1206 const Expr *const PrevAC = PrevClassTemplate->getAssociatedConstraints();
1207 const bool RedeclACMismatch = [&] {
1208 if (!(CurAC || PrevAC))
1209 return false; // Nothing to check; no mismatch.
1210 if (CurAC && PrevAC) {
1211 llvm::FoldingSetNodeID CurACInfo, PrevACInfo;
1212 CurAC->Profile(CurACInfo, Context, /*Canonical=*/true);
1213 PrevAC->Profile(PrevACInfo, Context, /*Canonical=*/true);
1214 if (CurACInfo == PrevACInfo)
1215 return false; // All good; no mismatch.
1216 }
1217 return true;
1218 }();
1219
1220 if (RedeclACMismatch) {
1221 Diag(CurAC ? CurAC->getLocStart() : NameLoc,
1222 diag::err_template_different_associated_constraints);
1223 Diag(PrevAC ? PrevAC->getLocStart() : PrevClassTemplate->getLocation(),
1224 diag::note_template_prev_declaration) << /*declaration*/0;
1225 return true;
1226 }
1227
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001228 // C++ [temp.class]p4:
1229 // In a redeclaration, partial specialization, explicit
1230 // specialization or explicit instantiation of a class template,
1231 // the class-key shall agree in kind with the original class
1232 // template declaration (7.1.5.3).
1233 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +00001234 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001235 TUK == TUK_Definition, KWLoc, Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00001236 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00001237 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00001238 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001239 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00001240 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001241 }
1242
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001243 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +00001244 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001245 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001246 // If we have a prior definition that is not visible, treat this as
1247 // simply making that previous definition visible.
1248 NamedDecl *Hidden = nullptr;
1249 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
Richard Smithd9ba2242015-05-07 03:54:19 +00001250 SkipBody->ShouldSkip = true;
Richard Smithbe3980b2015-03-27 00:41:57 +00001251 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1252 assert(Tmpl && "original definition of a class template is not a "
1253 "class template?");
Richard Smithd9ba2242015-05-07 03:54:19 +00001254 makeMergedDefinitionVisible(Hidden, KWLoc);
1255 makeMergedDefinitionVisible(Tmpl, KWLoc);
Richard Smithbe3980b2015-03-27 00:41:57 +00001256 return Def;
1257 }
1258
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001259 Diag(NameLoc, diag::err_redefinition) << Name;
1260 Diag(Def->getLocation(), diag::note_previous_definition);
1261 // FIXME: Would it make sense to try to "forget" the previous
1262 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +00001263 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001264 }
Serge Pavlove50bf752016-06-10 04:39:07 +00001265 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001266 } else if (PrevDecl) {
1267 // C++ [temp]p5:
1268 // A class template shall not have the same name as any other
1269 // template, class, function, object, enumeration, enumerator,
1270 // namespace, or type in the same scope (3.3), except as specified
1271 // in (14.5.4).
1272 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1273 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001274 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001275 }
1276
Douglas Gregordba32632009-02-10 19:49:53 +00001277 // Check the template parameter list of this declaration, possibly
1278 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001279 // template declaration. Skip this check for a friend in a dependent
1280 // context, because the template parameter list might be dependent.
1281 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001282 CheckTemplateParameterList(
1283 TemplateParams,
Craig Topperc3ec1492014-05-26 06:22:03 +00001284 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1285 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001286 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1287 SemanticContext->isDependentContext())
1288 ? TPC_ClassTemplateMember
1289 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1290 : TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +00001291 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001292
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001293 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001294 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001295 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001296 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1297 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001298 : diag::err_member_decl_does_not_match)
1299 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001300 Invalid = true;
1301 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001302 }
1303
Vassil Vassilev352e4412017-01-12 09:16:26 +00001304 // If this is a templated friend in a dependent context we should not put it
1305 // on the redecl chain. In some cases, the templated friend can be the most
1306 // recent declaration tricking the template instantiator to make substitutions
1307 // there.
1308 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1309 bool ShouldAddRedecl
1310 = !(TUK == TUK_Friend && CurContext->isDependentContext());
1311
Mike Stump11289f42009-09-09 15:08:12 +00001312 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001313 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Vassil Vassilev352e4412017-01-12 09:16:26 +00001314 PrevClassTemplate && ShouldAddRedecl ?
Craig Topperc3ec1492014-05-26 06:22:03 +00001315 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001316 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +00001317 SetNestedNameSpecifier(NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001318 if (NumOuterTemplateParamLists > 0)
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001319 NewClass->setTemplateParameterListsInfo(
1320 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1321 NumOuterTemplateParamLists));
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001322
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001323 // Add alignment attributes if necessary; these attributes are checked when
1324 // the ASTContext lays out the structure.
Eli Friedman0415f3e12012-08-08 21:08:34 +00001325 if (TUK == TUK_Definition) {
1326 AddAlignmentAttributesForRecord(NewClass);
1327 AddMsStructLayoutForRecord(NewClass);
1328 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001329
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001330 // Attach the associated constraints when the declaration will not be part of
1331 // a decl chain.
1332 Expr *const ACtoAttach =
1333 PrevClassTemplate && ShouldAddRedecl ? nullptr : CurAC;
1334
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001335 ClassTemplateDecl *NewTemplate
1336 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1337 DeclarationName(Name), TemplateParams,
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001338 NewClass, ACtoAttach);
Vassil Vassilev352e4412017-01-12 09:16:26 +00001339
1340 if (ShouldAddRedecl)
1341 NewTemplate->setPreviousDecl(PrevClassTemplate);
1342
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001343 NewClass->setDescribedClassTemplate(NewTemplate);
Simon Pilgrim6905d222016-12-30 22:55:33 +00001344
Douglas Gregor21823bf2011-12-20 18:11:52 +00001345 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001346 NewTemplate->setModulePrivate();
Simon Pilgrim6905d222016-12-30 22:55:33 +00001347
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001348 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001349 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001350 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001351 assert(T->isDependentType() && "Class template type is not dependent?");
1352 (void)T;
1353
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001354 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001355 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001356 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001357 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1358 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001359
Anders Carlsson137108d2009-03-26 01:24:28 +00001360 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001361 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001362 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001363
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001364 // Set the lexical context of these templates
1365 NewClass->setLexicalDeclContext(CurContext);
1366 NewTemplate->setLexicalDeclContext(CurContext);
1367
John McCall9bb74a52009-07-31 02:45:11 +00001368 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001369 NewClass->startDefinition();
1370
1371 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00001372 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001373
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001374 if (PrevClassTemplate)
1375 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1376
Rafael Espindola385c0422012-07-13 18:04:45 +00001377 AddPushedVisibilityAttribute(NewClass);
1378
Richard Smith234ff472014-08-23 00:49:01 +00001379 if (TUK != TUK_Friend) {
1380 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1381 Scope *Outer = S;
1382 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1383 Outer = Outer->getParent();
1384 PushOnScopeChains(NewTemplate, Outer);
1385 } else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001386 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001387 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001388 NewClass->setAccess(PrevClassTemplate->getAccess());
1389 }
John McCall27b5c252009-09-14 21:59:20 +00001390
Richard Smith64017682013-07-17 23:53:16 +00001391 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001392
John McCall27b5c252009-09-14 21:59:20 +00001393 // Friend templates are visible in fairly strange ways.
1394 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001395 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001396 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001397 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1398 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001399 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001400 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001401
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001402 FriendDecl *Friend = FriendDecl::Create(
1403 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
Douglas Gregor3dad8422009-09-26 06:47:28 +00001404 Friend->setAccess(AS_public);
1405 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001406 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001407
Douglas Gregordba32632009-02-10 19:49:53 +00001408 if (Invalid) {
1409 NewTemplate->setInvalidDecl();
1410 NewClass->setInvalidDecl();
1411 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001412
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001413 ActOnDocumentableDecl(NewTemplate);
1414
John McCall48871652010-08-21 09:40:31 +00001415 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001416}
1417
Richard Smith32918772017-02-14 00:25:28 +00001418namespace {
1419/// Transform to convert portions of a constructor declaration into the
1420/// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
1421struct ConvertConstructorToDeductionGuideTransform {
1422 ConvertConstructorToDeductionGuideTransform(Sema &S,
1423 ClassTemplateDecl *Template)
1424 : SemaRef(S), Template(Template) {}
1425
1426 Sema &SemaRef;
1427 ClassTemplateDecl *Template;
1428
1429 DeclContext *DC = Template->getDeclContext();
1430 CXXRecordDecl *Primary = Template->getTemplatedDecl();
1431 DeclarationName DeductionGuideName =
1432 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
1433
1434 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
1435
1436 // Index adjustment to apply to convert depth-1 template parameters into
1437 // depth-0 template parameters.
1438 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
1439
1440 /// Transform a constructor declaration into a deduction guide.
1441 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD, FunctionDecl *FD) {
1442 SmallVector<TemplateArgument, 16> SubstArgs;
1443
1444 // C++ [over.match.class.deduct]p1:
1445 // -- For each constructor of the class template designated by the
1446 // template-name, a function template with the following properties:
1447
1448 // -- The template parameters are the template parameters of the class
1449 // template followed by the template parameters (including default
1450 // template arguments) of the constructor, if any.
1451 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
1452 if (FTD) {
1453 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
1454 SmallVector<NamedDecl *, 16> AllParams;
1455 AllParams.reserve(TemplateParams->size() + InnerParams->size());
1456 AllParams.insert(AllParams.begin(),
1457 TemplateParams->begin(), TemplateParams->end());
1458 SubstArgs.reserve(InnerParams->size());
1459
1460 // Later template parameters could refer to earlier ones, so build up
1461 // a list of substituted template arguments as we go.
1462 for (NamedDecl *Param : *InnerParams) {
1463 MultiLevelTemplateArgumentList Args;
1464 Args.addOuterTemplateArguments(SubstArgs);
1465 Args.addOuterTemplateArguments(None);
1466 NamedDecl *NewParam = transformTemplateParameter(Param, Args);
1467 if (!NewParam)
1468 return nullptr;
1469 AllParams.push_back(NewParam);
1470 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
1471 SemaRef.Context.getInjectedTemplateArg(NewParam)));
1472 }
1473 TemplateParams = TemplateParameterList::Create(
1474 SemaRef.Context, InnerParams->getTemplateLoc(),
1475 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
1476 /*FIXME: RequiresClause*/ nullptr);
1477 }
1478
1479 // If we built a new template-parameter-list, track that we need to
1480 // substitute references to the old parameters into references to the
1481 // new ones.
1482 MultiLevelTemplateArgumentList Args;
1483 if (FTD) {
1484 Args.addOuterTemplateArguments(SubstArgs);
1485 Args.addOuterTemplateArguments(None);
1486 }
1487
1488 FunctionProtoTypeLoc FPTL = FD->getTypeSourceInfo()->getTypeLoc()
1489 .getAsAdjusted<FunctionProtoTypeLoc>();
1490 assert(FPTL && "no prototype for constructor declaration");
1491
1492 // Transform the type of the function, adjusting the return type and
1493 // replacing references to the old parameters with references to the
1494 // new ones.
1495 TypeLocBuilder TLB;
1496 SmallVector<ParmVarDecl*, 8> Params;
1497 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args);
1498 if (NewType.isNull())
1499 return nullptr;
1500 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
1501
1502 return buildDeductionGuide(TemplateParams, FD->isExplicit(), NewTInfo,
1503 FD->getLocStart(), FD->getLocation(),
1504 FD->getLocEnd());
1505 }
1506
1507 /// Build a deduction guide with the specified parameter types.
1508 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
1509 SourceLocation Loc = Template->getLocation();
1510
1511 // Build the requested type.
1512 FunctionProtoType::ExtProtoInfo EPI;
1513 EPI.HasTrailingReturn = true;
1514 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
1515 DeductionGuideName, EPI);
1516 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
1517
1518 FunctionProtoTypeLoc FPTL =
1519 TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
1520
1521 // Build the parameters, needed during deduction / substitution.
1522 SmallVector<ParmVarDecl*, 4> Params;
1523 for (auto T : ParamTypes) {
1524 ParmVarDecl *NewParam = ParmVarDecl::Create(
1525 SemaRef.Context, DC, Loc, Loc, nullptr, T,
1526 SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
1527 NewParam->setScopeInfo(0, Params.size());
1528 FPTL.setParam(Params.size(), NewParam);
1529 Params.push_back(NewParam);
1530 }
1531
1532 return buildDeductionGuide(Template->getTemplateParameters(), false, TSI,
1533 Loc, Loc, Loc);
1534 }
1535
1536private:
1537 /// Transform a constructor template parameter into a deduction guide template
1538 /// parameter, rebuilding any internal references to earlier parameters and
1539 /// renumbering as we go.
1540 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
1541 MultiLevelTemplateArgumentList &Args) {
1542 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
1543 // TemplateTypeParmDecl's index cannot be changed after creation, so
1544 // substitute it directly.
1545 auto *NewTTP = TemplateTypeParmDecl::Create(
1546 SemaRef.Context, DC, TTP->getLocStart(), TTP->getLocation(),
1547 /*Depth*/0, Depth1IndexAdjustment + TTP->getIndex(),
1548 TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
1549 TTP->isParameterPack());
1550 if (TTP->hasDefaultArgument()) {
1551 TypeSourceInfo *InstantiatedDefaultArg =
1552 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
1553 TTP->getDefaultArgumentLoc(), TTP->getDeclName());
1554 if (InstantiatedDefaultArg)
1555 NewTTP->setDefaultArgument(InstantiatedDefaultArg);
1556 }
1557 return NewTTP;
1558 }
1559
1560 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
1561 return transformTemplateParameterImpl(TTP, Args);
1562
1563 return transformTemplateParameterImpl(
1564 cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
1565 }
1566 template<typename TemplateParmDecl>
1567 TemplateParmDecl *
1568 transformTemplateParameterImpl(TemplateParmDecl *OldParam,
1569 MultiLevelTemplateArgumentList &Args) {
1570 // Ask the template instantiator to do the heavy lifting for us, then adjust
1571 // the index of the parameter once it's done.
1572 auto *NewParam =
1573 cast_or_null<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
1574 assert(NewParam->getDepth() == 0 && "unexpected template param depth");
1575 NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
1576 return NewParam;
1577 }
1578
1579 QualType transformFunctionProtoType(TypeLocBuilder &TLB,
1580 FunctionProtoTypeLoc TL,
1581 SmallVectorImpl<ParmVarDecl*> &Params,
1582 MultiLevelTemplateArgumentList &Args) {
1583 SmallVector<QualType, 4> ParamTypes;
1584 const FunctionProtoType *T = TL.getTypePtr();
1585
1586 // -- The types of the function parameters are those of the constructor.
1587 for (auto *OldParam : TL.getParams()) {
Richard Smithc27b3d72017-02-14 01:49:59 +00001588 ParmVarDecl *NewParam = transformFunctionTypeParam(OldParam, Args);
Richard Smith32918772017-02-14 00:25:28 +00001589 if (!NewParam)
1590 return QualType();
1591 ParamTypes.push_back(NewParam->getType());
1592 Params.push_back(NewParam);
1593 }
1594
1595 // -- The return type is the class template specialization designated by
1596 // the template-name and template arguments corresponding to the
1597 // template parameters obtained from the class template.
1598 //
1599 // We use the injected-class-name type of the primary template instead.
1600 // This has the convenient property that it is different from any type that
1601 // the user can write in a deduction-guide (because they cannot enter the
1602 // context of the template), so implicit deduction guides can never collide
1603 // with explicit ones.
1604 QualType ReturnType = DeducedType;
1605 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
1606
1607 // Resolving a wording defect, we also inherit the variadicness of the
1608 // constructor.
1609 FunctionProtoType::ExtProtoInfo EPI;
1610 EPI.Variadic = T->isVariadic();
1611 EPI.HasTrailingReturn = true;
1612
1613 QualType Result = SemaRef.BuildFunctionType(
1614 ReturnType, ParamTypes, TL.getLocStart(), DeductionGuideName, EPI);
1615 if (Result.isNull())
1616 return QualType();
1617
1618 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
1619 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
1620 NewTL.setLParenLoc(TL.getLParenLoc());
1621 NewTL.setRParenLoc(TL.getRParenLoc());
1622 NewTL.setExceptionSpecRange(SourceRange());
1623 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
1624 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
1625 NewTL.setParam(I, Params[I]);
1626
1627 return Result;
1628 }
1629
1630 ParmVarDecl *
1631 transformFunctionTypeParam(ParmVarDecl *OldParam,
1632 MultiLevelTemplateArgumentList &Args) {
1633 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
Richard Smithc27b3d72017-02-14 01:49:59 +00001634 TypeSourceInfo *NewDI =
1635 Args.getNumLevels()
1636 ? SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
1637 OldParam->getDeclName())
1638 : OldDI;
Richard Smith32918772017-02-14 00:25:28 +00001639 if (!NewDI)
1640 return nullptr;
1641
Richard Smithc27b3d72017-02-14 01:49:59 +00001642 // Canonicalize the type. This (for instance) replaces references to
1643 // typedef members of the current instantiations with the definitions of
1644 // those typedefs, avoiding triggering instantiation of the deduced type
1645 // during deduction.
1646 // FIXME: It would be preferable to retain type sugar and source
1647 // information here (and handle this in substitution instead).
1648 NewDI = SemaRef.Context.getTrivialTypeSourceInfo(
1649 SemaRef.Context.getCanonicalType(NewDI->getType()),
1650 OldParam->getLocation());
1651
Richard Smith32918772017-02-14 00:25:28 +00001652 // Resolving a wording defect, we also inherit default arguments from the
1653 // constructor.
1654 ExprResult NewDefArg;
1655 if (OldParam->hasDefaultArg()) {
Richard Smithc27b3d72017-02-14 01:49:59 +00001656 NewDefArg = Args.getNumLevels()
1657 ? SemaRef.SubstExpr(OldParam->getDefaultArg(), Args)
1658 : OldParam->getDefaultArg();
Richard Smith32918772017-02-14 00:25:28 +00001659 if (NewDefArg.isInvalid())
1660 return nullptr;
1661 }
1662
1663 ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
1664 OldParam->getInnerLocStart(),
1665 OldParam->getLocation(),
1666 OldParam->getIdentifier(),
1667 NewDI->getType(),
1668 NewDI,
1669 OldParam->getStorageClass(),
1670 NewDefArg.get());
1671 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
1672 OldParam->getFunctionScopeIndex());
1673 return NewParam;
1674 }
1675
1676 NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams,
1677 bool Explicit, TypeSourceInfo *TInfo,
1678 SourceLocation LocStart, SourceLocation Loc,
1679 SourceLocation LocEnd) {
1680 // Build the implicit deduction guide template.
1681 auto *Guide = FunctionDecl::Create(SemaRef.Context, DC, LocStart, Loc,
1682 DeductionGuideName, TInfo->getType(),
1683 TInfo, SC_None);
1684 Guide->setImplicit();
1685 if (Explicit)
1686 Guide->setExplicitSpecified();
1687 Guide->setRangeEnd(LocEnd);
1688 Guide->setParams(
1689 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams());
1690
1691 auto *GuideTemplate = FunctionTemplateDecl::Create(
1692 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
1693 GuideTemplate->setImplicit();
1694 Guide->setDescribedFunctionTemplate(GuideTemplate);
1695
1696 if (isa<CXXRecordDecl>(DC)) {
1697 Guide->setAccess(AS_public);
1698 GuideTemplate->setAccess(AS_public);
1699 }
1700
1701 DC->addDecl(GuideTemplate);
1702 return GuideTemplate;
1703 }
1704};
1705}
1706
1707void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
1708 SourceLocation Loc) {
1709 DeclContext *DC = Template->getDeclContext();
1710 if (DC->isDependentContext())
1711 return;
1712
1713 ConvertConstructorToDeductionGuideTransform Transform(
1714 *this, cast<ClassTemplateDecl>(Template));
1715 if (!isCompleteType(Loc, Transform.DeducedType))
1716 return;
1717
1718 // Check whether we've already declared deduction guides for this template.
1719 // FIXME: Consider storing a flag on the template to indicate this.
1720 auto Existing = DC->lookup(Transform.DeductionGuideName);
1721 for (auto *D : Existing)
1722 if (D->isImplicit())
1723 return;
1724
1725 // In case we were expanding a pack when we attempted to declare deduction
1726 // guides, turn off pack expansion for everything we're about to do.
1727 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1728 // Create a template instantiation record to track the "instantiation" of
1729 // constructors into deduction guides.
1730 // FIXME: Add a kind for this to give more meaningful diagnostics. But can
1731 // this substitution process actually fail?
1732 InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
1733
1734 // Convert declared constructors into deduction guide templates.
1735 // FIXME: Skip constructors for which deduction must necessarily fail (those
1736 // for which some class template parameter without a default argument never
1737 // appears in a deduced context).
1738 bool AddedAny = false;
1739 bool AddedCopyOrMove = false;
1740 for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
1741 D = D->getUnderlyingDecl();
1742 if (D->isInvalidDecl() || D->isImplicit())
1743 continue;
1744 D = cast<NamedDecl>(D->getCanonicalDecl());
1745
1746 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
1747 auto *FD = FTD ? FTD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D);
1748 // Class-scope explicit specializations (MS extension) do not result in
1749 // deduction guides.
1750 if (!FD || (!FTD && FD->isFunctionTemplateSpecialization()))
1751 continue;
1752
1753 Transform.transformConstructor(FTD, FD);
1754 AddedAny = true;
1755
1756 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(FD);
1757 AddedCopyOrMove |= CD->isCopyOrMoveConstructor();
1758 }
1759
1760 // Synthesize an X() -> X<...> guide if there were no declared constructors.
1761 // FIXME: The standard doesn't say (how) to do this.
1762 if (!AddedAny)
1763 Transform.buildSimpleDeductionGuide(None);
1764
1765 // Synthesize an X(X<...>) -> X<...> guide if there was no declared constructor
1766 // resembling a copy or move constructor.
1767 // FIXME: The standard doesn't say (how) to do this.
1768 if (!AddedCopyOrMove)
1769 Transform.buildSimpleDeductionGuide(Transform.DeducedType);
1770}
1771
Douglas Gregored5731f2009-11-25 17:50:39 +00001772/// \brief Diagnose the presence of a default template argument on a
1773/// template parameter, which is ill-formed in certain contexts.
1774///
1775/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001776static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00001777 Sema::TemplateParamListContext TPC,
1778 SourceLocation ParamLoc,
1779 SourceRange DefArgRange) {
1780 switch (TPC) {
1781 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00001782 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00001783 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001784 return false;
1785
1786 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001787 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001788 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00001789 // A default template-argument shall not be specified in a
1790 // function template declaration or a function template
1791 // definition [...]
Simon Pilgrim6905d222016-12-30 22:55:33 +00001792 // If a friend function template declaration specifies a default
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001793 // template-argument, that declaration shall be a definition and shall be
1794 // the only declaration of the function template in the translation unit.
1795 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001796 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00001797 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1798 : diag::ext_template_parameter_default_in_function_template)
1799 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00001800 return false;
1801
1802 case Sema::TPC_ClassTemplateMember:
1803 // C++0x [temp.param]p9:
1804 // A default template-argument shall not be specified in the
1805 // template-parameter-lists of the definition of a member of a
1806 // class template that appears outside of the member's class.
1807 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1808 << DefArgRange;
1809 return true;
1810
David Majnemerba8f17a2013-06-25 22:08:55 +00001811 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001812 case Sema::TPC_FriendFunctionTemplate:
1813 // C++ [temp.param]p9:
1814 // A default template-argument shall not be specified in a
1815 // friend template declaration.
1816 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1817 << DefArgRange;
1818 return true;
1819
1820 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1821 // for friend function templates if there is only a single
1822 // declaration (and it is a definition). Strange!
1823 }
1824
David Blaikie8a40f702012-01-17 06:56:22 +00001825 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00001826}
1827
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001828/// \brief Check for unexpanded parameter packs within the template parameters
1829/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00001830static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1831 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001832 // A template template parameter which is a parameter pack is also a pack
1833 // expansion.
1834 if (TTP->isParameterPack())
1835 return false;
1836
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001837 TemplateParameterList *Params = TTP->getTemplateParameters();
1838 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1839 NamedDecl *P = Params->getParam(I);
1840 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001841 if (!NTTP->isParameterPack() &&
1842 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001843 NTTP->getTypeSourceInfo(),
1844 Sema::UPPC_NonTypeTemplateParameterType))
1845 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001846
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001847 continue;
1848 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001849
1850 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001851 = dyn_cast<TemplateTemplateParmDecl>(P))
1852 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1853 return true;
1854 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001855
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001856 return false;
1857}
1858
Douglas Gregordba32632009-02-10 19:49:53 +00001859/// \brief Checks the validity of a template parameter list, possibly
1860/// considering the template parameter list from a previous
1861/// declaration.
1862///
1863/// If an "old" template parameter list is provided, it must be
1864/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1865/// template parameter list.
1866///
1867/// \param NewParams Template parameter list for a new template
1868/// declaration. This template parameter list will be updated with any
1869/// default arguments that are carried through from the previous
1870/// template parameter list.
1871///
1872/// \param OldParams If provided, template parameter list from a
1873/// previous declaration of the same template. Default template
1874/// arguments will be merged from the old template parameter list to
1875/// the new template parameter list.
1876///
Douglas Gregored5731f2009-11-25 17:50:39 +00001877/// \param TPC Describes the context in which we are checking the given
1878/// template parameter list.
1879///
Douglas Gregordba32632009-02-10 19:49:53 +00001880/// \returns true if an error occurred, false otherwise.
1881bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001882 TemplateParameterList *OldParams,
1883 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001884 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001885
Douglas Gregordba32632009-02-10 19:49:53 +00001886 // C++ [temp.param]p10:
1887 // The set of default template-arguments available for use with a
1888 // template declaration or definition is obtained by merging the
1889 // default arguments from the definition (if in scope) and all
1890 // declarations in scope in the same way default function
1891 // arguments are (8.3.6).
1892 bool SawDefaultArgument = false;
1893 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001894
Mike Stumpc89c8e32009-02-11 23:03:27 +00001895 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001896 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001897 if (OldParams)
1898 OldParam = OldParams->begin();
1899
Douglas Gregor0693def2011-01-27 01:40:17 +00001900 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00001901 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1902 NewParamEnd = NewParams->end();
1903 NewParam != NewParamEnd; ++NewParam) {
1904 // Variables used to diagnose redundant default arguments
1905 bool RedundantDefaultArg = false;
1906 SourceLocation OldDefaultLoc;
1907 SourceLocation NewDefaultLoc;
1908
David Blaikie651c73c2011-10-19 05:19:50 +00001909 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00001910 bool MissingDefaultArg = false;
1911
David Blaikie651c73c2011-10-19 05:19:50 +00001912 // Variable used to diagnose non-final parameter packs
1913 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00001914
Douglas Gregordba32632009-02-10 19:49:53 +00001915 if (TemplateTypeParmDecl *NewTypeParm
1916 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001917 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001918 if (NewTypeParm->hasDefaultArgument() &&
1919 DiagnoseDefaultTemplateArgument(*this, TPC,
1920 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001921 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001922 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001923 NewTypeParm->removeDefaultArgument();
1924
1925 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001926 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001927 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Anders Carlsson327865d2009-06-12 23:20:15 +00001928 if (NewTypeParm->isParameterPack()) {
1929 assert(!NewTypeParm->hasDefaultArgument() &&
1930 "Parameter packs can't have a default argument!");
1931 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001932 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
John McCall0ad16662009-10-29 08:12:44 +00001933 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001934 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1935 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1936 SawDefaultArgument = true;
1937 RedundantDefaultArg = true;
1938 PreviousDefaultArgLoc = NewDefaultLoc;
1939 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1940 // Merge the default argument from the old declaration to the
1941 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001942 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001943 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1944 } else if (NewTypeParm->hasDefaultArgument()) {
1945 SawDefaultArgument = true;
1946 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1947 } else if (SawDefaultArgument)
1948 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001949 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001950 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001951 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001952 if (!NewNonTypeParm->isParameterPack() &&
1953 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001954 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001955 UPPC_NonTypeTemplateParameterType)) {
1956 Invalid = true;
1957 continue;
1958 }
1959
Douglas Gregored5731f2009-11-25 17:50:39 +00001960 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001961 if (NewNonTypeParm->hasDefaultArgument() &&
1962 DiagnoseDefaultTemplateArgument(*this, TPC,
1963 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001964 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001965 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001966 }
1967
Mike Stump12b8ce12009-08-04 21:02:39 +00001968 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001969 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001970 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001971 if (NewNonTypeParm->isParameterPack()) {
1972 assert(!NewNonTypeParm->hasDefaultArgument() &&
1973 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001974 if (!NewNonTypeParm->isPackExpansion())
1975 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001976 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
Richard Smith35828f12013-07-22 03:31:14 +00001977 NewNonTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001978 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1979 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1980 SawDefaultArgument = true;
1981 RedundantDefaultArg = true;
1982 PreviousDefaultArgLoc = NewDefaultLoc;
1983 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1984 // Merge the default argument from the old declaration to the
1985 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001986 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001987 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1988 } else if (NewNonTypeParm->hasDefaultArgument()) {
1989 SawDefaultArgument = true;
1990 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1991 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001992 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001993 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00001994 TemplateTemplateParmDecl *NewTemplateParm
1995 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001996
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001997 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00001998 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001999 Invalid = true;
2000 continue;
2001 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002002
David Blaikie651c73c2011-10-19 05:19:50 +00002003 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002004 if (NewTemplateParm->hasDefaultArgument() &&
2005 DiagnoseDefaultTemplateArgument(*this, TPC,
2006 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002007 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00002008 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00002009
2010 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00002011 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002012 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00002013 if (NewTemplateParm->isParameterPack()) {
2014 assert(!NewTemplateParm->hasDefaultArgument() &&
2015 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00002016 if (!NewTemplateParm->isPackExpansion())
2017 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002018 } else if (OldTemplateParm &&
2019 hasVisibleDefaultArgument(OldTemplateParm) &&
2020 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002021 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2022 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002023 SawDefaultArgument = true;
2024 RedundantDefaultArg = true;
2025 PreviousDefaultArgLoc = NewDefaultLoc;
2026 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2027 // Merge the default argument from the old declaration to the
2028 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002029 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002030 PreviousDefaultArgLoc
2031 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002032 } else if (NewTemplateParm->hasDefaultArgument()) {
2033 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002034 PreviousDefaultArgLoc
2035 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002036 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002037 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00002038 }
2039
Richard Smith1fde8ec2012-09-07 02:06:42 +00002040 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00002041 // If a template parameter of a primary class template or alias template
2042 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002043 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00002044 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2045 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00002046 Diag((*NewParam)->getLocation(),
2047 diag::err_template_param_pack_must_be_last_template_parameter);
2048 Invalid = true;
2049 }
2050
Douglas Gregordba32632009-02-10 19:49:53 +00002051 if (RedundantDefaultArg) {
2052 // C++ [temp.param]p12:
2053 // A template-parameter shall not be given default arguments
2054 // by two different declarations in the same scope.
2055 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2056 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2057 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00002058 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00002059 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002060 // If a template-parameter of a class template has a default
2061 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00002062 // have a default template-argument supplied or be a template parameter
2063 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00002064 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00002065 diag::err_template_param_default_arg_missing);
2066 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2067 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00002068 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00002069 }
2070
2071 // If we have an old template parameter list that we're merging
2072 // in, move on to the next parameter.
2073 if (OldParams)
2074 ++OldParam;
2075 }
2076
Douglas Gregor0693def2011-01-27 01:40:17 +00002077 // We were missing some default arguments at the end of the list, so remove
2078 // all of the default arguments.
2079 if (RemoveDefaultArguments) {
2080 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2081 NewParamEnd = NewParams->end();
2082 NewParam != NewParamEnd; ++NewParam) {
2083 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2084 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002085 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00002086 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2087 NTTP->removeDefaultArgument();
2088 else
2089 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2090 }
2091 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002092
Douglas Gregordba32632009-02-10 19:49:53 +00002093 return Invalid;
2094}
Douglas Gregord32e0282009-02-09 23:23:08 +00002095
John McCalla020a012010-10-20 05:44:58 +00002096namespace {
2097
2098/// A class which looks for a use of a certain level of template
2099/// parameter.
2100struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2101 typedef RecursiveASTVisitor<DependencyChecker> super;
2102
2103 unsigned Depth;
Richard Smith43a833b2017-01-09 23:54:33 +00002104 bool FindLessThanDepth;
Richard Smith57aae072016-12-28 02:37:25 +00002105
2106 // Whether we're looking for a use of a template parameter that makes the
2107 // overall construct type-dependent / a dependent type. This is strictly
2108 // best-effort for now; we may fail to match at all for a dependent type
2109 // in some cases if this is set.
2110 bool IgnoreNonTypeDependent;
2111
John McCalla020a012010-10-20 05:44:58 +00002112 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00002113 SourceLocation MatchLoc;
2114
Richard Smith43a833b2017-01-09 23:54:33 +00002115 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent,
2116 bool FindLessThanDepth = false)
2117 : Depth(Depth), FindLessThanDepth(FindLessThanDepth),
2118 IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00002119
Richard Smith57aae072016-12-28 02:37:25 +00002120 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
Richard Smith43a833b2017-01-09 23:54:33 +00002121 : DependencyChecker(Params->getDepth(), IgnoreNonTypeDependent) {}
John McCalla020a012010-10-20 05:44:58 +00002122
Richard Smith6056d5e2014-02-09 00:54:43 +00002123 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
Richard Smith43a833b2017-01-09 23:54:33 +00002124 if (FindLessThanDepth ^ (ParmDepth >= Depth)) {
John McCalla020a012010-10-20 05:44:58 +00002125 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00002126 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00002127 return true;
2128 }
2129 return false;
2130 }
2131
Richard Smith57aae072016-12-28 02:37:25 +00002132 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2133 // Prune out non-type-dependent expressions if requested. This can
2134 // sometimes result in us failing to find a template parameter reference
2135 // (if a value-dependent expression creates a dependent type), but this
2136 // mode is best-effort only.
2137 if (auto *E = dyn_cast_or_null<Expr>(S))
2138 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2139 return true;
2140 return super::TraverseStmt(S, Q);
2141 }
2142
2143 bool TraverseTypeLoc(TypeLoc TL) {
2144 if (IgnoreNonTypeDependent && !TL.isNull() &&
2145 !TL.getType()->isDependentType())
2146 return true;
2147 return super::TraverseTypeLoc(TL);
2148 }
2149
Richard Smith6056d5e2014-02-09 00:54:43 +00002150 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2151 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2152 }
2153
John McCalla020a012010-10-20 05:44:58 +00002154 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
Richard Smith57aae072016-12-28 02:37:25 +00002155 // For a best-effort search, keep looking until we find a location.
2156 return IgnoreNonTypeDependent || !Matches(T->getDepth());
John McCalla020a012010-10-20 05:44:58 +00002157 }
2158
2159 bool TraverseTemplateName(TemplateName N) {
2160 if (TemplateTemplateParmDecl *PD =
2161 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00002162 if (Matches(PD->getDepth()))
2163 return false;
John McCalla020a012010-10-20 05:44:58 +00002164 return super::TraverseTemplateName(N);
2165 }
2166
2167 bool VisitDeclRefExpr(DeclRefExpr *E) {
2168 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00002169 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2170 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00002171 return false;
John McCalla020a012010-10-20 05:44:58 +00002172 return super::VisitDeclRefExpr(E);
2173 }
Richard Smith6056d5e2014-02-09 00:54:43 +00002174
2175 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2176 return TraverseType(T->getReplacementType());
2177 }
2178
2179 bool
2180 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2181 return TraverseTemplateArgument(T->getArgumentPack());
2182 }
2183
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00002184 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2185 return TraverseType(T->getInjectedSpecializationType());
2186 }
John McCalla020a012010-10-20 05:44:58 +00002187};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002188} // end anonymous namespace
John McCalla020a012010-10-20 05:44:58 +00002189
Douglas Gregor972fe532011-05-10 18:27:06 +00002190/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00002191/// list.
2192static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00002193DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
Richard Smith57aae072016-12-28 02:37:25 +00002194 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
Douglas Gregor972fe532011-05-10 18:27:06 +00002195 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00002196 return Checker.Match;
2197}
2198
Douglas Gregor972fe532011-05-10 18:27:06 +00002199// Find the source range corresponding to the named type in the given
2200// nested-name-specifier, if any.
2201static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2202 QualType T,
2203 const CXXScopeSpec &SS) {
2204 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2205 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2206 if (const Type *CurType = NNS->getAsType()) {
2207 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2208 return NNSLoc.getTypeLoc().getSourceRange();
2209 } else
2210 break;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002211
Douglas Gregor972fe532011-05-10 18:27:06 +00002212 NNSLoc = NNSLoc.getPrefix();
2213 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002214
Douglas Gregor972fe532011-05-10 18:27:06 +00002215 return SourceRange();
2216}
2217
Mike Stump11289f42009-09-09 15:08:12 +00002218/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00002219/// specifier, returning the template parameter list that applies to the
2220/// name.
2221///
2222/// \param DeclStartLoc the start of the declaration that has a scope
2223/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00002224///
Douglas Gregor972fe532011-05-10 18:27:06 +00002225/// \param DeclLoc The location of the declaration itself.
2226///
Douglas Gregord8d297c2009-07-21 23:53:31 +00002227/// \param SS the scope specifier that will be matched to the given template
2228/// parameter lists. This scope specifier precedes a qualified name that is
2229/// being declared.
2230///
Richard Smith4b55a9c2014-04-17 03:29:33 +00002231/// \param TemplateId The template-id following the scope specifier, if there
2232/// is one. Used to check for a missing 'template<>'.
2233///
Douglas Gregord8d297c2009-07-21 23:53:31 +00002234/// \param ParamLists the template parameter lists, from the outermost to the
2235/// innermost template parameter lists.
2236///
John McCalle820e5e2010-04-13 20:37:33 +00002237/// \param IsFriend Whether to apply the slightly different rules for
2238/// matching template parameters to scope specifiers in friend
2239/// declarations.
2240///
Richard Smithf445f192017-02-09 21:04:43 +00002241/// \param IsMemberSpecialization will be set true if the scope specifier
2242/// denotes a fully-specialized type, and therefore this is a declaration of
2243/// a member specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002244///
Mike Stump11289f42009-09-09 15:08:12 +00002245/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00002246/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00002247/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00002248/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00002249/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00002250/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002251TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2252 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00002253 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002254 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
Richard Smithf445f192017-02-09 21:04:43 +00002255 bool &IsMemberSpecialization, bool &Invalid) {
2256 IsMemberSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00002257 Invalid = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002258
Douglas Gregor972fe532011-05-10 18:27:06 +00002259 // The sequence of nested types to which we will match up the template
2260 // parameter lists. We first build this list by starting with the type named
2261 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002262 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00002263 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00002264 if (SS.getScopeRep()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002265 if (CXXRecordDecl *Record
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00002266 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2267 T = Context.getTypeDeclType(Record);
2268 else
2269 T = QualType(SS.getScopeRep()->getAsType(), 0);
2270 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002271
Douglas Gregor972fe532011-05-10 18:27:06 +00002272 // If we found an explicit specialization that prevents us from needing
2273 // 'template<>' headers, this will be set to the location of that
2274 // explicit specialization.
2275 SourceLocation ExplicitSpecLoc;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002276
Douglas Gregor972fe532011-05-10 18:27:06 +00002277 while (!T.isNull()) {
2278 NestedTypes.push_back(T);
Simon Pilgrim6905d222016-12-30 22:55:33 +00002279
Douglas Gregor972fe532011-05-10 18:27:06 +00002280 // Retrieve the parent of a record type.
2281 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2282 // If this type is an explicit specialization, we're done.
2283 if (ClassTemplateSpecializationDecl *Spec
2284 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002285 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002286 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2287 ExplicitSpecLoc = Spec->getLocation();
2288 break;
Douglas Gregor65911492009-11-23 12:11:45 +00002289 }
Douglas Gregor972fe532011-05-10 18:27:06 +00002290 } else if (Record->getTemplateSpecializationKind()
2291 == TSK_ExplicitSpecialization) {
2292 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00002293 break;
2294 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002295
Douglas Gregor972fe532011-05-10 18:27:06 +00002296 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2297 T = Context.getTypeDeclType(Parent);
2298 else
2299 T = QualType();
2300 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002301 }
2302
Douglas Gregor972fe532011-05-10 18:27:06 +00002303 if (const TemplateSpecializationType *TST
2304 = T->getAs<TemplateSpecializationType>()) {
2305 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2306 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2307 T = Context.getTypeDeclType(Parent);
2308 else
2309 T = QualType();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002310 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002311 }
Douglas Gregor972fe532011-05-10 18:27:06 +00002312 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002313
Douglas Gregor972fe532011-05-10 18:27:06 +00002314 // Look one step prior in a dependent template specialization type.
2315 if (const DependentTemplateSpecializationType *DependentTST
2316 = T->getAs<DependentTemplateSpecializationType>()) {
2317 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2318 T = QualType(NNS->getAsType(), 0);
2319 else
2320 T = QualType();
2321 continue;
2322 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002323
Douglas Gregor972fe532011-05-10 18:27:06 +00002324 // Look one step prior in a dependent name type.
2325 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2326 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2327 T = QualType(NNS->getAsType(), 0);
2328 else
2329 T = QualType();
2330 continue;
2331 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002332
Douglas Gregor972fe532011-05-10 18:27:06 +00002333 // Retrieve the parent of an enumeration type.
2334 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2335 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2336 // check here.
2337 EnumDecl *Enum = EnumT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002338
Douglas Gregor972fe532011-05-10 18:27:06 +00002339 // Get to the parent type.
2340 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2341 T = Context.getTypeDeclType(Parent);
2342 else
Simon Pilgrim6905d222016-12-30 22:55:33 +00002343 T = QualType();
Douglas Gregor972fe532011-05-10 18:27:06 +00002344 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002345 }
Mike Stump11289f42009-09-09 15:08:12 +00002346
Douglas Gregor972fe532011-05-10 18:27:06 +00002347 T = QualType();
2348 }
2349 // Reverse the nested types list, since we want to traverse from the outermost
2350 // to the innermost while checking template-parameter-lists.
2351 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00002352
Douglas Gregor972fe532011-05-10 18:27:06 +00002353 // C++0x [temp.expl.spec]p17:
2354 // A member or a member template may be nested within many
2355 // enclosing class templates. In an explicit specialization for
2356 // such a member, the member declaration shall be preceded by a
2357 // template<> for each enclosing class template that is
2358 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002359 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00002360
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002361 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00002362 if (SawNonEmptyTemplateParameterList) {
2363 Diag(DeclLoc, diag::err_specialize_member_of_template)
2364 << !Recovery << Range;
2365 Invalid = true;
Richard Smithf445f192017-02-09 21:04:43 +00002366 IsMemberSpecialization = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00002367 return true;
2368 }
2369
2370 return false;
2371 };
2372
2373 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2374 // Check that we can have an explicit specialization here.
2375 if (CheckExplicitSpecialization(Range, true))
2376 return true;
2377
2378 // We don't have a template header, but we should.
2379 SourceLocation ExpectedTemplateLoc;
2380 if (!ParamLists.empty())
2381 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2382 else
2383 ExpectedTemplateLoc = DeclStartLoc;
2384
2385 Diag(DeclLoc, diag::err_template_spec_needs_header)
2386 << Range
2387 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2388 return false;
2389 };
2390
Douglas Gregor972fe532011-05-10 18:27:06 +00002391 unsigned ParamIdx = 0;
2392 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2393 ++TypeIdx) {
2394 T = NestedTypes[TypeIdx];
Simon Pilgrim6905d222016-12-30 22:55:33 +00002395
Douglas Gregor972fe532011-05-10 18:27:06 +00002396 // Whether we expect a 'template<>' header.
2397 bool NeedEmptyTemplateHeader = false;
2398
2399 // Whether we expect a template header with parameters.
2400 bool NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002401
Douglas Gregor972fe532011-05-10 18:27:06 +00002402 // For a dependent type, the set of template parameters that we
2403 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00002404 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002405
Douglas Gregor373af9b2011-05-11 23:26:17 +00002406 // C++0x [temp.expl.spec]p15:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002407 // A member or a member template may be nested within many enclosing
2408 // class templates. In an explicit specialization for such a member, the
2409 // member declaration shall be preceded by a template<> for each
Douglas Gregor373af9b2011-05-11 23:26:17 +00002410 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00002411 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2412 if (ClassTemplatePartialSpecializationDecl *Partial
2413 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2414 ExpectedTemplateParams = Partial->getTemplateParameters();
2415 NeedNonemptyTemplateHeader = true;
2416 } else if (Record->isDependentType()) {
2417 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00002418 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00002419 ->getTemplateParameters();
2420 NeedNonemptyTemplateHeader = true;
2421 }
2422 } else if (ClassTemplateSpecializationDecl *Spec
2423 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2424 // C++0x [temp.expl.spec]p4:
2425 // Members of an explicitly specialized class template are defined
Simon Pilgrim6905d222016-12-30 22:55:33 +00002426 // in the same manner as members of normal classes, and not using
2427 // the template<> syntax.
Douglas Gregor972fe532011-05-10 18:27:06 +00002428 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2429 NeedEmptyTemplateHeader = true;
2430 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00002431 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002432 } else if (Record->getTemplateSpecializationKind()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002433 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00002434 != TSK_ExplicitSpecialization &&
2435 TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002436 IsMemberSpecialization = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002437
Douglas Gregor373af9b2011-05-11 23:26:17 +00002438 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002439 }
2440 } else if (const TemplateSpecializationType *TST
2441 = T->getAs<TemplateSpecializationType>()) {
Nico Weber28900612015-01-30 02:35:21 +00002442 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002443 ExpectedTemplateParams = Template->getTemplateParameters();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002444 NeedNonemptyTemplateHeader = true;
Douglas Gregor972fe532011-05-10 18:27:06 +00002445 }
2446 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2447 // FIXME: We actually could/should check the template arguments here
2448 // against the corresponding template parameter list.
2449 NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002450 }
2451
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002452 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002453 // In an explicit specialization declaration for a member of a class
2454 // template or a member template that ap- pears in namespace scope, the
2455 // member template and some of its enclosing class templates may remain
2456 // unspecialized, except that the declaration shall not explicitly
2457 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002458 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002459 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002460 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002461 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2462 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002463 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002464 } else
2465 SawNonEmptyTemplateParameterList = true;
2466 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002467
Douglas Gregor972fe532011-05-10 18:27:06 +00002468 if (NeedEmptyTemplateHeader) {
2469 // If we're on the last of the types, and we need a 'template<>' header
Richard Smithf445f192017-02-09 21:04:43 +00002470 // here, then it's a member specialization.
Douglas Gregor972fe532011-05-10 18:27:06 +00002471 if (TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002472 IsMemberSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002473
2474 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002475 if (ParamLists[ParamIdx]->size() > 0) {
2476 // The header has template parameters when it shouldn't. Complain.
Simon Pilgrim6905d222016-12-30 22:55:33 +00002477 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregor972fe532011-05-10 18:27:06 +00002478 diag::err_template_param_list_matches_nontemplate)
2479 << T
2480 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2481 ParamLists[ParamIdx]->getRAngleLoc())
2482 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2483 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002484 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002485 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002486
Douglas Gregor972fe532011-05-10 18:27:06 +00002487 // Consume this template header.
2488 ++ParamIdx;
2489 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002490 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002491
2492 if (!IsFriend)
2493 if (DiagnoseMissingExplicitSpecialization(
2494 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00002495 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002496
Douglas Gregor972fe532011-05-10 18:27:06 +00002497 continue;
2498 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002499
Douglas Gregor972fe532011-05-10 18:27:06 +00002500 if (NeedNonemptyTemplateHeader) {
2501 // In friend declarations we can have template-ids which don't
2502 // depend on the corresponding template parameter lists. But
2503 // assume that empty parameter lists are supposed to match this
2504 // template-id.
2505 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002506 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002507 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00002508 ExpectedTemplateParams = nullptr;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002509 else
Douglas Gregor972fe532011-05-10 18:27:06 +00002510 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002511 }
Douglas Gregored5731f2009-11-25 17:50:39 +00002512
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002513 if (ParamIdx < ParamLists.size()) {
2514 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00002515 if (ExpectedTemplateParams &&
2516 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2517 ExpectedTemplateParams,
2518 true, TPL_TemplateMatch))
2519 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002520
Douglas Gregor972fe532011-05-10 18:27:06 +00002521 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00002522 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00002523 TPC_ClassTemplateMember))
2524 Invalid = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002525
Douglas Gregor972fe532011-05-10 18:27:06 +00002526 ++ParamIdx;
2527 continue;
2528 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002529
Douglas Gregor972fe532011-05-10 18:27:06 +00002530 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2531 << T
2532 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2533 Invalid = true;
2534 continue;
2535 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00002536 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00002537
Douglas Gregord8d297c2009-07-21 23:53:31 +00002538 // If there were at least as many template-ids as there were template
2539 // parameter lists, then there are no template parameter lists remaining for
2540 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00002541 if (ParamIdx >= ParamLists.size()) {
2542 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00002543 // We don't have a template header for the declaration itself, but we
2544 // should.
Richard Smith11a80dc2014-04-17 03:52:20 +00002545 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2546 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00002547
2548 // Fabricate an empty template parameter list for the invented header.
2549 return TemplateParameterList::Create(Context, SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +00002550 SourceLocation(), None,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00002551 SourceLocation(), nullptr);
Richard Smith4b55a9c2014-04-17 03:29:33 +00002552 }
2553
Craig Topperc3ec1492014-05-26 06:22:03 +00002554 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002555 }
Mike Stump11289f42009-09-09 15:08:12 +00002556
Douglas Gregord8d297c2009-07-21 23:53:31 +00002557 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002558 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002559 bool HasAnyExplicitSpecHeader = false;
2560 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002561 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002562 if (ParamLists[I]->size() == 0)
2563 HasAnyExplicitSpecHeader = true;
2564 else
2565 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002566 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002567
Douglas Gregor972fe532011-05-10 18:27:06 +00002568 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002569 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2570 : diag::err_template_spec_extra_headers)
2571 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2572 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00002573
2574 // If there was a specialization somewhere, such that 'template<>' is
2575 // not required, and there were any 'template<>' headers, note where the
2576 // specialization occurred.
2577 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
Simon Pilgrim6905d222016-12-30 22:55:33 +00002578 Diag(ExplicitSpecLoc,
Douglas Gregor972fe532011-05-10 18:27:06 +00002579 diag::note_explicit_template_spec_does_not_need_header)
2580 << NestedTypes.back();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002581
Douglas Gregor972fe532011-05-10 18:27:06 +00002582 // We have a template parameter list with no corresponding scope, which
2583 // means that the resulting template declaration can't be instantiated
2584 // properly (we'll end up with dependent nodes when we shouldn't).
2585 if (!AllExplicitSpecHeaders)
2586 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002587 }
Mike Stump11289f42009-09-09 15:08:12 +00002588
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002589 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002590 // In an explicit specialization declaration for a member of a class
2591 // template or a member template that ap- pears in namespace scope, the
2592 // member template and some of its enclosing class templates may remain
2593 // unspecialized, except that the declaration shall not explicitly
2594 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002595 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00002596 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002597 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2598 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002599 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002600
Douglas Gregord8d297c2009-07-21 23:53:31 +00002601 // Return the last template parameter list, which corresponds to the
2602 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002603 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00002604}
2605
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002606void Sema::NoteAllFoundTemplates(TemplateName Name) {
2607 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2608 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002609 << (isa<FunctionTemplateDecl>(Template)
2610 ? 0
2611 : isa<ClassTemplateDecl>(Template)
2612 ? 1
2613 : isa<VarTemplateDecl>(Template)
2614 ? 2
2615 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2616 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002617 return;
2618 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002619
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002620 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002621 for (OverloadedTemplateStorage::iterator I = OST->begin(),
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002622 IEnd = OST->end();
2623 I != IEnd; ++I)
2624 Diag((*I)->getLocation(), diag::note_template_declared_here)
2625 << 0 << (*I)->getDeclName();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002626
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002627 return;
2628 }
2629}
2630
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002631static QualType
2632checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2633 const SmallVectorImpl<TemplateArgument> &Converted,
2634 SourceLocation TemplateLoc,
2635 TemplateArgumentListInfo &TemplateArgs) {
2636 ASTContext &Context = SemaRef.getASTContext();
2637 switch (BTD->getBuiltinTemplateKind()) {
Eric Fiselier6ad68552016-07-01 01:24:09 +00002638 case BTK__make_integer_seq: {
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002639 // Specializations of __make_integer_seq<S, T, N> are treated like
2640 // S<T, 0, ..., N-1>.
2641
2642 // C++14 [inteseq.intseq]p1:
2643 // T shall be an integer type.
2644 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2645 SemaRef.Diag(TemplateArgs[1].getLocation(),
2646 diag::err_integer_sequence_integral_element_type);
2647 return QualType();
2648 }
2649
2650 // C++14 [inteseq.make]p1:
2651 // If N is negative the program is ill-formed.
2652 TemplateArgument NumArgsArg = Converted[2];
2653 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2654 if (NumArgs < 0) {
2655 SemaRef.Diag(TemplateArgs[2].getLocation(),
2656 diag::err_integer_sequence_negative_length);
2657 return QualType();
2658 }
2659
2660 QualType ArgTy = NumArgsArg.getIntegralType();
2661 TemplateArgumentListInfo SyntheticTemplateArgs;
2662 // The type argument gets reused as the first template argument in the
2663 // synthetic template argument list.
2664 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2665 // Expand N into 0 ... N-1.
2666 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2667 I < NumArgs; ++I) {
2668 TemplateArgument TA(Context, I, ArgTy);
Richard Smith7873de02016-08-11 22:25:46 +00002669 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
2670 TA, ArgTy, TemplateArgs[2].getLocation()));
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002671 }
2672 // The first template argument will be reused as the template decl that
2673 // our synthetic template arguments will be applied to.
2674 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2675 TemplateLoc, SyntheticTemplateArgs);
2676 }
Eric Fiselier6ad68552016-07-01 01:24:09 +00002677
2678 case BTK__type_pack_element:
2679 // Specializations of
2680 // __type_pack_element<Index, T_1, ..., T_N>
2681 // are treated like T_Index.
2682 assert(Converted.size() == 2 &&
2683 "__type_pack_element should be given an index and a parameter pack");
2684
2685 // If the Index is out of bounds, the program is ill-formed.
2686 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
2687 llvm::APSInt Index = IndexArg.getAsIntegral();
2688 assert(Index >= 0 && "the index used with __type_pack_element should be of "
2689 "type std::size_t, and hence be non-negative");
2690 if (Index >= Ts.pack_size()) {
2691 SemaRef.Diag(TemplateArgs[0].getLocation(),
2692 diag::err_type_pack_element_out_of_bounds);
2693 return QualType();
2694 }
2695
2696 // We simply return the type at index `Index`.
2697 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
2698 return Nth->getAsType();
2699 }
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002700 llvm_unreachable("unexpected BuiltinTemplateDecl!");
2701}
2702
Douglas Gregordc572a32009-03-30 22:58:21 +00002703QualType Sema::CheckTemplateIdType(TemplateName Name,
2704 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002705 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00002706 DependentTemplateName *DTN
2707 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00002708 if (DTN && DTN->isIdentifier())
2709 // When building a template-id where the template-name is dependent,
2710 // assume the template is a type template. Either our assumption is
2711 // correct, or the code is ill-formed and will be diagnosed when the
2712 // dependent name is substituted.
2713 return Context.getDependentTemplateSpecializationType(ETK_None,
2714 DTN->getQualifier(),
2715 DTN->getIdentifier(),
2716 TemplateArgs);
2717
Douglas Gregordc572a32009-03-30 22:58:21 +00002718 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00002719 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2720 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002721 // We might have a substituted template template parameter pack. If so,
2722 // build a template specialization type for it.
2723 if (Name.getAsSubstTemplateTemplateParmPack())
2724 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002725
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002726 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2727 << Name;
2728 NoteAllFoundTemplates(Name);
2729 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00002730 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002731
Douglas Gregorc40290e2009-03-09 23:48:35 +00002732 // Check that the template argument list is well-formed for this
2733 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002734 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00002735 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00002736 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00002737 return QualType();
2738
Douglas Gregorc40290e2009-03-09 23:48:35 +00002739 QualType CanonType;
2740
Douglas Gregor678d76c2011-07-01 01:22:09 +00002741 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00002742 if (TypeAliasTemplateDecl *AliasTemplate =
2743 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00002744 // Find the canonical type for this type alias template specialization.
2745 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2746 if (Pattern->isInvalidDecl())
2747 return QualType();
2748
2749 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00002750 Converted);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002751
2752 // Only substitute for the innermost template argument list.
2753 MultiLevelTemplateArgumentList TemplateArgLists;
Richard Smith0c4a34b2011-05-14 15:04:18 +00002754 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00002755 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2756 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00002757 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002758
Richard Smith802c4b72012-08-23 06:16:52 +00002759 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002760 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002761 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00002762 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00002763
Richard Smith3f1b5d02011-05-05 21:57:07 +00002764 CanonType = SubstType(Pattern->getUnderlyingType(),
2765 TemplateArgLists, AliasTemplate->getLocation(),
2766 AliasTemplate->getDeclName());
2767 if (CanonType.isNull())
2768 return QualType();
2769 } else if (Name.isDependent() ||
2770 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00002771 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002772 // This class template specialization is a dependent
2773 // type. Therefore, its canonical type is another class template
2774 // specialization type that contains all of the converted
2775 // arguments in canonical form. This ensures that, e.g., A<T> and
2776 // A<T, T> have identical types when A is declared as:
2777 //
2778 // template<typename T, typename U = T> struct A;
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00002779 CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
John McCall2408e322010-04-27 00:57:59 +00002780
2781 // This might work out to be a current instantiation, in which
2782 // case the canonical type needs to be the InjectedClassNameType.
2783 //
2784 // TODO: in theory this could be a simple hashtable lookup; most
2785 // changes to CurContext don't change the set of current
2786 // instantiations.
2787 if (isa<ClassTemplateDecl>(Template)) {
2788 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2789 // If we get out to a namespace, we're done.
2790 if (Ctx->isFileContext()) break;
2791
2792 // If this isn't a record, keep looking.
2793 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2794 if (!Record) continue;
2795
2796 // Look for one of the two cases with InjectedClassNameTypes
2797 // and check whether it's the same template.
2798 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2799 !Record->getDescribedClassTemplate())
2800 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002801
John McCall2408e322010-04-27 00:57:59 +00002802 // Fetch the injected class name type and check whether its
2803 // injected type is equal to the type we just built.
2804 QualType ICNT = Context.getTypeDeclType(Record);
2805 QualType Injected = cast<InjectedClassNameType>(ICNT)
2806 ->getInjectedSpecializationType();
2807
2808 if (CanonType != Injected->getCanonicalTypeInternal())
2809 continue;
2810
2811 // If so, the canonical type of this TST is the injected
2812 // class name type of the record we just found.
2813 assert(ICNT.isCanonical());
2814 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00002815 break;
2816 }
2817 }
Mike Stump11289f42009-09-09 15:08:12 +00002818 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002819 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002820 // Find the class template specialization declaration that
2821 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002822 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002823 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00002824 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002825 if (!Decl) {
2826 // This is the first time we have referenced this class template
2827 // specialization. Create the canonical declaration and add it to
2828 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002829 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002830 ClassTemplate->getTemplatedDecl()->getTagKind(),
2831 ClassTemplate->getDeclContext(),
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002832 ClassTemplate->getTemplatedDecl()->getLocStart(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002833 ClassTemplate->getLocation(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002834 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00002835 Converted, nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00002836 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00002837 if (ClassTemplate->isOutOfLine())
2838 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00002839 }
2840
Chandler Carruth2acfb222013-09-27 22:14:40 +00002841 // Diagnose uses of this specialization.
2842 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2843
Douglas Gregorc40290e2009-03-09 23:48:35 +00002844 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00002845 assert(isa<RecordType>(CanonType) &&
2846 "type of non-dependent specialization is not a RecordType");
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002847 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
2848 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
2849 TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002850 }
Mike Stump11289f42009-09-09 15:08:12 +00002851
Douglas Gregorc40290e2009-03-09 23:48:35 +00002852 // Build the fully-sugared type for this class template
2853 // specialization, which refers back to the class template
2854 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00002855 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002856}
2857
John McCallfaf5fb42010-08-26 23:41:50 +00002858TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002859Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Richard Smith74f02342017-01-19 21:00:13 +00002860 TemplateTy TemplateD, IdentifierInfo *TemplateII,
2861 SourceLocation TemplateIILoc,
Mike Stump11289f42009-09-09 15:08:12 +00002862 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00002863 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002864 SourceLocation RAngleLoc,
Richard Smith62559bd2017-02-01 21:36:38 +00002865 bool IsCtorOrDtorName, bool IsClassName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002866 if (SS.isInvalid())
2867 return true;
2868
Richard Smith62559bd2017-02-01 21:36:38 +00002869 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
2870 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
2871
2872 // C++ [temp.res]p3:
2873 // A qualified-id that refers to a type and in which the
2874 // nested-name-specifier depends on a template-parameter (14.6.2)
2875 // shall be prefixed by the keyword typename to indicate that the
2876 // qualified-id denotes a type, forming an
2877 // elaborated-type-specifier (7.1.5.3).
2878 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
Richard Smith3411fbf2017-02-01 21:41:18 +00002879 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
Richard Smith62559bd2017-02-01 21:36:38 +00002880 << SS.getScopeRep() << TemplateII->getName();
2881 // Recover as if 'typename' were specified.
2882 // FIXME: This is not quite correct recovery as we don't transform SS
2883 // into the corresponding dependent form (and we don't diagnose missing
2884 // 'template' keywords within SS as a result).
2885 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
2886 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
2887 TemplateArgsIn, RAngleLoc);
2888 }
2889
2890 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
2891 // it's not actually allowed to be used as a type in most cases. Because
2892 // we annotate it before we know whether it's valid, we have to check for
2893 // this case here.
2894 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
Richard Smith74f02342017-01-19 21:00:13 +00002895 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
2896 Diag(TemplateIILoc,
2897 TemplateKWLoc.isInvalid()
2898 ? diag::err_out_of_line_qualified_id_type_names_constructor
2899 : diag::ext_out_of_line_qualified_id_type_names_constructor)
2900 << TemplateII << 0 /*injected-class-name used as template name*/
2901 << 1 /*if any keyword was present, it was 'template'*/;
2902 }
2903 }
2904
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002905 TemplateName Template = TemplateD.get();
Douglas Gregor8bf42052009-02-09 18:46:07 +00002906
Douglas Gregorc40290e2009-03-09 23:48:35 +00002907 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00002908 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002909 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00002910
Douglas Gregor5a064722011-02-28 17:23:35 +00002911 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00002912 QualType T
2913 = Context.getDependentTemplateSpecializationType(ETK_None,
2914 DTN->getQualifier(),
2915 DTN->getIdentifier(),
2916 TemplateArgs);
2917 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00002918 TypeLocBuilder TLB;
2919 DependentTemplateSpecializationTypeLoc SpecTL
2920 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002921 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2922 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002923 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00002924 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002925 SpecTL.setLAngleLoc(LAngleLoc);
2926 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002927 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2928 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2929 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2930 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002931
Richard Smith74f02342017-01-19 21:00:13 +00002932 QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002933 if (Result.isNull())
2934 return true;
2935
Douglas Gregore7c20652011-03-02 00:47:37 +00002936 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002937 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00002938 TemplateSpecializationTypeLoc SpecTL
2939 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002940 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00002941 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002942 SpecTL.setLAngleLoc(LAngleLoc);
2943 SpecTL.setRAngleLoc(RAngleLoc);
2944 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2945 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00002946
Abramo Bagnara4244b432012-01-27 08:46:19 +00002947 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2948 // constructor or destructor name (in such a case, the scope specifier
2949 // will be attached to the enclosing Decl or Expr node).
2950 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002951 // Create an elaborated-type-specifier containing the nested-name-specifier.
2952 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2953 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002954 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00002955 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2956 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002957
Douglas Gregore7c20652011-03-02 00:47:37 +00002958 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00002959}
John McCall06f6fe8d2009-09-04 01:14:41 +00002960
Douglas Gregore7c20652011-03-02 00:47:37 +00002961TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00002962 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00002963 SourceLocation TagLoc,
2964 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002965 SourceLocation TemplateKWLoc,
2966 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00002967 SourceLocation TemplateLoc,
2968 SourceLocation LAngleLoc,
2969 ASTTemplateArgsPtr TemplateArgsIn,
2970 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002971 TemplateName Template = TemplateD.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002972
Douglas Gregore7c20652011-03-02 00:47:37 +00002973 // Translate the parser's template argument list in our AST format.
2974 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2975 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00002976
Douglas Gregore7c20652011-03-02 00:47:37 +00002977 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00002978 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00002979 ElaboratedTypeKeyword Keyword
2980 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00002981
Douglas Gregore7c20652011-03-02 00:47:37 +00002982 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2983 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
Simon Pilgrim6905d222016-12-30 22:55:33 +00002984 DTN->getQualifier(),
2985 DTN->getIdentifier(),
Douglas Gregore7c20652011-03-02 00:47:37 +00002986 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00002987
2988 // Build type-source information.
Douglas Gregore7c20652011-03-02 00:47:37 +00002989 TypeLocBuilder TLB;
2990 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002991 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2992 SpecTL.setElaboratedKeywordLoc(TagLoc);
2993 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002994 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002995 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002996 SpecTL.setLAngleLoc(LAngleLoc);
2997 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002998 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2999 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3000 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3001 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00003002
3003 if (TypeAliasTemplateDecl *TAT =
3004 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3005 // C++0x [dcl.type.elab]p2:
3006 // If the identifier resolves to a typedef-name or the simple-template-id
3007 // resolves to an alias template specialization, the
3008 // elaborated-type-specifier is ill-formed.
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00003009 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3010 << TAT << NTK_TypeAliasTemplate << TagKind;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003011 Diag(TAT->getLocation(), diag::note_declared_at);
3012 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003013
Douglas Gregore7c20652011-03-02 00:47:37 +00003014 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3015 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00003016 return TypeResult(true);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003017
Douglas Gregore7c20652011-03-02 00:47:37 +00003018 // Check the tag kind
3019 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00003020 RecordDecl *D = RT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00003021
John McCalld8fe9af2009-09-08 17:47:29 +00003022 IdentifierInfo *Id = D->getIdentifier();
3023 assert(Id && "templated class must have an identifier");
Simon Pilgrim6905d222016-12-30 22:55:33 +00003024
Richard Trieucaa33d32011-06-10 03:11:26 +00003025 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00003026 TagLoc, Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00003027 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00003028 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00003029 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00003030 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00003031 }
3032 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003033
Douglas Gregore7c20652011-03-02 00:47:37 +00003034 // Provide source-location information for the template specialization.
3035 TypeLocBuilder TLB;
3036 TemplateSpecializationTypeLoc SpecTL
3037 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003038 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003039 SpecTL.setTemplateNameLoc(TemplateLoc);
3040 SpecTL.setLAngleLoc(LAngleLoc);
3041 SpecTL.setRAngleLoc(RAngleLoc);
3042 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3043 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00003044
Douglas Gregore7c20652011-03-02 00:47:37 +00003045 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003046 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00003047 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3048 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00003049 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003050 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3051 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003052}
3053
Larisse Voufo39a1e502013-08-06 01:03:05 +00003054static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3055 NamedDecl *PrevDecl,
3056 SourceLocation Loc,
3057 bool IsPartialSpecialization);
3058
3059static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003060
Richard Smith300e0c32013-09-24 04:49:23 +00003061static bool isTemplateArgumentTemplateParameter(
3062 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3063 switch (Arg.getKind()) {
3064 case TemplateArgument::Null:
3065 case TemplateArgument::NullPtr:
3066 case TemplateArgument::Integral:
3067 case TemplateArgument::Declaration:
3068 case TemplateArgument::Pack:
3069 case TemplateArgument::TemplateExpansion:
3070 return false;
3071
3072 case TemplateArgument::Type: {
3073 QualType Type = Arg.getAsType();
3074 const TemplateTypeParmType *TPT =
3075 Arg.getAsType()->getAs<TemplateTypeParmType>();
3076 return TPT && !Type.hasQualifiers() &&
3077 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3078 }
3079
3080 case TemplateArgument::Expression: {
3081 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3082 if (!DRE || !DRE->getDecl())
3083 return false;
3084 const NonTypeTemplateParmDecl *NTTP =
3085 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3086 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3087 }
3088
3089 case TemplateArgument::Template:
3090 const TemplateTemplateParmDecl *TTP =
3091 dyn_cast_or_null<TemplateTemplateParmDecl>(
3092 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
3093 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3094 }
3095 llvm_unreachable("unexpected kind of template argument");
3096}
3097
3098static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
3099 ArrayRef<TemplateArgument> Args) {
3100 if (Params->size() != Args.size())
3101 return false;
3102
3103 unsigned Depth = Params->getDepth();
3104
3105 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3106 TemplateArgument Arg = Args[I];
3107
3108 // If the parameter is a pack expansion, the argument must be a pack
3109 // whose only element is a pack expansion.
3110 if (Params->getParam(I)->isParameterPack()) {
3111 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3112 !Arg.pack_begin()->isPackExpansion())
3113 return false;
3114 Arg = Arg.pack_begin()->getPackExpansionPattern();
3115 }
3116
3117 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3118 return false;
3119 }
3120
3121 return true;
3122}
3123
Richard Smith4b55a9c2014-04-17 03:29:33 +00003124/// Convert the parser's template argument list representation into our form.
3125static TemplateArgumentListInfo
3126makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
3127 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
3128 TemplateId.RAngleLoc);
3129 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
3130 TemplateId.NumArgs);
3131 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
3132 return TemplateArgs;
3133}
3134
Richard Smith0e617ec2016-12-27 07:56:27 +00003135template<typename PartialSpecDecl>
3136static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3137 if (Partial->getDeclContext()->isDependentContext())
3138 return;
3139
3140 // FIXME: Get the TDK from deduction in order to provide better diagnostics
3141 // for non-substitution-failure issues?
3142 TemplateDeductionInfo Info(Partial->getLocation());
3143 if (S.isMoreSpecializedThanPrimary(Partial, Info))
3144 return;
3145
3146 auto *Template = Partial->getSpecializedTemplate();
3147 S.Diag(Partial->getLocation(),
Richard Smithfa4a09d2016-12-27 20:03:09 +00003148 diag::ext_partial_spec_not_more_specialized_than_primary)
3149 << isa<VarTemplateDecl>(Template);
Richard Smith0e617ec2016-12-27 07:56:27 +00003150
3151 if (Info.hasSFINAEDiagnostic()) {
3152 PartialDiagnosticAt Diag = {SourceLocation(),
3153 PartialDiagnostic::NullDiagnostic()};
3154 Info.takeSFINAEDiagnostic(Diag);
3155 SmallString<128> SFINAEArgString;
3156 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3157 S.Diag(Diag.first,
3158 diag::note_partial_spec_not_more_specialized_than_primary)
3159 << SFINAEArgString;
3160 }
3161
3162 S.Diag(Template->getLocation(), diag::note_template_decl_here);
3163}
3164
Richard Smith57aae072016-12-28 02:37:25 +00003165template<typename PartialSpecDecl>
3166static void checkTemplatePartialSpecialization(Sema &S,
3167 PartialSpecDecl *Partial) {
3168 // C++1z [temp.class.spec]p8: (DR1495)
3169 // - The specialization shall be more specialized than the primary
3170 // template (14.5.5.2).
3171 checkMoreSpecializedThanPrimary(S, Partial);
3172
3173 // C++ [temp.class.spec]p8: (DR1315)
3174 // - Each template-parameter shall appear at least once in the
3175 // template-id outside a non-deduced context.
3176 // C++1z [temp.class.spec.match]p3 (P0127R2)
3177 // If the template arguments of a partial specialization cannot be
3178 // deduced because of the structure of its template-parameter-list
3179 // and the template-id, the program is ill-formed.
3180 auto *TemplateParams = Partial->getTemplateParameters();
3181 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3182 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3183 TemplateParams->getDepth(), DeducibleParams);
3184
3185 if (!DeducibleParams.all()) {
3186 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3187 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3188 << isa<VarTemplatePartialSpecializationDecl>(Partial)
3189 << (NumNonDeducible > 1)
3190 << SourceRange(Partial->getLocation(),
3191 Partial->getTemplateArgsAsWritten()->RAngleLoc);
3192 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3193 if (!DeducibleParams[I]) {
3194 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3195 if (Param->getDeclName())
3196 S.Diag(Param->getLocation(),
3197 diag::note_partial_spec_unused_parameter)
3198 << Param->getDeclName();
3199 else
3200 S.Diag(Param->getLocation(),
3201 diag::note_partial_spec_unused_parameter)
3202 << "(anonymous)";
3203 }
3204 }
3205 }
3206}
3207
3208void Sema::CheckTemplatePartialSpecialization(
3209 ClassTemplatePartialSpecializationDecl *Partial) {
3210 checkTemplatePartialSpecialization(*this, Partial);
3211}
3212
3213void Sema::CheckTemplatePartialSpecialization(
3214 VarTemplatePartialSpecializationDecl *Partial) {
3215 checkTemplatePartialSpecialization(*this, Partial);
3216}
3217
Larisse Voufo39a1e502013-08-06 01:03:05 +00003218DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00003219 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00003220 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00003221 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003222 // D must be variable template id.
3223 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
3224 "Variable template specialization is declared with a template it.");
3225
3226 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00003227 TemplateArgumentListInfo TemplateArgs =
3228 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003229 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3230 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3231 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00003232
Richard Smithbeef3452014-01-16 23:39:20 +00003233 TemplateName Name = TemplateId->Template.get();
3234
3235 // The template-id must name a variable template.
3236 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00003237 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3238 if (!VarTemplate) {
3239 NamedDecl *FnTemplate;
3240 if (auto *OTS = Name.getAsOverloadedTemplate())
3241 FnTemplate = *OTS->begin();
3242 else
3243 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3244 if (FnTemplate)
3245 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3246 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00003247 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3248 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00003249 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003250
3251 // Check for unexpanded parameter packs in any of the template arguments.
3252 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3253 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3254 UPPC_PartialSpecialization))
3255 return true;
3256
3257 // Check that the template argument list is well-formed for this
3258 // template.
3259 SmallVector<TemplateArgument, 4> Converted;
3260 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
3261 false, Converted))
3262 return true;
3263
Larisse Voufo39a1e502013-08-06 01:03:05 +00003264 // Find the variable template (partial) specialization declaration that
3265 // corresponds to these arguments.
3266 if (IsPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00003267 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
3268 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00003269 return true;
3270
Richard Smith57aae072016-12-28 02:37:25 +00003271 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
3272 // also do them during instantiation.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003273 bool InstantiationDependent;
3274 if (!Name.isDependent() &&
3275 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00003276 TemplateArgs.arguments(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00003277 InstantiationDependent)) {
3278 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3279 << VarTemplate->getDeclName();
3280 IsPartialSpecialization = false;
3281 }
Richard Smith300e0c32013-09-24 04:49:23 +00003282
3283 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
3284 Converted)) {
3285 // C++ [temp.class.spec]p9b3:
3286 //
3287 // -- The argument list of the specialization shall not be identical
3288 // to the implicit argument list of the primary template.
3289 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3290 << /*variable template*/ 1
3291 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
3292 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
3293 // FIXME: Recover from this by treating the declaration as a redeclaration
3294 // of the primary template.
3295 return true;
3296 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003297 }
3298
Craig Topperc3ec1492014-05-26 06:22:03 +00003299 void *InsertPos = nullptr;
3300 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003301
3302 if (IsPartialSpecialization)
3303 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00003304 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003305 else
Craig Topper7e0daca2014-06-26 04:58:53 +00003306 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003307
Craig Topperc3ec1492014-05-26 06:22:03 +00003308 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003309
3310 // Check whether we can declare a variable template specialization in
3311 // the current scope.
3312 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
3313 TemplateNameLoc,
3314 IsPartialSpecialization))
3315 return true;
3316
3317 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3318 // Since the only prior variable template specialization with these
3319 // arguments was referenced but not declared, reuse that
3320 // declaration node as our own, updating its source location and
3321 // the list of outer template parameters to reflect our new declaration.
3322 Specialization = PrevDecl;
3323 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00003324 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003325 } else if (IsPartialSpecialization) {
3326 // Create a new class template partial specialization declaration node.
3327 VarTemplatePartialSpecializationDecl *PrevPartial =
3328 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003329 VarTemplatePartialSpecializationDecl *Partial =
3330 VarTemplatePartialSpecializationDecl::Create(
3331 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
3332 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
David Majnemer8b622692016-07-03 21:17:51 +00003333 Converted, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003334
3335 if (!PrevPartial)
3336 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
3337 Specialization = Partial;
3338
3339 // If we are providing an explicit specialization of a member variable
3340 // template specialization, make a note of that.
3341 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00003342 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00003343
Richard Smith57aae072016-12-28 02:37:25 +00003344 CheckTemplatePartialSpecialization(Partial);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003345 } else {
3346 // Create a new class template specialization declaration node for
3347 // this explicit specialization or friend declaration.
3348 Specialization = VarTemplateSpecializationDecl::Create(
3349 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
David Majnemer8b622692016-07-03 21:17:51 +00003350 VarTemplate, DI->getType(), DI, SC, Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003351 Specialization->setTemplateArgsInfo(TemplateArgs);
3352
3353 if (!PrevDecl)
3354 VarTemplate->AddSpecialization(Specialization, InsertPos);
3355 }
3356
3357 // C++ [temp.expl.spec]p6:
3358 // If a template, a member template or the member of a class template is
3359 // explicitly specialized then that specialization shall be declared
3360 // before the first use of that specialization that would cause an implicit
3361 // instantiation to take place, in every translation unit in which such a
3362 // use occurs; no diagnostic is required.
3363 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3364 bool Okay = false;
3365 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
3366 // Is there any previous explicit specialization declaration?
3367 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3368 Okay = true;
3369 break;
3370 }
3371 }
3372
3373 if (!Okay) {
3374 SourceRange Range(TemplateNameLoc, RAngleLoc);
3375 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3376 << Name << Range;
3377
3378 Diag(PrevDecl->getPointOfInstantiation(),
3379 diag::note_instantiation_required_here)
3380 << (PrevDecl->getTemplateSpecializationKind() !=
3381 TSK_ImplicitInstantiation);
3382 return true;
3383 }
3384 }
3385
3386 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
3387 Specialization->setLexicalDeclContext(CurContext);
3388
3389 // Add the specialization into its lexical context, so that it can
3390 // be seen when iterating through the list of declarations in that
3391 // context. However, specializations are not found by name lookup.
3392 CurContext->addDecl(Specialization);
3393
3394 // Note that this is an explicit specialization.
3395 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
3396
3397 if (PrevDecl) {
3398 // Check that this isn't a redefinition of this specialization,
3399 // merging with previous declarations.
3400 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
3401 ForRedeclaration);
3402 PrevSpec.addDecl(PrevDecl);
3403 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00003404 } else if (Specialization->isStaticDataMember() &&
3405 Specialization->isOutOfLine()) {
3406 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00003407 }
3408
3409 // Link instantiations of static data members back to the template from
3410 // which they were instantiated.
3411 if (Specialization->isStaticDataMember())
3412 Specialization->setInstantiationOfStaticDataMember(
3413 VarTemplate->getTemplatedDecl(),
3414 Specialization->getSpecializationKind());
3415
3416 return Specialization;
3417}
3418
3419namespace {
3420/// \brief A partial specialization whose template arguments have matched
3421/// a given template-id.
3422struct PartialSpecMatchResult {
3423 VarTemplatePartialSpecializationDecl *Partial;
3424 TemplateArgumentList *Args;
3425};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003426} // end anonymous namespace
Larisse Voufo39a1e502013-08-06 01:03:05 +00003427
3428DeclResult
3429Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
3430 SourceLocation TemplateNameLoc,
3431 const TemplateArgumentListInfo &TemplateArgs) {
3432 assert(Template && "A variable template id without template?");
3433
3434 // Check that the template argument list is well-formed for this template.
3435 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003436 if (CheckTemplateArgumentList(
3437 Template, TemplateNameLoc,
3438 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00003439 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00003440 return true;
3441
3442 // Find the variable template specialization declaration that
3443 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00003444 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003445 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Richard Smith6739a102016-05-05 00:56:12 +00003446 Converted, InsertPos)) {
3447 checkSpecializationVisibility(TemplateNameLoc, Spec);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003448 // If we already have a variable template specialization, return it.
3449 return Spec;
Richard Smith6739a102016-05-05 00:56:12 +00003450 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003451
3452 // This is the first time we have referenced this variable template
3453 // specialization. Create the canonical declaration and add it to
3454 // the set of specializations, based on the closest partial specialization
3455 // that it represents. That is,
3456 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
3457 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00003458 Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003459 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
3460 bool AmbiguousPartialSpec = false;
3461 typedef PartialSpecMatchResult MatchResult;
3462 SmallVector<MatchResult, 4> Matched;
3463 SourceLocation PointOfInstantiation = TemplateNameLoc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003464 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
3465 /*ForTakingAddress=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003466
3467 // 1. Attempt to find the closest partial specialization that this
3468 // specializes, if any.
3469 // If any of the template arguments is dependent, then this is probably
3470 // a placeholder for an incomplete declarative context; which must be
3471 // complete by instantiation time. Thus, do not search through the partial
3472 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00003473 // TODO: Unify with InstantiateClassTemplateSpecialization()?
3474 // Perhaps better after unification of DeduceTemplateArguments() and
3475 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00003476 bool InstantiationDependent = false;
3477 if (!TemplateSpecializationType::anyDependentTemplateArguments(
3478 TemplateArgs, InstantiationDependent)) {
3479
3480 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3481 Template->getPartialSpecializations(PartialSpecs);
3482
3483 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3484 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3485 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3486
3487 if (TemplateDeductionResult Result =
3488 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
3489 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00003490 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00003491 FailedCandidates.addCandidate().set(
3492 DeclAccessPair::make(Template, AS_public), Partial,
3493 MakeDeductionFailureInfo(Context, Result, Info));
Larisse Voufo39a1e502013-08-06 01:03:05 +00003494 (void)Result;
3495 } else {
3496 Matched.push_back(PartialSpecMatchResult());
3497 Matched.back().Partial = Partial;
3498 Matched.back().Args = Info.take();
3499 }
3500 }
3501
Larisse Voufo39a1e502013-08-06 01:03:05 +00003502 if (Matched.size() >= 1) {
3503 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
3504 if (Matched.size() == 1) {
3505 // -- If exactly one matching specialization is found, the
3506 // instantiation is generated from that specialization.
3507 // We don't need to do anything for this.
3508 } else {
3509 // -- If more than one matching specialization is found, the
3510 // partial order rules (14.5.4.2) are used to determine
3511 // whether one of the specializations is more specialized
3512 // than the others. If none of the specializations is more
3513 // specialized than all of the other matching
3514 // specializations, then the use of the variable template is
3515 // ambiguous and the program is ill-formed.
3516 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
3517 PEnd = Matched.end();
3518 P != PEnd; ++P) {
3519 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
3520 PointOfInstantiation) ==
3521 P->Partial)
3522 Best = P;
3523 }
3524
3525 // Determine if the best partial specialization is more specialized than
3526 // the others.
3527 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
3528 PEnd = Matched.end();
3529 P != PEnd; ++P) {
3530 if (P != Best && getMoreSpecializedPartialSpecialization(
3531 P->Partial, Best->Partial,
3532 PointOfInstantiation) != Best->Partial) {
3533 AmbiguousPartialSpec = true;
3534 break;
3535 }
3536 }
3537 }
3538
3539 // Instantiate using the best variable template partial specialization.
3540 InstantiationPattern = Best->Partial;
3541 InstantiationArgs = Best->Args;
3542 } else {
3543 // -- If no match is found, the instantiation is generated
3544 // from the primary template.
3545 // InstantiationPattern = Template->getTemplatedDecl();
3546 }
3547 }
3548
Larisse Voufo39a1e502013-08-06 01:03:05 +00003549 // 2. Create the canonical declaration.
Richard Smith6739a102016-05-05 00:56:12 +00003550 // Note that we do not instantiate a definition until we see an odr-use
3551 // in DoMarkVarDeclReferenced().
Larisse Voufo39a1e502013-08-06 01:03:05 +00003552 // FIXME: LateAttrs et al.?
3553 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
3554 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
3555 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
3556 if (!Decl)
3557 return true;
3558
3559 if (AmbiguousPartialSpec) {
3560 // Partial ordering did not produce a clear winner. Complain.
3561 Decl->setInvalidDecl();
3562 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
3563 << Decl;
3564
3565 // Print the matching partial specializations.
Yaron Keren1cb81462016-11-16 13:45:34 +00003566 for (MatchResult P : Matched)
3567 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
3568 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
3569 *P.Args);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003570 return true;
3571 }
3572
3573 if (VarTemplatePartialSpecializationDecl *D =
3574 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
3575 Decl->setInstantiationOf(D, InstantiationArgs);
3576
Richard Smith6739a102016-05-05 00:56:12 +00003577 checkSpecializationVisibility(TemplateNameLoc, Decl);
3578
Larisse Voufo39a1e502013-08-06 01:03:05 +00003579 assert(Decl && "No variable template specialization?");
3580 return Decl;
3581}
3582
3583ExprResult
3584Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
3585 const DeclarationNameInfo &NameInfo,
3586 VarTemplateDecl *Template, SourceLocation TemplateLoc,
3587 const TemplateArgumentListInfo *TemplateArgs) {
3588
3589 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
3590 *TemplateArgs);
3591 if (Decl.isInvalid())
3592 return ExprError();
3593
3594 VarDecl *Var = cast<VarDecl>(Decl.get());
3595 if (!Var->getTemplateSpecializationKind())
3596 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
3597 NameInfo.getLoc());
3598
3599 // Build an ordinary singleton decl ref.
3600 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00003601 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003602}
3603
John McCalldadc5752010-08-24 06:29:42 +00003604ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003605 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00003606 LookupResult &R,
3607 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003608 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00003609 // FIXME: Can we do any checking at this point? I guess we could check the
3610 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00003611 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00003612 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00003613 // foo<int> could identify a single function unambiguously
3614 // This approach does NOT work, since f<int>(1);
3615 // gets resolved prior to resorting to overload resolution
3616 // i.e., template<class T> void f(double);
3617 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00003618
3619 // These should be filtered out by our callers.
3620 assert(!R.empty() && "empty lookup results when building templateid");
3621 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
3622
Larisse Voufo39a1e502013-08-06 01:03:05 +00003623 // In C++1y, check variable template ids.
Richard Smithd7d11ef2014-02-03 20:09:56 +00003624 bool InstantiationDependent;
3625 if (R.getAsSingle<VarTemplateDecl>() &&
3626 !TemplateSpecializationType::anyDependentTemplateArguments(
3627 *TemplateArgs, InstantiationDependent)) {
3628 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
3629 R.getAsSingle<VarTemplateDecl>(),
3630 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003631 }
3632
John McCall58cc69d2010-01-27 01:50:18 +00003633 // We don't want lookup warnings at this point.
3634 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003635
John McCalle66edc12009-11-24 19:00:30 +00003636 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00003637 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00003638 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003639 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003640 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003641 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00003642 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00003643
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003644 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00003645}
3646
John McCalle66edc12009-11-24 19:00:30 +00003647// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00003648ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003649Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003650 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003651 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003652 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003653
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003654 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00003655 DeclContext *DC;
3656 if (!(DC = computeDeclContext(SS, false)) ||
3657 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00003658 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00003659 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003660
Douglas Gregor786123d2010-05-21 23:18:07 +00003661 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003662 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Craig Topperc3ec1492014-05-26 06:22:03 +00003663 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
Douglas Gregor786123d2010-05-21 23:18:07 +00003664 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00003665
John McCalle66edc12009-11-24 19:00:30 +00003666 if (R.isAmbiguous())
3667 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003668
John McCalle66edc12009-11-24 19:00:30 +00003669 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003670 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
3671 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00003672 return ExprError();
3673 }
3674
3675 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003676 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00003677 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00003678 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00003679 Diag(Temp->getLocation(), diag::note_referenced_class_template);
3680 return ExprError();
3681 }
3682
Abramo Bagnara7945c982012-01-27 09:46:47 +00003683 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00003684}
3685
Douglas Gregorb67535d2009-03-31 00:43:58 +00003686/// \brief Form a dependent template name.
3687///
3688/// This action forms a dependent template name given the template
3689/// name and its (presumably dependent) scope specifier. For
3690/// example, given "MetaFun::template apply", the scope specifier \p
3691/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
3692/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003693TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00003694 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003695 SourceLocation TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00003696 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00003697 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00003698 bool EnteringContext,
Richard Smithfd3dae02017-01-20 00:20:39 +00003699 TemplateTy &Result,
3700 bool AllowInjectedClassName) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00003701 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
3702 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003703 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00003704 diag::warn_cxx98_compat_template_outside_of_template :
3705 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003706 << FixItHint::CreateRemoval(TemplateKWLoc);
3707
Craig Topperc3ec1492014-05-26 06:22:03 +00003708 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00003709 if (SS.isSet())
3710 LookupCtx = computeDeclContext(SS, EnteringContext);
3711 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00003712 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00003713 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00003714 // C++0x [temp.names]p5:
3715 // If a name prefixed by the keyword template is not the name of
3716 // a template, the program is ill-formed. [Note: the keyword
3717 // template may not be applied to non-template members of class
3718 // templates. -end note ] [ Note: as is the case with the
3719 // typename prefix, the template prefix is allowed in cases
3720 // where it is not strictly necessary; i.e., when the
3721 // nested-name-specifier or the expression on the left of the ->
3722 // or . is not dependent on a template-parameter, or the use
3723 // does not appear in the scope of a template. -end note]
3724 //
3725 // Note: C++03 was more strict here, because it banned the use of
3726 // the "template" keyword prior to a template-name that was not a
3727 // dependent name. C++ DR468 relaxed this requirement (the
3728 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00003729 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00003730 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00003731 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00003732 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00003733 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00003734 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
3735 isa<CXXRecordDecl>(LookupCtx) &&
Douglas Gregor5ecbb1b2011-03-11 23:27:41 +00003736 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
3737 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
Douglas Gregorbb119652010-06-16 23:00:59 +00003738 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00003739 } else if (TNK == TNK_Non_template) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003740 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003741 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003742 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003743 << Name.getSourceRange()
3744 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003745 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00003746 } else {
3747 // We found something; return it.
Richard Smithfd3dae02017-01-20 00:20:39 +00003748 auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
3749 if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
3750 Name.getKind() == UnqualifiedId::IK_Identifier && Name.Identifier &&
3751 LookupRD->getIdentifier() == Name.Identifier) {
3752 // C++14 [class.qual]p2:
3753 // In a lookup in which function names are not ignored and the
3754 // nested-name-specifier nominates a class C, if the name specified
3755 // [...] is the injected-class-name of C, [...] the name is instead
3756 // considered to name the constructor
3757 //
3758 // We don't get here if naming the constructor would be valid, so we
3759 // just reject immediately and recover by treating the
3760 // injected-class-name as naming the template.
3761 Diag(Name.getLocStart(),
3762 diag::ext_out_of_line_qualified_id_type_names_constructor)
3763 << Name.Identifier << 0 /*injected-class-name used as template name*/
3764 << 1 /*'template' keyword was used*/;
3765 }
Douglas Gregorbb119652010-06-16 23:00:59 +00003766 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003767 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00003768 }
3769
Aaron Ballman4a979672014-01-03 13:56:08 +00003770 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003771
Douglas Gregor3cf81312009-11-03 23:16:33 +00003772 switch (Name.getKind()) {
3773 case UnqualifiedId::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003774 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00003775 Name.Identifier));
3776 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003777
Douglas Gregor71395fa2009-11-04 00:56:37 +00003778 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00003779 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00003780 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00003781 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00003782
3783 case UnqualifiedId::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00003784 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00003785
Douglas Gregor3cf81312009-11-03 23:16:33 +00003786 default:
3787 break;
3788 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003789
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003790 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003791 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003792 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003793 << Name.getSourceRange()
3794 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003795 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003796}
3797
Mike Stump11289f42009-09-09 15:08:12 +00003798bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003799 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003800 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00003801 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00003802 QualType ArgType;
3803 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00003804
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003805 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003806 switch(Arg.getKind()) {
3807 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003808 // C++ [temp.arg.type]p1:
3809 // A template-argument for a template-parameter which is a
3810 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00003811 ArgType = Arg.getAsType();
3812 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003813 break;
3814 case TemplateArgument::Template: {
3815 // We have a template type parameter but the template argument
3816 // is a template without any arguments.
3817 SourceRange SR = AL.getSourceRange();
3818 TemplateName Name = Arg.getAsTemplate();
3819 Diag(SR.getBegin(), diag::err_template_missing_args)
Richard Smith0c062b42017-01-14 02:19:59 +00003820 << (int)getTemplateNameKindForDiagnostics(Name) << Name << SR;
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003821 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3822 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003823
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003824 return true;
3825 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003826 case TemplateArgument::Expression: {
3827 // We have a template type parameter but the template argument is an
3828 // expression; see if maybe it is missing the "typename" keyword.
3829 CXXScopeSpec SS;
3830 DeclarationNameInfo NameInfo;
3831
3832 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3833 SS.Adopt(ArgExpr->getQualifierLoc());
3834 NameInfo = ArgExpr->getNameInfo();
3835 } else if (DependentScopeDeclRefExpr *ArgExpr =
3836 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3837 SS.Adopt(ArgExpr->getQualifierLoc());
3838 NameInfo = ArgExpr->getNameInfo();
3839 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3840 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003841 if (ArgExpr->isImplicitAccess()) {
3842 SS.Adopt(ArgExpr->getQualifierLoc());
3843 NameInfo = ArgExpr->getMemberNameInfo();
3844 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003845 }
3846
Reid Kleckner377c1592014-06-10 23:29:48 +00003847 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003848 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3849 LookupParsedName(Result, CurScope, &SS);
3850
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003851 if (Result.getAsSingle<TypeDecl>() ||
3852 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00003853 LookupResult::NotFoundInCurrentInstantiation) {
3854 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003855 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00003856 Diag(Loc, getLangOpts().MSVCCompat
3857 ? diag::ext_ms_template_type_arg_missing_typename
3858 : diag::err_template_arg_must_be_type_suggest)
3859 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003860 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00003861
3862 // Recover by synthesizing a type using the location information that we
3863 // already have.
3864 ArgType =
3865 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3866 TypeLocBuilder TLB;
3867 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3868 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3869 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3870 TL.setNameLoc(NameInfo.getLoc());
3871 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3872
3873 // Overwrite our input TemplateArgumentLoc so that we can recover
3874 // properly.
3875 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3876 TemplateArgumentLocInfo(TSI));
3877
3878 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003879 }
3880 }
3881 // fallthrough
3882 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003883 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003884 // We have a template type parameter but the template argument
3885 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00003886 SourceRange SR = AL.getSourceRange();
3887 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003888 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003889
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003890 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003891 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003892 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003893
Reid Kleckner377c1592014-06-10 23:29:48 +00003894 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003895 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003896
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003897 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00003898 ArgType = Context.getCanonicalType(ArgType);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003899
Douglas Gregore46db902011-06-17 22:11:49 +00003900 // Objective-C ARC:
3901 // If an explicitly-specified template argument type is a lifetime type
3902 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003903 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00003904 ArgType->isObjCLifetimeType() &&
3905 !ArgType.getObjCLifetime()) {
3906 Qualifiers Qs;
3907 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3908 ArgType = Context.getQualifiedType(ArgType, Qs);
3909 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003910
Douglas Gregore46db902011-06-17 22:11:49 +00003911 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003912 return false;
3913}
3914
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003915/// \brief Substitute template arguments into the default template argument for
3916/// the given template type parameter.
3917///
3918/// \param SemaRef the semantic analysis object for which we are performing
3919/// the substitution.
3920///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003921/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003922/// for.
3923///
3924/// \param TemplateLoc the location of the template name that started the
3925/// template-id we are checking.
3926///
3927/// \param RAngleLoc the location of the right angle bracket ('>') that
3928/// terminates the template-id.
3929///
3930/// \param Param the template template parameter whose default we are
3931/// substituting into.
3932///
3933/// \param Converted the list of template arguments provided for template
3934/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003935/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00003936static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003937SubstDefaultTemplateArgument(Sema &SemaRef,
3938 TemplateDecl *Template,
3939 SourceLocation TemplateLoc,
3940 SourceLocation RAngleLoc,
3941 TemplateTypeParmDecl *Param,
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00003942 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00003943 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003944
3945 // If the argument type is dependent, instantiate it now based
3946 // on the previously-computed template arguments.
3947 if (ArgType->getType()->isDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003948 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00003949 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003950 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003951 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00003952 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003953
David Majnemer8b622692016-07-03 21:17:51 +00003954 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00003955
3956 // Only substitute for the innermost template argument list.
3957 MultiLevelTemplateArgumentList TemplateArgLists;
3958 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3959 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3960 TemplateArgLists.addOuterTemplateArguments(None);
3961
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003962 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003963 ArgType =
3964 SemaRef.SubstType(ArgType, TemplateArgLists,
3965 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003966 }
3967
3968 return ArgType;
3969}
3970
3971/// \brief Substitute template arguments into the default template argument for
3972/// the given non-type template parameter.
3973///
3974/// \param SemaRef the semantic analysis object for which we are performing
3975/// the substitution.
3976///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003977/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003978/// for.
3979///
3980/// \param TemplateLoc the location of the template name that started the
3981/// template-id we are checking.
3982///
3983/// \param RAngleLoc the location of the right angle bracket ('>') that
3984/// terminates the template-id.
3985///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003986/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003987/// substituting into.
3988///
3989/// \param Converted the list of template arguments provided for template
3990/// parameters that precede \p Param in the template parameter list.
3991///
3992/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00003993static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003994SubstDefaultTemplateArgument(Sema &SemaRef,
3995 TemplateDecl *Template,
3996 SourceLocation TemplateLoc,
3997 SourceLocation RAngleLoc,
3998 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003999 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004000 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00004001 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004002 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004003 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004004 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004005
David Majnemer8b622692016-07-03 21:17:51 +00004006 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004007
4008 // Only substitute for the innermost template argument list.
4009 MultiLevelTemplateArgumentList TemplateArgLists;
4010 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4011 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4012 TemplateArgLists.addOuterTemplateArguments(None);
4013
Faisal Vali48401eb2015-11-19 19:20:17 +00004014 EnterExpressionEvaluationContext ConstantEvaluated(SemaRef,
4015 Sema::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00004016 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004017}
4018
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004019/// \brief Substitute template arguments into the default template argument for
4020/// the given template template parameter.
4021///
4022/// \param SemaRef the semantic analysis object for which we are performing
4023/// the substitution.
4024///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004025/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004026/// for.
4027///
4028/// \param TemplateLoc the location of the template name that started the
4029/// template-id we are checking.
4030///
4031/// \param RAngleLoc the location of the right angle bracket ('>') that
4032/// terminates the template-id.
4033///
4034/// \param Param the template template parameter whose default we are
4035/// substituting into.
4036///
4037/// \param Converted the list of template arguments provided for template
4038/// parameters that precede \p Param in the template parameter list.
4039///
Simon Pilgrim6905d222016-12-30 22:55:33 +00004040/// \param QualifierLoc Will be set to the nested-name-specifier (with
Douglas Gregordf846d12011-03-02 18:46:51 +00004041/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00004042///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004043/// \returns the substituted template argument, or NULL if an error occurred.
4044static TemplateName
4045SubstDefaultTemplateArgument(Sema &SemaRef,
4046 TemplateDecl *Template,
4047 SourceLocation TemplateLoc,
4048 SourceLocation RAngleLoc,
4049 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004050 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00004051 NestedNameSpecifierLoc &QualifierLoc) {
Richard Smith54f18e82016-08-31 02:15:21 +00004052 Sema::InstantiatingTemplate Inst(
4053 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
4054 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004055 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004056 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004057
David Majnemer8b622692016-07-03 21:17:51 +00004058 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004059
4060 // Only substitute for the innermost template argument list.
4061 MultiLevelTemplateArgumentList TemplateArgLists;
4062 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4063 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4064 TemplateArgLists.addOuterTemplateArguments(None);
4065
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00004066 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00004067 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00004068 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00004069 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00004070 QualifierLoc =
4071 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00004072 if (!QualifierLoc)
4073 return TemplateName();
4074 }
David Majnemer89189202013-08-28 23:48:32 +00004075
4076 return SemaRef.SubstTemplateName(
4077 QualifierLoc,
4078 Param->getDefaultArgument().getArgument().getAsTemplate(),
4079 Param->getDefaultArgument().getTemplateNameLoc(),
4080 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004081}
4082
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004083/// \brief If the given template parameter has a default template
4084/// argument, substitute into that default template argument and
4085/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004086TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004087Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
4088 SourceLocation TemplateLoc,
4089 SourceLocation RAngleLoc,
4090 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00004091 SmallVectorImpl<TemplateArgument>
4092 &Converted,
4093 bool &HasDefaultArg) {
4094 HasDefaultArg = false;
4095
4096 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004097 if (!hasVisibleDefaultArgument(TypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004098 return TemplateArgumentLoc();
4099
Richard Smithc87b9382013-07-04 01:01:24 +00004100 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00004101 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004102 TemplateLoc,
4103 RAngleLoc,
4104 TypeParm,
4105 Converted);
4106 if (DI)
4107 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4108
4109 return TemplateArgumentLoc();
4110 }
4111
4112 if (NonTypeTemplateParmDecl *NonTypeParm
4113 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004114 if (!hasVisibleDefaultArgument(NonTypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004115 return TemplateArgumentLoc();
4116
Richard Smithc87b9382013-07-04 01:01:24 +00004117 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00004118 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00004119 TemplateLoc,
4120 RAngleLoc,
4121 NonTypeParm,
4122 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004123 if (Arg.isInvalid())
4124 return TemplateArgumentLoc();
4125
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004126 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004127 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
4128 }
4129
4130 TemplateTemplateParmDecl *TempTempParm
4131 = cast<TemplateTemplateParmDecl>(Param);
Richard Smith95d83952015-06-10 20:36:34 +00004132 if (!hasVisibleDefaultArgument(TempTempParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004133 return TemplateArgumentLoc();
4134
Richard Smithc87b9382013-07-04 01:01:24 +00004135 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00004136 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004137 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004138 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004139 RAngleLoc,
4140 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00004141 Converted,
4142 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004143 if (TName.isNull())
4144 return TemplateArgumentLoc();
4145
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004146 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00004147 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004148 TempTempParm->getDefaultArgument().getTemplateNameLoc());
4149}
4150
Richard Smith11255ec2017-01-18 19:19:22 +00004151/// Convert a template-argument that we parsed as a type into a template, if
4152/// possible. C++ permits injected-class-names to perform dual service as
4153/// template template arguments and as template type arguments.
4154static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
4155 // Extract and step over any surrounding nested-name-specifier.
4156 NestedNameSpecifierLoc QualLoc;
4157 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4158 if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
4159 return TemplateArgumentLoc();
4160
4161 QualLoc = ETLoc.getQualifierLoc();
4162 TLoc = ETLoc.getNamedTypeLoc();
4163 }
4164
4165 // If this type was written as an injected-class-name, it can be used as a
4166 // template template argument.
4167 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4168 return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
4169 QualLoc, InjLoc.getNameLoc());
4170
4171 // If this type was written as an injected-class-name, it may have been
4172 // converted to a RecordType during instantiation. If the RecordType is
4173 // *not* wrapped in a TemplateSpecializationType and denotes a class
4174 // template specialization, it must have come from an injected-class-name.
4175 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
4176 if (auto *CTSD =
4177 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
4178 return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
4179 QualLoc, RecLoc.getNameLoc());
4180
4181 return TemplateArgumentLoc();
4182}
4183
Douglas Gregorda0fb532009-11-11 19:31:23 +00004184/// \brief Check that the given template argument corresponds to the given
4185/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004186///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004187/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004188/// checked.
4189///
Richard Trieu15b66532015-01-24 02:48:32 +00004190/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004191///
4192/// \param Template The template in which the template argument resides.
4193///
4194/// \param TemplateLoc The location of the template name for the template
4195/// whose argument list we're matching.
4196///
4197/// \param RAngleLoc The location of the right angle bracket ('>') that closes
4198/// the template argument list.
4199///
4200/// \param ArgumentPackIndex The index into the argument pack where this
4201/// argument will be placed. Only valid if the parameter is a parameter pack.
4202///
4203/// \param Converted The checked, converted argument will be added to the
4204/// end of this small vector.
4205///
4206/// \param CTAK Describes how we arrived at this particular template argument:
4207/// explicitly written, deduced, etc.
4208///
4209/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004210bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00004211 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00004212 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004213 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004214 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004215 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004216 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00004217 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00004218 // Check template type parameters.
4219 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004220 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004221
Douglas Gregoreebed722009-11-11 19:41:09 +00004222 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004223 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004224 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00004225 // with the template arguments we've seen thus far. But if the
4226 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004227 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004228 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
4229 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004230
Peter Collingbourne01687632010-12-10 17:08:53 +00004231 if (NTTPType->isDependentType() &&
4232 !isa<TemplateTemplateParmDecl>(Template) &&
4233 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004234 // Do substitution on the type of the non-type template parameter.
4235 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00004236 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004237 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004238 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004239 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004240
4241 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00004242 Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004243 NTTPType = SubstType(NTTPType,
4244 MultiLevelTemplateArgumentList(TemplateArgs),
4245 NTTP->getLocation(),
4246 NTTP->getDeclName());
4247 // If that worked, check the non-type template parameter type
4248 // for validity.
4249 if (!NTTPType.isNull())
4250 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
4251 NTTP->getLocation());
4252 if (NTTPType.isNull())
4253 return true;
4254 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004255
Douglas Gregorda0fb532009-11-11 19:31:23 +00004256 switch (Arg.getArgument().getKind()) {
4257 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00004258 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004259
Douglas Gregorda0fb532009-11-11 19:31:23 +00004260 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004261 TemplateArgument Result;
John Wiegley01296292011-04-08 18:41:53 +00004262 ExprResult Res =
4263 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
4264 Result, CTAK);
4265 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00004266 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004267
Richard Trieu15b66532015-01-24 02:48:32 +00004268 // If the resulting expression is new, then use it in place of the
4269 // old expression in the template argument.
4270 if (Res.get() != Arg.getArgument().getAsExpr()) {
4271 TemplateArgument TA(Res.get());
4272 Arg = TemplateArgumentLoc(TA, Res.get());
4273 }
4274
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004275 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004276 break;
4277 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004278
Douglas Gregorda0fb532009-11-11 19:31:23 +00004279 case TemplateArgument::Declaration:
4280 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00004281 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00004282 // We've already checked this template argument, so just copy
4283 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004284 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00004285 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004286
Douglas Gregorda0fb532009-11-11 19:31:23 +00004287 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004288 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00004289 // We were given a template template argument. It may not be ill-formed;
4290 // see below.
4291 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004292 = Arg.getArgument().getAsTemplateOrTemplatePattern()
4293 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004294 // We have a template argument such as \c T::template X, which we
4295 // parsed as a template template argument. However, since we now
4296 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004297 // template name into an expression.
4298
4299 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
4300 Arg.getTemplateNameLoc());
4301
Douglas Gregor3a43fd62011-02-25 20:49:16 +00004302 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00004303 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00004304 // FIXME: the template-template arg was a DependentTemplateName,
4305 // so it was provided with a template keyword. However, its source
4306 // location is not stored in the template argument structure.
4307 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004308 ExprResult E = DependentScopeDeclRefExpr::Create(
4309 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
4310 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004311
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004312 // If we parsed the template argument as a pack expansion, create a
4313 // pack expansion expression.
4314 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004315 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00004316 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004317 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004318 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004319
Douglas Gregorda0fb532009-11-11 19:31:23 +00004320 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004321 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00004322 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00004323 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004324
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004325 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004326 break;
4327 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004328
Douglas Gregorda0fb532009-11-11 19:31:23 +00004329 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00004330 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00004331 // therefore cannot be a non-type template argument.
4332 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
4333 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004334
Douglas Gregorda0fb532009-11-11 19:31:23 +00004335 Diag(Param->getLocation(), diag::note_template_param_here);
4336 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004337
Douglas Gregorda0fb532009-11-11 19:31:23 +00004338 case TemplateArgument::Type: {
4339 // We have a non-type template parameter but the template
4340 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004341
Douglas Gregorda0fb532009-11-11 19:31:23 +00004342 // C++ [temp.arg]p2:
4343 // In a template-argument, an ambiguity between a type-id and
4344 // an expression is resolved to a type-id, regardless of the
4345 // form of the corresponding template-parameter.
4346 //
4347 // We warn specifically about this case, since it can be rather
4348 // confusing for users.
4349 QualType T = Arg.getArgument().getAsType();
4350 SourceRange SR = Arg.getSourceRange();
4351 if (T->isFunctionType())
4352 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
4353 else
4354 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
4355 Diag(Param->getLocation(), diag::note_template_param_here);
4356 return true;
4357 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004358
Douglas Gregorda0fb532009-11-11 19:31:23 +00004359 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004360 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004361 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004362
Douglas Gregorda0fb532009-11-11 19:31:23 +00004363 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004364 }
4365
4366
Douglas Gregorda0fb532009-11-11 19:31:23 +00004367 // Check template template parameters.
4368 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004369
Douglas Gregorda0fb532009-11-11 19:31:23 +00004370 // Substitute into the template parameter list of the template
4371 // template parameter, since previously-supplied template arguments
4372 // may appear within the template template parameter.
4373 {
4374 // Set up a template instantiation context.
4375 LocalInstantiationScope Scope(*this);
4376 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00004377 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004378 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004379 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004380 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004381
David Majnemer8b622692016-07-03 21:17:51 +00004382 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004383 TempParm = cast_or_null<TemplateTemplateParmDecl>(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004384 SubstDecl(TempParm, CurContext,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004385 MultiLevelTemplateArgumentList(TemplateArgs)));
4386 if (!TempParm)
4387 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00004388 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004389
Richard Smith11255ec2017-01-18 19:19:22 +00004390 // C++1z [temp.local]p1: (DR1004)
4391 // When [the injected-class-name] is used [...] as a template-argument for
4392 // a template template-parameter [...] it refers to the class template
4393 // itself.
4394 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
4395 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
4396 Arg.getTypeSourceInfo()->getTypeLoc());
4397 if (!ConvertedArg.getArgument().isNull())
4398 Arg = ConvertedArg;
4399 }
4400
Douglas Gregorda0fb532009-11-11 19:31:23 +00004401 switch (Arg.getArgument().getKind()) {
4402 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00004403 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004404
Douglas Gregorda0fb532009-11-11 19:31:23 +00004405 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004406 case TemplateArgument::TemplateExpansion:
Richard Smith1fde8ec2012-09-07 02:06:42 +00004407 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004408 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004409
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004410 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00004411 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004412
Douglas Gregorda0fb532009-11-11 19:31:23 +00004413 case TemplateArgument::Expression:
4414 case TemplateArgument::Type:
4415 // We have a template template parameter but the template
4416 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004417 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004418 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00004419 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004420
Douglas Gregorda0fb532009-11-11 19:31:23 +00004421 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00004422 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004423 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00004424 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00004425 case TemplateArgument::NullPtr:
4426 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004427
Douglas Gregorda0fb532009-11-11 19:31:23 +00004428 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004429 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004430 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004431
Douglas Gregorda0fb532009-11-11 19:31:23 +00004432 return false;
4433}
4434
Simon Pilgrim6905d222016-12-30 22:55:33 +00004435/// \brief Diagnose an arity mismatch in the
Douglas Gregor8e072612012-02-03 07:34:46 +00004436static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
4437 SourceLocation TemplateLoc,
4438 TemplateArgumentListInfo &TemplateArgs) {
4439 TemplateParameterList *Params = Template->getTemplateParameters();
4440 unsigned NumParams = Params->size();
4441 unsigned NumArgs = TemplateArgs.size();
4442
4443 SourceRange Range;
4444 if (NumArgs > NumParams)
Simon Pilgrim6905d222016-12-30 22:55:33 +00004445 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
Douglas Gregor8e072612012-02-03 07:34:46 +00004446 TemplateArgs.getRAngleLoc());
4447 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4448 << (NumArgs > NumParams)
Richard Smith0c062b42017-01-14 02:19:59 +00004449 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(Template))
Douglas Gregor8e072612012-02-03 07:34:46 +00004450 << Template << Range;
4451 S.Diag(Template->getLocation(), diag::note_template_decl_here)
4452 << Params->getSourceRange();
4453 return true;
4454}
4455
Richard Smith1fde8ec2012-09-07 02:06:42 +00004456/// \brief Check whether the template parameter is a pack expansion, and if so,
4457/// determine the number of parameters produced by that expansion. For instance:
4458///
4459/// \code
4460/// template<typename ...Ts> struct A {
4461/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
4462/// };
4463/// \endcode
4464///
4465/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
4466/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00004467static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00004468 if (NonTypeTemplateParmDecl *NTTP
4469 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4470 if (NTTP->isExpandedParameterPack())
4471 return NTTP->getNumExpansionTypes();
4472 }
4473
4474 if (TemplateTemplateParmDecl *TTP
4475 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
4476 if (TTP->isExpandedParameterPack())
4477 return TTP->getNumExpansionTemplateParameters();
4478 }
4479
David Blaikie7a30dc52013-02-21 01:47:18 +00004480 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00004481}
4482
Richard Smith35c1df52015-06-17 20:16:32 +00004483/// Diagnose a missing template argument.
4484template<typename TemplateParmDecl>
4485static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
4486 TemplateDecl *TD,
4487 const TemplateParmDecl *D,
4488 TemplateArgumentListInfo &Args) {
4489 // Dig out the most recent declaration of the template parameter; there may be
4490 // declarations of the template that are more recent than TD.
4491 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
4492 ->getTemplateParameters()
4493 ->getParam(D->getIndex()));
4494
4495 // If there's a default argument that's not visible, diagnose that we're
4496 // missing a module import.
4497 llvm::SmallVector<Module*, 8> Modules;
4498 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
4499 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
4500 D->getDefaultArgumentLoc(), Modules,
4501 Sema::MissingImportKind::DefaultArgument,
Richard Smith6739a102016-05-05 00:56:12 +00004502 /*Recover*/true);
Richard Smith35c1df52015-06-17 20:16:32 +00004503 return true;
4504 }
4505
4506 // FIXME: If there's a more recent default argument that *is* visible,
4507 // diagnose that it was declared too late.
4508
4509 return diagnoseArityMismatch(S, TD, Loc, Args);
4510}
4511
Douglas Gregord32e0282009-02-09 23:23:08 +00004512/// \brief Check that the given template argument list is well-formed
4513/// for specializing the given template.
Richard Smith11255ec2017-01-18 19:19:22 +00004514bool Sema::CheckTemplateArgumentList(
4515 TemplateDecl *Template, SourceLocation TemplateLoc,
4516 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
4517 SmallVectorImpl<TemplateArgument> &Converted,
4518 bool UpdateArgsWithConversions) {
Richard Trieu15b66532015-01-24 02:48:32 +00004519 // Make a copy of the template arguments for processing. Only make the
4520 // changes at the end when successful in matching the arguments to the
4521 // template.
4522 TemplateArgumentListInfo NewArgs = TemplateArgs;
4523
Douglas Gregord32e0282009-02-09 23:23:08 +00004524 TemplateParameterList *Params = Template->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00004525
Richard Trieu15b66532015-01-24 02:48:32 +00004526 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00004527
Mike Stump11289f42009-09-09 15:08:12 +00004528 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00004529 // [...] The type and form of each template-argument specified in
4530 // a template-id shall match the type and form specified for the
4531 // corresponding parameter declared by the template in its
4532 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00004533 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004534 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00004535 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00004536 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00004537 for (TemplateParameterList::iterator Param = Params->begin(),
4538 ParamEnd = Params->end();
4539 Param != ParamEnd; /* increment in loop */) {
4540 // If we have an expanded parameter pack, make sure we don't have too
4541 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00004542 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00004543 if (*Expansions == ArgumentPack.size()) {
4544 // We're done with this parameter pack. Pack up its arguments and add
4545 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00004546 Converted.push_back(
Benjamin Kramercce63472015-08-05 09:40:22 +00004547 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00004548 ArgumentPack.clear();
4549
Richard Smith1fde8ec2012-09-07 02:06:42 +00004550 // This argument is assigned to the next parameter.
4551 ++Param;
4552 continue;
4553 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
4554 // Not enough arguments for this parameter pack.
4555 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4556 << false
Richard Smith0c062b42017-01-14 02:19:59 +00004557 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
Richard Smith1fde8ec2012-09-07 02:06:42 +00004558 << Template;
4559 Diag(Template->getLocation(), diag::note_template_decl_here)
4560 << Params->getSourceRange();
4561 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004562 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00004563 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004564
Richard Smith1fde8ec2012-09-07 02:06:42 +00004565 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00004566 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00004567 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004568 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004569 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00004570 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004571
Richard Smith96d71c32014-11-12 23:38:38 +00004572 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00004573 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00004574 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
4575 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00004576 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00004577 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00004578 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00004579 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00004580 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00004581 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00004582 Diag((*Param)->getLocation(), diag::note_template_param_here);
4583 return true;
4584 }
4585
Richard Smith1fde8ec2012-09-07 02:06:42 +00004586 // We're now done with this argument.
4587 ++ArgIdx;
4588
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004589 if ((*Param)->isTemplateParameterPack()) {
4590 // The template parameter was a template parameter pack, so take the
4591 // deduced argument and place it on the argument pack. Note that we
4592 // stay on the same template parameter so that we can deduce more
4593 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00004594 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004595 } else {
4596 // Move to the next template parameter.
4597 ++Param;
4598 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00004599
Richard Smith96d71c32014-11-12 23:38:38 +00004600 // If we just saw a pack expansion into a non-pack, then directly convert
4601 // the remaining arguments, because we don't know what parameters they'll
4602 // match up with.
4603 if (PackExpansionIntoNonPack) {
4604 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00004605 // If we were part way through filling in an expanded parameter pack,
4606 // fall back to just producing individual arguments.
4607 Converted.insert(Converted.end(),
4608 ArgumentPack.begin(), ArgumentPack.end());
4609 ArgumentPack.clear();
4610 }
4611
4612 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00004613 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00004614 ++ArgIdx;
4615 }
4616
Richard Smith1fde8ec2012-09-07 02:06:42 +00004617 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00004618 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00004619
Douglas Gregor84d49a22009-11-11 21:54:23 +00004620 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00004621 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004622
Douglas Gregor2f157c92011-06-03 02:59:40 +00004623 // If we're checking a partial template argument list, we're done.
4624 if (PartialTemplateArgs) {
4625 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
Benjamin Kramercce63472015-08-05 09:40:22 +00004626 Converted.push_back(
4627 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4628
Richard Smith1fde8ec2012-09-07 02:06:42 +00004629 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00004630 }
4631
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004632 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004633 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00004634 if ((*Param)->isTemplateParameterPack()) {
4635 assert(!getExpandedPackSize(*Param) &&
4636 "Should have dealt with this already");
4637
4638 // A non-expanded parameter pack before the end of the parameter list
4639 // only occurs for an ill-formed template parameter list, unless we've
4640 // got a partial argument list for a function template, so just bail out.
4641 if (Param + 1 != ParamEnd)
4642 return true;
4643
Benjamin Kramercce63472015-08-05 09:40:22 +00004644 Converted.push_back(
4645 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00004646 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00004647
4648 ++Param;
4649 continue;
4650 }
4651
Douglas Gregor8e072612012-02-03 07:34:46 +00004652 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00004653 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004654
Douglas Gregor84d49a22009-11-11 21:54:23 +00004655 // Retrieve the default template argument from the template
4656 // parameter. For each kind of template parameter, we substitute the
4657 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004658 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00004659 // the default argument.
4660 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004661 if (!hasVisibleDefaultArgument(TTP))
Richard Smith35c1df52015-06-17 20:16:32 +00004662 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
4663 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004664
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004665 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004666 Template,
4667 TemplateLoc,
4668 RAngleLoc,
4669 TTP,
4670 Converted);
4671 if (!ArgType)
4672 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004673
Douglas Gregor84d49a22009-11-11 21:54:23 +00004674 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
4675 ArgType);
4676 } else if (NonTypeTemplateParmDecl *NTTP
4677 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004678 if (!hasVisibleDefaultArgument(NTTP))
Richard Smith35c1df52015-06-17 20:16:32 +00004679 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
4680 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004681
John McCalldadc5752010-08-24 06:29:42 +00004682 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004683 TemplateLoc,
4684 RAngleLoc,
4685 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004686 Converted);
4687 if (E.isInvalid())
4688 return true;
4689
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004690 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00004691 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
4692 } else {
4693 TemplateTemplateParmDecl *TempParm
4694 = cast<TemplateTemplateParmDecl>(*Param);
4695
Richard Smith95d83952015-06-10 20:36:34 +00004696 if (!hasVisibleDefaultArgument(TempParm))
Richard Smith35c1df52015-06-17 20:16:32 +00004697 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
4698 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004699
Douglas Gregordf846d12011-03-02 18:46:51 +00004700 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00004701 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004702 TemplateLoc,
4703 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004704 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00004705 Converted,
4706 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004707 if (Name.isNull())
4708 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004709
Douglas Gregor9d802122011-03-02 17:09:35 +00004710 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
4711 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00004712 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004713
Douglas Gregor84d49a22009-11-11 21:54:23 +00004714 // Introduce an instantiation record that describes where we are using
Richard Smith54f18e82016-08-31 02:15:21 +00004715 // the default template argument. We're not actually instantiating a
4716 // template here, we just create this object to put a note into the
4717 // context stack.
Alp Tokerd4a72d52013-10-08 08:09:04 +00004718 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
4719 SourceRange(TemplateLoc, RAngleLoc));
4720 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004721 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004722
Douglas Gregor84d49a22009-11-11 21:54:23 +00004723 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00004724 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004725 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004726 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004727
Richard Trieu15b66532015-01-24 02:48:32 +00004728 // Core issue 150 (assumed resolution): if this is a template template
4729 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00004730 // template definition.
4731 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00004732 NewArgs.addArgument(Arg);
4733
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004734 // Move to the next template parameter and argument.
4735 ++Param;
4736 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00004737 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004738
Richard Smith07f79912014-06-06 16:00:50 +00004739 // If we're performing a partial argument substitution, allow any trailing
4740 // pack expansions; they might be empty. This can happen even if
4741 // PartialTemplateArgs is false (the list of arguments is complete but
4742 // still dependent).
4743 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
4744 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00004745 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
4746 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00004747 }
4748
Douglas Gregor8e072612012-02-03 07:34:46 +00004749 // If we have any leftover arguments, then there were too many arguments.
4750 // Complain and fail.
4751 if (ArgIdx < NumArgs)
Richard Trieu15b66532015-01-24 02:48:32 +00004752 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
4753
4754 // No problems found with the new argument list, propagate changes back
4755 // to caller.
Richard Smith11255ec2017-01-18 19:19:22 +00004756 if (UpdateArgsWithConversions)
4757 TemplateArgs = std::move(NewArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004758
Richard Smith1fde8ec2012-09-07 02:06:42 +00004759 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00004760}
4761
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004762namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004763 class UnnamedLocalNoLinkageFinder
4764 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004765 {
4766 Sema &S;
4767 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004768
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004769 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004770
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004771 public:
4772 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
4773
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004774 bool Visit(QualType T) {
Daniel Jasper5cad6852017-01-02 22:55:45 +00004775 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004776 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004777
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004778#define TYPE(Class, Parent) \
4779 bool Visit##Class##Type(const Class##Type *);
4780#define ABSTRACT_TYPE(Class, Parent) \
4781 bool Visit##Class##Type(const Class##Type *) { return false; }
4782#define NON_CANONICAL_TYPE(Class, Parent) \
4783 bool Visit##Class##Type(const Class##Type *) { return false; }
4784#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004785
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004786 bool VisitTagDecl(const TagDecl *Tag);
4787 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
4788 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004789} // end anonymous namespace
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004790
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004791bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004792 return false;
4793}
4794
4795bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
4796 return Visit(T->getElementType());
4797}
4798
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004799bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004800 return Visit(T->getPointeeType());
4801}
4802
4803bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004804 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004805 return Visit(T->getPointeeType());
4806}
4807
4808bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004809 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004810 return Visit(T->getPointeeType());
4811}
4812
4813bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004814 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004815 return Visit(T->getPointeeType());
4816}
4817
4818bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004819 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004820 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
4821}
4822
4823bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004824 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004825 return Visit(T->getElementType());
4826}
4827
4828bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004829 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004830 return Visit(T->getElementType());
4831}
4832
4833bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004834 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004835 return Visit(T->getElementType());
4836}
4837
4838bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004839 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004840 return Visit(T->getElementType());
4841}
4842
4843bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004844 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004845 return Visit(T->getElementType());
4846}
4847
4848bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
4849 return Visit(T->getElementType());
4850}
4851
4852bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
4853 return Visit(T->getElementType());
4854}
4855
4856bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
4857 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004858 for (const auto &A : T->param_types()) {
4859 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004860 return true;
4861 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004862
Alp Toker314cc812014-01-25 16:55:45 +00004863 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004864}
4865
4866bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
4867 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00004868 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004869}
4870
4871bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
4872 const UnresolvedUsingType*) {
4873 return false;
4874}
4875
4876bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
4877 return false;
4878}
4879
4880bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4881 return Visit(T->getUnderlyingType());
4882}
4883
4884bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4885 return false;
4886}
4887
Alexis Hunte852b102011-05-24 22:41:36 +00004888bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4889 const UnaryTransformType*) {
4890 return false;
4891}
4892
Richard Smith30482bc2011-02-20 03:19:35 +00004893bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4894 return Visit(T->getDeducedType());
4895}
4896
Richard Smith600b5262017-01-26 20:40:47 +00004897bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
4898 const DeducedTemplateSpecializationType *T) {
4899 return Visit(T->getDeducedType());
4900}
4901
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004902bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4903 return VisitTagDecl(T->getDecl());
4904}
4905
4906bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4907 return VisitTagDecl(T->getDecl());
4908}
4909
4910bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4911 const TemplateTypeParmType*) {
4912 return false;
4913}
4914
Douglas Gregorada4b792011-01-14 02:55:32 +00004915bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4916 const SubstTemplateTypeParmPackType *) {
4917 return false;
4918}
4919
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004920bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4921 const TemplateSpecializationType*) {
4922 return false;
4923}
4924
4925bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4926 const InjectedClassNameType* T) {
4927 return VisitTagDecl(T->getDecl());
4928}
4929
4930bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4931 const DependentNameType* T) {
4932 return VisitNestedNameSpecifier(T->getQualifier());
4933}
4934
4935bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4936 const DependentTemplateSpecializationType* T) {
4937 return VisitNestedNameSpecifier(T->getQualifier());
4938}
4939
Douglas Gregord2fa7662010-12-20 02:24:11 +00004940bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4941 const PackExpansionType* T) {
4942 return Visit(T->getPattern());
4943}
4944
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004945bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4946 return false;
4947}
4948
4949bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4950 const ObjCInterfaceType *) {
4951 return false;
4952}
4953
4954bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4955 const ObjCObjectPointerType *) {
4956 return false;
4957}
4958
Eli Friedman0dfb8892011-10-06 23:00:33 +00004959bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4960 return Visit(T->getValueType());
4961}
4962
Xiuli Pan9c14e282016-01-09 12:53:17 +00004963bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
4964 return false;
4965}
4966
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004967bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4968 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004969 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004970 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004971 diag::warn_cxx98_compat_template_arg_local_type :
4972 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004973 << S.Context.getTypeDeclType(Tag) << SR;
4974 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004975 }
4976
John McCall5ea95772013-03-09 00:54:27 +00004977 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004978 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004979 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004980 diag::warn_cxx98_compat_template_arg_unnamed_type :
4981 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004982 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4983 return true;
4984 }
4985
4986 return false;
4987}
4988
4989bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4990 NestedNameSpecifier *NNS) {
4991 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4992 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004993
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004994 switch (NNS->getKind()) {
4995 case NestedNameSpecifier::Identifier:
4996 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004997 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004998 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004999 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005000 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005001
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005002 case NestedNameSpecifier::TypeSpec:
5003 case NestedNameSpecifier::TypeSpecWithTemplate:
5004 return Visit(QualType(NNS->getAsType(), 0));
5005 }
David Blaikie8a40f702012-01-17 06:56:22 +00005006 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005007}
5008
Douglas Gregord32e0282009-02-09 23:23:08 +00005009/// \brief Check a template argument against its corresponding
5010/// template type parameter.
5011///
5012/// This routine implements the semantics of C++ [temp.arg.type]. It
5013/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005014bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00005015 TypeSourceInfo *ArgInfo) {
5016 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00005017 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00005018 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00005019
5020 if (Arg->isVariablyModifiedType()) {
5021 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005022 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005023 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00005024 }
5025
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005026 // C++03 [temp.arg.type]p2:
5027 // A local type, a type with no linkage, an unnamed type or a type
5028 // compounded from any of these types shall not be used as a
5029 // template-argument for a template type-parameter.
5030 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00005031 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005032 // a warning.
Daniel Jasper5cad6852017-01-02 22:55:45 +00005033 if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005034 UnnamedLocalNoLinkageFinder Finder(*this, SR);
5035 (void)Finder.Visit(Context.getCanonicalType(Arg));
5036 }
5037
Douglas Gregord32e0282009-02-09 23:23:08 +00005038 return false;
5039}
5040
Douglas Gregor20fdef32012-04-10 17:08:25 +00005041enum NullPointerValueKind {
5042 NPV_NotNullPointer,
5043 NPV_NullPointer,
5044 NPV_Error
5045};
5046
5047/// \brief Determine whether the given template argument is a null pointer
5048/// value of the appropriate type.
5049static NullPointerValueKind
5050isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
5051 QualType ParamType, Expr *Arg) {
5052 if (Arg->isValueDependent() || Arg->isTypeDependent())
5053 return NPV_NotNullPointer;
David Majnemer69c3ddc2015-09-11 20:18:09 +00005054
Richard Smithdb0ac552015-12-18 22:40:25 +00005055 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
David Majnemerb54368c2015-09-11 20:55:29 +00005056 llvm_unreachable(
5057 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
David Majnemer69c3ddc2015-09-11 20:18:09 +00005058
David Majnemer5c734ad2014-08-14 00:49:23 +00005059 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00005060 return NPV_NotNullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005061
Douglas Gregor20fdef32012-04-10 17:08:25 +00005062 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00005063 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
5064 if (ArgRV.isInvalid())
5065 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005066 Arg = ArgRV.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005067
Douglas Gregor20fdef32012-04-10 17:08:25 +00005068 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005069 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00005070 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005071 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00005072 EvalResult.HasSideEffects) {
5073 SourceLocation DiagLoc = Arg->getExprLoc();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005074
Douglas Gregor350880c2012-04-10 19:03:30 +00005075 // If our only note is the usual "invalid subexpression" note, just point
5076 // the caret at its location rather than producing an essentially
5077 // redundant note.
5078 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5079 diag::note_invalid_subexpr_in_const_expr) {
5080 DiagLoc = Notes[0].first;
5081 Notes.clear();
5082 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005083
Douglas Gregor350880c2012-04-10 19:03:30 +00005084 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5085 << Arg->getType() << Arg->getSourceRange();
5086 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5087 S.Diag(Notes[I].first, Notes[I].second);
Simon Pilgrim6905d222016-12-30 22:55:33 +00005088
Douglas Gregor350880c2012-04-10 19:03:30 +00005089 S.Diag(Param->getLocation(), diag::note_template_param_here);
5090 return NPV_Error;
5091 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005092
Douglas Gregor20fdef32012-04-10 17:08:25 +00005093 // C++11 [temp.arg.nontype]p1:
5094 // - an address constant expression of type std::nullptr_t
5095 if (Arg->getType()->isNullPtrType())
5096 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005097
Douglas Gregor20fdef32012-04-10 17:08:25 +00005098 // - a constant expression that evaluates to a null pointer value (4.10); or
5099 // - a constant expression that evaluates to a null member pointer value
5100 // (4.11); or
5101 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
5102 (EvalResult.Val.isMemberPointer() &&
5103 !EvalResult.Val.getMemberPointerDecl())) {
5104 // If our expression has an appropriate type, we've succeeded.
5105 bool ObjCLifetimeConversion;
5106 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5107 S.IsQualificationConversion(Arg->getType(), ParamType, false,
5108 ObjCLifetimeConversion))
5109 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005110
Douglas Gregor20fdef32012-04-10 17:08:25 +00005111 // The types didn't match, but we know we got a null pointer; complain,
5112 // then recover as if the types were correct.
5113 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
5114 << Arg->getType() << ParamType << Arg->getSourceRange();
5115 S.Diag(Param->getLocation(), diag::note_template_param_here);
5116 return NPV_NullPointer;
5117 }
5118
5119 // If we don't have a null pointer value, but we do have a NULL pointer
5120 // constant, suggest a cast to the appropriate type.
5121 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
5122 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
5123 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Alp Tokerb6cc5922014-05-03 03:45:55 +00005124 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
5125 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
5126 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00005127 S.Diag(Param->getLocation(), diag::note_template_param_here);
5128 return NPV_NullPointer;
5129 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005130
Douglas Gregor20fdef32012-04-10 17:08:25 +00005131 // FIXME: If we ever want to support general, address-constant expressions
5132 // as non-type template arguments, we should return the ExprResult here to
5133 // be interpreted by the caller.
5134 return NPV_NotNullPointer;
5135}
5136
David Majnemer61c39a12013-08-23 05:39:39 +00005137/// \brief Checks whether the given template argument is compatible with its
5138/// template parameter.
5139static bool CheckTemplateArgumentIsCompatibleWithParameter(
5140 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
5141 Expr *Arg, QualType ArgType) {
5142 bool ObjCLifetimeConversion;
5143 if (ParamType->isPointerType() &&
5144 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
5145 S.IsQualificationConversion(ArgType, ParamType, false,
5146 ObjCLifetimeConversion)) {
5147 // For pointer-to-object types, qualification conversions are
5148 // permitted.
5149 } else {
5150 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
5151 if (!ParamRef->getPointeeType()->isFunctionType()) {
5152 // C++ [temp.arg.nontype]p5b3:
5153 // For a non-type template-parameter of type reference to
5154 // object, no conversions apply. The type referred to by the
5155 // reference may be more cv-qualified than the (otherwise
5156 // identical) type of the template- argument. The
5157 // template-parameter is bound directly to the
5158 // template-argument, which shall be an lvalue.
5159
5160 // FIXME: Other qualifiers?
5161 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
5162 unsigned ArgQuals = ArgType.getCVRQualifiers();
5163
5164 if ((ParamQuals | ArgQuals) != ParamQuals) {
5165 S.Diag(Arg->getLocStart(),
5166 diag::err_template_arg_ref_bind_ignores_quals)
5167 << ParamType << Arg->getType() << Arg->getSourceRange();
5168 S.Diag(Param->getLocation(), diag::note_template_param_here);
5169 return true;
5170 }
5171 }
5172 }
5173
5174 // At this point, the template argument refers to an object or
5175 // function with external linkage. We now need to check whether the
5176 // argument and parameter types are compatible.
5177 if (!S.Context.hasSameUnqualifiedType(ArgType,
5178 ParamType.getNonReferenceType())) {
5179 // We can't perform this conversion or binding.
5180 if (ParamType->isReferenceType())
5181 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
5182 << ParamType << ArgIn->getType() << Arg->getSourceRange();
5183 else
5184 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
5185 << ArgIn->getType() << ParamType << Arg->getSourceRange();
5186 S.Diag(Param->getLocation(), diag::note_template_param_here);
5187 return true;
5188 }
5189 }
5190
5191 return false;
5192}
5193
Douglas Gregorccb07762009-02-11 19:52:55 +00005194/// \brief Checks whether the given template argument is the address
5195/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005196static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00005197CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
5198 NonTypeTemplateParmDecl *Param,
5199 QualType ParamType,
5200 Expr *ArgIn,
5201 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005202 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005203 Expr *Arg = ArgIn;
5204 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00005205
Douglas Gregorb242683d2010-04-01 18:32:35 +00005206 bool AddressTaken = false;
5207 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00005208 if (S.getLangOpts().MicrosoftExt) {
5209 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
5210 // dereference and address-of operators.
5211 Arg = Arg->IgnoreParenCasts();
5212
5213 bool ExtWarnMSTemplateArg = false;
5214 UnaryOperatorKind FirstOpKind;
5215 SourceLocation FirstOpLoc;
5216 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5217 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
5218 if (UnOpKind == UO_Deref)
5219 ExtWarnMSTemplateArg = true;
5220 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
5221 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
5222 if (!AddrOpLoc.isValid()) {
5223 FirstOpKind = UnOpKind;
5224 FirstOpLoc = UnOp->getOperatorLoc();
5225 }
5226 } else
5227 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005228 }
David Majnemer61c39a12013-08-23 05:39:39 +00005229 if (FirstOpLoc.isValid()) {
5230 if (ExtWarnMSTemplateArg)
5231 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
5232 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00005233
David Majnemer61c39a12013-08-23 05:39:39 +00005234 if (FirstOpKind == UO_AddrOf)
5235 AddressTaken = true;
5236 else if (Arg->getType()->isPointerType()) {
5237 // We cannot let pointers get dereferenced here, that is obviously not a
5238 // constant expression.
5239 assert(FirstOpKind == UO_Deref);
5240 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5241 << Arg->getSourceRange();
5242 }
5243 }
5244 } else {
5245 // See through any implicit casts we added to fix the type.
5246 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00005247
David Majnemer61c39a12013-08-23 05:39:39 +00005248 // C++ [temp.arg.nontype]p1:
5249 //
5250 // A template-argument for a non-type, non-template
5251 // template-parameter shall be one of: [...]
5252 //
5253 // -- the address of an object or function with external
5254 // linkage, including function templates and function
5255 // template-ids but excluding non-static class members,
5256 // expressed as & id-expression where the & is optional if
5257 // the name refers to a function or array, or if the
5258 // corresponding template-parameter is a reference; or
5259
5260 // In C++98/03 mode, give an extension warning on any extra parentheses.
5261 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5262 bool ExtraParens = false;
5263 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5264 if (!Invalid && !ExtraParens) {
5265 S.Diag(Arg->getLocStart(),
5266 S.getLangOpts().CPlusPlus11
5267 ? diag::warn_cxx98_compat_template_arg_extra_parens
5268 : diag::ext_template_arg_extra_parens)
5269 << Arg->getSourceRange();
5270 ExtraParens = true;
5271 }
5272
5273 Arg = Parens->getSubExpr();
5274 }
5275
5276 while (SubstNonTypeTemplateParmExpr *subst =
5277 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5278 Arg = subst->getReplacement()->IgnoreImpCasts();
5279
5280 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5281 if (UnOp->getOpcode() == UO_AddrOf) {
5282 Arg = UnOp->getSubExpr();
5283 AddressTaken = true;
5284 AddrOpLoc = UnOp->getOperatorLoc();
5285 }
5286 }
5287
5288 while (SubstNonTypeTemplateParmExpr *subst =
5289 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5290 Arg = subst->getReplacement()->IgnoreImpCasts();
5291 }
John McCall7c454bb2011-07-15 05:09:51 +00005292
David Majnemer07910d62014-06-26 07:48:46 +00005293 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
5294 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5295
5296 // If our parameter has pointer type, check for a null template value.
5297 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
5298 NullPointerValueKind NPV;
5299 // dllimport'd entities aren't constant but are available inside of template
5300 // arguments.
5301 if (Entity && Entity->hasAttr<DLLImportAttr>())
5302 NPV = NPV_NotNullPointer;
5303 else
5304 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
5305 switch (NPV) {
5306 case NPV_NullPointer:
5307 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005308 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5309 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00005310 return false;
5311
5312 case NPV_Error:
5313 return true;
5314
5315 case NPV_NotNullPointer:
5316 break;
5317 }
5318 }
5319
Chandler Carruth724a8a12010-01-31 10:01:20 +00005320 // Stop checking the precise nature of the argument if it is value dependent,
5321 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00005322 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005323 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00005324 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005325 }
David Majnemer61c39a12013-08-23 05:39:39 +00005326
5327 if (isa<CXXUuidofExpr>(Arg)) {
5328 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
5329 ArgIn, Arg, ArgType))
5330 return true;
5331
5332 Converted = TemplateArgument(ArgIn);
5333 return false;
5334 }
5335
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005336 if (!DRE) {
5337 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5338 << Arg->getSourceRange();
5339 S.Diag(Param->getLocation(), diag::note_template_param_here);
5340 return true;
5341 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00005342
Douglas Gregorccb07762009-02-11 19:52:55 +00005343 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00005344 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005345 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
David Majnemer6bedcfa2013-10-26 06:12:44 +00005346 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005347 S.Diag(Param->getLocation(), diag::note_template_param_here);
5348 return true;
5349 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005350
5351 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00005352 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005353 if (!Method->isStatic()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005354 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00005355 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005356 S.Diag(Param->getLocation(), diag::note_template_param_here);
5357 return true;
5358 }
Richard Smith9380e0e2012-04-04 21:11:30 +00005359 }
Mike Stump11289f42009-09-09 15:08:12 +00005360
Richard Smith9380e0e2012-04-04 21:11:30 +00005361 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
5362 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00005363
Richard Smith9380e0e2012-04-04 21:11:30 +00005364 // A non-type template argument must refer to an object or function.
5365 if (!Func && !Var) {
5366 // We found something, but we don't know specifically what it is.
5367 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
5368 << Arg->getSourceRange();
5369 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
5370 return true;
5371 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005372
Richard Smith9380e0e2012-04-04 21:11:30 +00005373 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00005374 if (Entity->getFormalLinkage() == InternalLinkage) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005375 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
Richard Smith9380e0e2012-04-04 21:11:30 +00005376 diag::warn_cxx98_compat_template_arg_object_internal :
5377 diag::ext_template_arg_object_internal)
5378 << !Func << Entity << Arg->getSourceRange();
5379 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5380 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00005381 } else if (!Entity->hasLinkage()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00005382 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
5383 << !Func << Entity << Arg->getSourceRange();
5384 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5385 << !Func;
5386 return true;
5387 }
5388
5389 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005390 // If the template parameter has pointer type, the function decays.
5391 if (ParamType->isPointerType() && !AddressTaken)
5392 ArgType = S.Context.getPointerType(Func->getType());
5393 else if (AddressTaken && ParamType->isReferenceType()) {
5394 // If we originally had an address-of operator, but the
5395 // parameter has reference type, complain and (if things look
5396 // like they will work) drop the address-of operator.
5397 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
5398 ParamType.getNonReferenceType())) {
5399 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5400 << ParamType;
5401 S.Diag(Param->getLocation(), diag::note_template_param_here);
5402 return true;
5403 }
5404
5405 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5406 << ParamType
5407 << FixItHint::CreateRemoval(AddrOpLoc);
5408 S.Diag(Param->getLocation(), diag::note_template_param_here);
5409
5410 ArgType = Func->getType();
5411 }
Richard Smith9380e0e2012-04-04 21:11:30 +00005412 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005413 // A value of reference type is not an object.
5414 if (Var->getType()->isReferenceType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005415 S.Diag(Arg->getLocStart(),
Douglas Gregorb242683d2010-04-01 18:32:35 +00005416 diag::err_template_arg_reference_var)
5417 << Var->getType() << Arg->getSourceRange();
5418 S.Diag(Param->getLocation(), diag::note_template_param_here);
5419 return true;
5420 }
5421
Richard Smith9380e0e2012-04-04 21:11:30 +00005422 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00005423 if (Var->getTLSKind()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00005424 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
5425 << Arg->getSourceRange();
5426 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
5427 return true;
5428 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00005429
5430 // If the template parameter has pointer type, we must have taken
5431 // the address of this object.
5432 if (ParamType->isReferenceType()) {
5433 if (AddressTaken) {
5434 // If we originally had an address-of operator, but the
5435 // parameter has reference type, complain and (if things look
5436 // like they will work) drop the address-of operator.
5437 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
5438 ParamType.getNonReferenceType())) {
5439 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5440 << ParamType;
5441 S.Diag(Param->getLocation(), diag::note_template_param_here);
5442 return true;
5443 }
5444
5445 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5446 << ParamType
5447 << FixItHint::CreateRemoval(AddrOpLoc);
5448 S.Diag(Param->getLocation(), diag::note_template_param_here);
5449
5450 ArgType = Var->getType();
5451 }
5452 } else if (!AddressTaken && ParamType->isPointerType()) {
5453 if (Var->getType()->isArrayType()) {
5454 // Array-to-pointer decay.
5455 ArgType = S.Context.getArrayDecayedType(Var->getType());
5456 } else {
5457 // If the template parameter has pointer type but the address of
5458 // this object was not taken, complain and (possibly) recover by
5459 // taking the address of the entity.
5460 ArgType = S.Context.getPointerType(Var->getType());
5461 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
5462 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5463 << ParamType;
5464 S.Diag(Param->getLocation(), diag::note_template_param_here);
5465 return true;
5466 }
5467
5468 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5469 << ParamType
5470 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
5471
5472 S.Diag(Param->getLocation(), diag::note_template_param_here);
5473 }
5474 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005475 }
Mike Stump11289f42009-09-09 15:08:12 +00005476
David Majnemer61c39a12013-08-23 05:39:39 +00005477 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
5478 Arg, ArgType))
5479 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005480
5481 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00005482 Converted =
5483 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Nick Lewycky45b50522013-02-02 00:25:55 +00005484 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00005485 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00005486}
5487
5488/// \brief Checks whether the given template argument is a pointer to
5489/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00005490static bool CheckTemplateArgumentPointerToMember(Sema &S,
5491 NonTypeTemplateParmDecl *Param,
5492 QualType ParamType,
5493 Expr *&ResultArg,
5494 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005495 bool Invalid = false;
5496
Douglas Gregor20fdef32012-04-10 17:08:25 +00005497 // Check for a null pointer value.
5498 Expr *Arg = ResultArg;
5499 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
5500 case NPV_Error:
5501 return true;
5502 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00005503 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005504 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5505 /*isNullPtr*/true);
Douglas Gregor20fdef32012-04-10 17:08:25 +00005506 return false;
5507 case NPV_NotNullPointer:
5508 break;
5509 }
5510
5511 bool ObjCLifetimeConversion;
5512 if (S.IsQualificationConversion(Arg->getType(),
5513 ParamType.getNonReferenceType(),
5514 false, ObjCLifetimeConversion)) {
5515 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005516 Arg->getValueKind()).get();
Douglas Gregor20fdef32012-04-10 17:08:25 +00005517 ResultArg = Arg;
5518 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
5519 ParamType.getNonReferenceType())) {
5520 // We can't perform this conversion.
5521 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
5522 << Arg->getType() << ParamType << Arg->getSourceRange();
5523 S.Diag(Param->getLocation(), diag::note_template_param_here);
5524 return true;
5525 }
5526
Douglas Gregorccb07762009-02-11 19:52:55 +00005527 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00005528 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00005529 Arg = Cast->getSubExpr();
5530
5531 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00005532 //
Douglas Gregorccb07762009-02-11 19:52:55 +00005533 // A template-argument for a non-type, non-template
5534 // template-parameter shall be one of: [...]
5535 //
5536 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00005537 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00005538
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00005539 // In C++98/03 mode, give an extension warning on any extra parentheses.
5540 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5541 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00005542 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005543 if (!Invalid && !ExtraParens) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00005544 S.Diag(Arg->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005545 S.getLangOpts().CPlusPlus11 ?
Douglas Gregor20fdef32012-04-10 17:08:25 +00005546 diag::warn_cxx98_compat_template_arg_extra_parens :
5547 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00005548 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00005549 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00005550 }
5551
5552 Arg = Parens->getSubExpr();
5553 }
5554
John McCall7c454bb2011-07-15 05:09:51 +00005555 while (SubstNonTypeTemplateParmExpr *subst =
5556 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5557 Arg = subst->getReplacement()->IgnoreImpCasts();
5558
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005559 // A pointer-to-member constant written &Class::member.
5560 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00005561 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005562 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
5563 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00005564 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005565 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005566 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005567 // A constant of pointer-to-member type.
5568 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
5569 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
5570 if (VD->getType()->isMemberPointerType()) {
David Majnemercd053cd2013-12-10 00:40:58 +00005571 if (isa<NonTypeTemplateParmDecl>(VD)) {
Eli Friedmanb826a002012-09-26 02:36:12 +00005572 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005573 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00005574 } else {
5575 VD = cast<ValueDecl>(VD->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00005576 Converted = TemplateArgument(VD, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00005577 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005578 return Invalid;
5579 }
5580 }
5581 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005582
Craig Topperc3ec1492014-05-26 06:22:03 +00005583 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005584 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005585
Douglas Gregorccb07762009-02-11 19:52:55 +00005586 if (!DRE)
Douglas Gregor20fdef32012-04-10 17:08:25 +00005587 return S.Diag(Arg->getLocStart(),
5588 diag::err_template_arg_not_pointer_to_member_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00005589 << Arg->getSourceRange();
5590
David Majnemer3ac84e62013-10-22 21:56:38 +00005591 if (isa<FieldDecl>(DRE->getDecl()) ||
5592 isa<IndirectFieldDecl>(DRE->getDecl()) ||
5593 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005594 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00005595 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00005596 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
5597 "Only non-static member pointers can make it here");
5598
5599 // Okay: this is the address of a non-static member, and therefore
5600 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00005601 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005602 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00005603 } else {
5604 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00005605 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00005606 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005607 return Invalid;
5608 }
5609
5610 // We found something else, but we don't know specifically what it is.
Douglas Gregor20fdef32012-04-10 17:08:25 +00005611 S.Diag(Arg->getLocStart(),
5612 diag::err_template_arg_not_pointer_to_member_form)
5613 << Arg->getSourceRange();
5614 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00005615 return true;
5616}
5617
Douglas Gregord32e0282009-02-09 23:23:08 +00005618/// \brief Check a template argument against its corresponding
5619/// non-type template parameter.
5620///
Douglas Gregor463421d2009-03-03 04:44:36 +00005621/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00005622/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00005623/// returns the converted template argument. \p ParamType is the
5624/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00005625ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00005626 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00005627 TemplateArgument &Converted,
5628 CheckTemplateArgumentKind CTAK) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005629 SourceLocation StartLoc = Arg->getLocStart();
Douglas Gregorc40290e2009-03-09 23:48:35 +00005630
Richard Smith5f274382016-09-28 23:55:27 +00005631 // If the parameter type somehow involves auto, deduce the type now.
5632 if (getLangOpts().CPlusPlus1z && ParamType->isUndeducedType()) {
Richard Smith87d263e2016-12-25 08:05:23 +00005633 // When checking a deduced template argument, deduce from its type even if
5634 // the type is dependent, in order to check the types of non-type template
5635 // arguments line up properly in partial ordering.
5636 Optional<unsigned> Depth;
5637 if (CTAK != CTAK_Specified)
5638 Depth = Param->getDepth() + 1;
Richard Smith5f274382016-09-28 23:55:27 +00005639 if (DeduceAutoType(
5640 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
Richard Smith87d263e2016-12-25 08:05:23 +00005641 Arg, ParamType, Depth) == DAR_Failed) {
Richard Smith5f274382016-09-28 23:55:27 +00005642 Diag(Arg->getExprLoc(),
5643 diag::err_non_type_template_parm_type_deduction_failure)
5644 << Param->getDeclName() << Param->getType() << Arg->getType()
5645 << Arg->getSourceRange();
5646 Diag(Param->getLocation(), diag::note_template_param_here);
5647 return ExprError();
5648 }
5649 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
5650 // an error. The error message normally references the parameter
5651 // declaration, but here we'll pass the argument location because that's
5652 // where the parameter type is deduced.
5653 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
5654 if (ParamType.isNull()) {
5655 Diag(Param->getLocation(), diag::note_template_param_here);
5656 return ExprError();
5657 }
5658 }
5659
Richard Smithd663fdd2014-12-17 20:42:37 +00005660 // We should have already dropped all cv-qualifiers by now.
5661 assert(!ParamType.hasQualifiers() &&
5662 "non-type template parameter type cannot be qualified");
5663
5664 if (CTAK == CTAK_Deduced &&
Richard Smithd92eddf2016-12-27 06:14:37 +00005665 !Context.hasSameType(ParamType.getNonLValueExprType(Context),
Richard Smith0e617ec2016-12-27 07:56:27 +00005666 Arg->getType())) {
Richard Smith957fbf12017-01-17 02:14:37 +00005667 // FIXME: If either type is dependent, we skip the check. This isn't
5668 // correct, since during deduction we're supposed to have replaced each
5669 // template parameter with some unique (non-dependent) placeholder.
5670 // FIXME: If the argument type contains 'auto', we carry on and fail the
5671 // type check in order to force specific types to be more specialized than
5672 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
5673 // work.
5674 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
5675 !Arg->getType()->getContainedAutoType()) {
5676 Converted = TemplateArgument(Arg);
5677 return Arg;
5678 }
5679 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
5680 // we should actually be checking the type of the template argument in P,
5681 // not the type of the template argument deduced from A, against the
5682 // template parameter type.
Richard Smithd663fdd2014-12-17 20:42:37 +00005683 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
Richard Smith0e617ec2016-12-27 07:56:27 +00005684 << Arg->getType()
Richard Smithd663fdd2014-12-17 20:42:37 +00005685 << ParamType.getUnqualifiedType();
5686 Diag(Param->getLocation(), diag::note_template_param_here);
5687 return ExprError();
5688 }
5689
Richard Smith87d263e2016-12-25 08:05:23 +00005690 // If either the parameter has a dependent type or the argument is
5691 // type-dependent, there's nothing we can check now.
5692 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
5693 // FIXME: Produce a cloned, canonical expression?
5694 Converted = TemplateArgument(Arg);
5695 return Arg;
5696 }
5697
Richard Smithe5945872017-01-06 22:52:53 +00005698 // The initialization of the parameter from the argument is
5699 // a constant-evaluated context.
5700 EnterExpressionEvaluationContext ConstantEvaluated(*this,
5701 Sema::ConstantEvaluated);
5702
Richard Smith410cc892014-11-26 03:26:53 +00005703 if (getLangOpts().CPlusPlus1z) {
Richard Smith410cc892014-11-26 03:26:53 +00005704 // C++1z [temp.arg.nontype]p1:
5705 // A template-argument for a non-type template parameter shall be
5706 // a converted constant expression of the type of the template-parameter.
5707 APValue Value;
5708 ExprResult ArgResult = CheckConvertedConstantExpression(
5709 Arg, ParamType, Value, CCEK_TemplateArg);
5710 if (ArgResult.isInvalid())
5711 return ExprError();
5712
Richard Smith52e624f2016-12-21 21:42:57 +00005713 // For a value-dependent argument, CheckConvertedConstantExpression is
5714 // permitted (and expected) to be unable to determine a value.
5715 if (ArgResult.get()->isValueDependent()) {
Richard Smith01bfa682016-12-27 02:02:09 +00005716 Converted = TemplateArgument(ArgResult.get());
5717 return ArgResult;
Richard Smith52e624f2016-12-21 21:42:57 +00005718 }
5719
Richard Smithd663fdd2014-12-17 20:42:37 +00005720 QualType CanonParamType = Context.getCanonicalType(ParamType);
5721
Richard Smith410cc892014-11-26 03:26:53 +00005722 // Convert the APValue to a TemplateArgument.
5723 switch (Value.getKind()) {
5724 case APValue::Uninitialized:
5725 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00005726 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005727 break;
5728 case APValue::Int:
5729 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00005730 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00005731 break;
5732 case APValue::MemberPointer: {
5733 assert(ParamType->isMemberPointerType());
5734
5735 // FIXME: We need TemplateArgument representation and mangling for these.
5736 if (!Value.getMemberPointerPath().empty()) {
5737 Diag(Arg->getLocStart(),
5738 diag::err_template_arg_member_ptr_base_derived_not_supported)
5739 << Value.getMemberPointerDecl() << ParamType
5740 << Arg->getSourceRange();
5741 return ExprError();
5742 }
5743
5744 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00005745 Converted = VD ? TemplateArgument(VD, CanonParamType)
5746 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005747 break;
5748 }
5749 case APValue::LValue: {
5750 // For a non-type template-parameter of pointer or reference type,
5751 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00005752 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
5753 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00005754 // -- a temporary object
5755 // -- a string literal
5756 // -- the result of a typeid expression, or
5757 // -- a predefind __func__ variable
5758 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
5759 if (isa<CXXUuidofExpr>(E)) {
5760 Converted = TemplateArgument(const_cast<Expr*>(E));
5761 break;
5762 }
5763 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5764 << Arg->getSourceRange();
5765 return ExprError();
5766 }
5767 auto *VD = const_cast<ValueDecl *>(
5768 Value.getLValueBase().dyn_cast<const ValueDecl *>());
5769 // -- a subobject
5770 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
5771 VD && VD->getType()->isArrayType() &&
5772 Value.getLValuePath()[0].ArrayIndex == 0 &&
5773 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
5774 // Per defect report (no number yet):
5775 // ... other than a pointer to the first element of a complete array
5776 // object.
5777 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
5778 Value.isLValueOnePastTheEnd()) {
5779 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
5780 << Value.getAsString(Context, ParamType);
5781 return ExprError();
5782 }
Richard Smithd663fdd2014-12-17 20:42:37 +00005783 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00005784 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00005785 assert((!VD || !ParamType->isNullPtrType()) &&
5786 "non-null value of type nullptr_t?");
5787 Converted = VD ? TemplateArgument(VD, CanonParamType)
5788 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005789 break;
5790 }
5791 case APValue::AddrLabelDiff:
5792 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
5793 case APValue::Float:
5794 case APValue::ComplexInt:
5795 case APValue::ComplexFloat:
5796 case APValue::Vector:
5797 case APValue::Array:
5798 case APValue::Struct:
5799 case APValue::Union:
5800 llvm_unreachable("invalid kind for template argument");
5801 }
5802
5803 return ArgResult.get();
5804 }
5805
Douglas Gregor86560402009-02-10 23:36:10 +00005806 // C++ [temp.arg.nontype]p5:
5807 // The following conversions are performed on each expression used
5808 // as a non-type template-argument. If a non-type
5809 // template-argument cannot be converted to the type of the
5810 // corresponding template-parameter then the program is
5811 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00005812 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00005813 // C++11:
5814 // -- for a non-type template-parameter of integral or
5815 // enumeration type, conversions permitted in a converted
5816 // constant expression are applied.
5817 //
5818 // C++98:
5819 // -- for a non-type template-parameter of integral or
5820 // enumeration type, integral promotions (4.5) and integral
5821 // conversions (4.7) are applied.
5822
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005823 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00005824 // C++ [temp.arg.nontype]p1:
5825 // A template-argument for a non-type, non-template template-parameter
5826 // shall be one of:
5827 //
5828 // -- for a non-type template-parameter of integral or enumeration
5829 // type, a converted constant expression of the type of the
5830 // template-parameter; or
5831 llvm::APSInt Value;
5832 ExprResult ArgResult =
5833 CheckConvertedConstantExpression(Arg, ParamType, Value,
5834 CCEK_TemplateArg);
5835 if (ArgResult.isInvalid())
5836 return ExprError();
5837
Richard Smith01bfa682016-12-27 02:02:09 +00005838 // We can't check arbitrary value-dependent arguments.
5839 if (ArgResult.get()->isValueDependent()) {
5840 Converted = TemplateArgument(ArgResult.get());
5841 return ArgResult;
5842 }
5843
Richard Smithf8379a02012-01-18 23:55:52 +00005844 // Widen the argument value to sizeof(parameter type). This is almost
5845 // always a no-op, except when the parameter type is bool. In
5846 // that case, this may extend the argument from 1 bit to 8 bits.
5847 QualType IntegerType = ParamType;
5848 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5849 IntegerType = Enum->getDecl()->getIntegerType();
5850 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
5851
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005852 Converted = TemplateArgument(Context, Value,
5853 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00005854 return ArgResult;
5855 }
5856
Richard Smith08b12f12011-10-27 22:11:44 +00005857 ExprResult ArgResult = DefaultLvalueConversion(Arg);
5858 if (ArgResult.isInvalid())
5859 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005860 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00005861
5862 QualType ArgType = Arg->getType();
5863
Douglas Gregor86560402009-02-10 23:36:10 +00005864 // C++ [temp.arg.nontype]p1:
5865 // A template-argument for a non-type, non-template
5866 // template-parameter shall be one of:
5867 //
5868 // -- an integral constant-expression of integral or enumeration
5869 // type; or
5870 // -- the name of a non-type template-parameter; or
5871 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005872 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00005873 if (!ArgType->isIntegralOrEnumerationType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005874 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005875 diag::err_template_arg_not_integral_or_enumeral)
5876 << ArgType << Arg->getSourceRange();
5877 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005878 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00005879 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005880 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
5881 QualType T;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005882
Douglas Gregore2b37442012-05-04 22:38:52 +00005883 public:
5884 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00005885
5886 void diagnoseNotICE(Sema &S, SourceLocation Loc,
5887 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00005888 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
5889 }
5890 } Diagnoser(ArgType);
5891
5892 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005893 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00005894 if (!Arg)
5895 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005896 }
5897
Richard Smithd663fdd2014-12-17 20:42:37 +00005898 // From here on out, all we care about is the unqualified form
5899 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005900 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00005901
5902 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00005903 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00005904 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00005905 } else if (ParamType->isBooleanType()) {
5906 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005907 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005908 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
5909 !ParamType->isEnumeralType()) {
5910 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005911 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005912 } else {
5913 // We can't perform this conversion.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005914 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005915 diag::err_template_arg_not_convertible)
Richard Smithd663fdd2014-12-17 20:42:37 +00005916 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00005917 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005918 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005919 }
5920
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005921 // Add the value of this argument to the list of converted
5922 // arguments. We use the bitwidth and signedness of the template
5923 // parameter.
5924 if (Arg->isValueDependent()) {
5925 // The argument is value-dependent. Create a new
5926 // TemplateArgument with the converted expression.
5927 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005928 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005929 }
5930
Douglas Gregor52aba872009-03-14 00:20:21 +00005931 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00005932 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00005933 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00005934
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005935 if (ParamType->isBooleanType()) {
5936 // Value must be zero or one.
5937 Value = Value != 0;
5938 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5939 if (Value.getBitWidth() != AllowedBits)
5940 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005941 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005942 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005943 llvm::APSInt OldValue = Value;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005944
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005945 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005946 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005947 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005948 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005949 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005950 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Simon Pilgrim6905d222016-12-30 22:55:33 +00005951
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005952 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005953 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005954 && (OldValue.isSigned() && OldValue.isNegative())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005955 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005956 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5957 << Arg->getSourceRange();
5958 Diag(Param->getLocation(), diag::note_template_param_here);
5959 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005960
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005961 // Complain if we overflowed the template parameter's type.
5962 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005963 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005964 RequiredBits = OldValue.getActiveBits();
5965 else if (OldValue.isUnsigned())
5966 RequiredBits = OldValue.getActiveBits() + 1;
5967 else
5968 RequiredBits = OldValue.getMinSignedBits();
5969 if (RequiredBits > AllowedBits) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005970 Diag(Arg->getLocStart(),
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005971 diag::warn_template_arg_too_large)
5972 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5973 << Arg->getSourceRange();
5974 Diag(Param->getLocation(), diag::note_template_param_here);
5975 }
Douglas Gregor52aba872009-03-14 00:20:21 +00005976 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005977
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005978 Converted = TemplateArgument(Context, Value,
Simon Pilgrim6905d222016-12-30 22:55:33 +00005979 ParamType->isEnumeralType()
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00005980 ? Context.getCanonicalType(ParamType)
5981 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005982 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00005983 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005984
Richard Smith08b12f12011-10-27 22:11:44 +00005985 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00005986 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
5987
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005988 // Handle pointer-to-function, reference-to-function, and
5989 // pointer-to-member-function all in (roughly) the same way.
5990 if (// -- For a non-type template-parameter of type pointer to
5991 // function, only the function-to-pointer conversion (4.3) is
5992 // applied. If the template-argument represents a set of
5993 // overloaded functions (or a pointer to such), the matching
5994 // function is selected from the set (13.4).
5995 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005996 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005997 // -- For a non-type template-parameter of type reference to
5998 // function, no conversions apply. If the template-argument
5999 // represents a set of overloaded functions, the matching
6000 // function is selected from the set (13.4).
6001 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006002 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006003 // -- For a non-type template-parameter of type pointer to
6004 // member function, no conversions apply. If the
6005 // template-argument represents a set of overloaded member
6006 // functions, the matching member function is selected from
6007 // the set (13.4).
6008 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006009 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006010 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006011
Douglas Gregor064fdb22010-04-14 23:11:21 +00006012 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006013 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00006014 true,
6015 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006016 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00006017 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00006018
6019 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6020 ArgType = Arg->getType();
6021 } else
John Wiegley01296292011-04-08 18:41:53 +00006022 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006023 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006024
John Wiegley01296292011-04-08 18:41:53 +00006025 if (!ParamType->isMemberPointerType()) {
6026 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6027 ParamType,
6028 Arg, Converted))
6029 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006030 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00006031 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00006032
Douglas Gregor20fdef32012-04-10 17:08:25 +00006033 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6034 Converted))
John Wiegley01296292011-04-08 18:41:53 +00006035 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006036 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006037 }
6038
Chris Lattner696197c2009-02-20 21:37:53 +00006039 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006040 // -- for a non-type template-parameter of type pointer to
6041 // object, qualification conversions (4.4) and the
6042 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00006043 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00006044 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006045 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00006046
John Wiegley01296292011-04-08 18:41:53 +00006047 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6048 ParamType,
6049 Arg, Converted))
6050 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006051 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00006052 }
Mike Stump11289f42009-09-09 15:08:12 +00006053
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006054 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006055 // -- For a non-type template-parameter of type reference to
6056 // object, no conversions apply. The type referred to by the
6057 // reference may be more cv-qualified than the (otherwise
6058 // identical) type of the template-argument. The
6059 // template-parameter is bound directly to the
6060 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00006061 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006062 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00006063
Douglas Gregor064fdb22010-04-14 23:11:21 +00006064 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006065 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
6066 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00006067 true,
6068 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006069 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00006070 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00006071
6072 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6073 ArgType = Arg->getType();
6074 } else
John Wiegley01296292011-04-08 18:41:53 +00006075 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006076 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006077
John Wiegley01296292011-04-08 18:41:53 +00006078 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6079 ParamType,
6080 Arg, Converted))
6081 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006082 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006083 }
Douglas Gregor0e558532009-02-11 16:16:59 +00006084
Douglas Gregor20fdef32012-04-10 17:08:25 +00006085 // Deal with parameters of type std::nullptr_t.
6086 if (ParamType->isNullPtrType()) {
6087 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6088 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006089 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006090 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006091
Douglas Gregor20fdef32012-04-10 17:08:25 +00006092 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
6093 case NPV_NotNullPointer:
6094 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
6095 << Arg->getType() << ParamType;
6096 Diag(Param->getLocation(), diag::note_template_param_here);
6097 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00006098
Douglas Gregor20fdef32012-04-10 17:08:25 +00006099 case NPV_Error:
6100 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00006101
Douglas Gregor20fdef32012-04-10 17:08:25 +00006102 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00006103 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00006104 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
6105 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006106 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006107 }
6108 }
6109
Douglas Gregor0e558532009-02-11 16:16:59 +00006110 // -- For a non-type template-parameter of type pointer to data
6111 // member, qualification conversions (4.4) are applied.
6112 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
6113
Douglas Gregor20fdef32012-04-10 17:08:25 +00006114 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6115 Converted))
John Wiegley01296292011-04-08 18:41:53 +00006116 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006117 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00006118}
6119
Richard Smith26b86ea2016-12-31 21:41:23 +00006120static void DiagnoseTemplateParameterListArityMismatch(
6121 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
6122 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
6123
Douglas Gregord32e0282009-02-09 23:23:08 +00006124/// \brief Check a template argument against its corresponding
6125/// template template parameter.
6126///
6127/// This routine implements the semantics of C++ [temp.arg.template].
6128/// It returns true if an error occurred, and false otherwise.
6129bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00006130 TemplateArgumentLoc &Arg,
Richard Smith1fde8ec2012-09-07 02:06:42 +00006131 unsigned ArgumentPackIndex) {
Eli Friedmanb826a002012-09-26 02:36:12 +00006132 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006133 TemplateDecl *Template = Name.getAsTemplateDecl();
6134 if (!Template) {
6135 // Any dependent template name is fine.
6136 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
6137 return false;
6138 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00006139
Richard Smith26b86ea2016-12-31 21:41:23 +00006140 if (Template->isInvalidDecl())
6141 return true;
6142
Richard Smith3f1b5d02011-05-05 21:57:07 +00006143 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00006144 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00006145 // the name of a class template or an alias template, expressed as an
6146 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00006147 // primary class templates are considered when matching the
6148 // template template argument with the corresponding parameter;
6149 // partial specializations are not considered even if their
6150 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00006151 //
6152 // Note that we also allow template template parameters here, which
6153 // will happen when we are dealing with, e.g., class template
6154 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00006155 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00006156 !isa<TemplateTemplateParmDecl>(Template) &&
David Majnemerc2406d42016-07-11 17:09:56 +00006157 !isa<TypeAliasTemplateDecl>(Template) &&
6158 !isa<BuiltinTemplateDecl>(Template)) {
6159 assert(isa<FunctionTemplateDecl>(Template) &&
6160 "Only function templates are possible here");
Faisal Valib8b04f82016-03-26 20:46:45 +00006161 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
David Majnemerc2406d42016-07-11 17:09:56 +00006162 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
6163 << Template;
Douglas Gregor85e0f662009-02-10 00:24:35 +00006164 }
6165
Richard Smith1fde8ec2012-09-07 02:06:42 +00006166 TemplateParameterList *Params = Param->getTemplateParameters();
6167 if (Param->isExpandedParameterPack())
6168 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
6169
Richard Smith26b86ea2016-12-31 21:41:23 +00006170 // C++1z [temp.arg.template]p3: (DR 150)
6171 // A template-argument matches a template template-parameter P when P
6172 // is at least as specialized as the template-argument A.
6173 if (getLangOpts().RelaxedTemplateTemplateArgs) {
6174 // Quick check for the common case:
6175 // If P contains a parameter pack, then A [...] matches P if each of A's
6176 // template parameters matches the corresponding template parameter in
6177 // the template-parameter-list of P.
6178 if (TemplateParameterListsAreEqual(
6179 Template->getTemplateParameters(), Params, false,
6180 TPL_TemplateTemplateArgumentMatch, Arg.getLocation()))
6181 return false;
6182
6183 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
6184 Arg.getLocation()))
6185 return false;
6186 // FIXME: Produce better diagnostics for deduction failures.
6187 }
6188
Douglas Gregor85e0f662009-02-10 00:24:35 +00006189 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00006190 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006191 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006192 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006193 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00006194}
6195
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006196/// \brief Given a non-type template argument that refers to a
6197/// declaration and the type of its corresponding non-type template
6198/// parameter, produce an expression that properly refers to that
6199/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006200ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006201Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6202 QualType ParamType,
6203 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00006204 // C++ [temp.param]p8:
6205 //
6206 // A non-type template-parameter of type "array of T" or
6207 // "function returning T" is adjusted to be of type "pointer to
6208 // T" or "pointer to function returning T", respectively.
6209 if (ParamType->isArrayType())
6210 ParamType = Context.getArrayDecayedType(ParamType);
6211 else if (ParamType->isFunctionType())
6212 ParamType = Context.getPointerType(ParamType);
6213
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006214 // For a NULL non-type template argument, return nullptr casted to the
6215 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00006216 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006217 return ImpCastExprToType(
6218 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
6219 ParamType,
6220 ParamType->getAs<MemberPointerType>()
6221 ? CK_NullToMemberPointer
6222 : CK_NullToPointer);
6223 }
Eli Friedmanb826a002012-09-26 02:36:12 +00006224 assert(Arg.getKind() == TemplateArgument::Declaration &&
6225 "Only declaration template arguments permitted here");
6226
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006227 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
6228
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006229 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00006230 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
6231 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006232 // If the value is a class member, we might have a pointer-to-member.
6233 // Determine whether the non-type template template parameter is of
6234 // pointer-to-member type. If so, we need to build an appropriate
6235 // expression for a pointer-to-member, since a "normal" DeclRefExpr
6236 // would refer to the member itself.
6237 if (ParamType->isMemberPointerType()) {
6238 QualType ClassType
6239 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
6240 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00006241 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00006242 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006243 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00006244 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00006245
6246 // The actual value-ness of this is unimportant, but for
6247 // internal consistency's sake, references to instance methods
6248 // are r-values.
6249 ExprValueKind VK = VK_LValue;
6250 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
6251 VK = VK_RValue;
6252
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006253 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00006254 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00006255 VK,
John McCall7decc9e2010-11-18 06:31:45 +00006256 Loc,
6257 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006258 if (RefExpr.isInvalid())
6259 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006260
John McCalle3027922010-08-25 11:45:40 +00006261 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006262
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006263 // We might need to perform a trailing qualification conversion, since
6264 // the element type on the parameter could be more qualified than the
6265 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00006266 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006267 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00006268 ParamType.getUnqualifiedType(), false,
6269 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006270 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006271
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006272 assert(!RefExpr.isInvalid() &&
6273 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006274 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006275 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006276 }
6277 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006278
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006279 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00006280
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006281 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006282 // When the non-type template parameter is a pointer, take the
6283 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00006284 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006285 if (RefExpr.isInvalid())
6286 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006287
Richard Smithfc6fca12017-01-28 00:38:35 +00006288 if (!Context.hasSameUnqualifiedType(ParamType->getPointeeType(), T) &&
6289 (T->isFunctionType() || T->isArrayType())) {
6290 // Decay functions and arrays unless we're forming a pointer to array.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006291 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00006292 if (RefExpr.isInvalid())
6293 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006294
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006295 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006296 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006297
Douglas Gregorb242683d2010-04-01 18:32:35 +00006298 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00006299 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006300 }
6301
John McCall7decc9e2010-11-18 06:31:45 +00006302 ExprValueKind VK = VK_RValue;
6303
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006304 // If the non-type template parameter has reference type, qualify the
6305 // resulting declaration reference with the extra qualifiers on the
6306 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00006307 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
6308 VK = VK_LValue;
6309 T = Context.getQualifiedType(T,
6310 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00006311 } else if (isa<FunctionDecl>(VD)) {
6312 // References to functions are always lvalues.
6313 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00006314 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006315
John McCall7decc9e2010-11-18 06:31:45 +00006316 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006317}
6318
6319/// \brief Construct a new expression that refers to the given
6320/// integral template argument with the given source-location
6321/// information.
6322///
6323/// This routine takes care of the mapping from an integral template
6324/// argument (which may have any integral type) to the appropriate
6325/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006326ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006327Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6328 SourceLocation Loc) {
6329 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00006330 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006331 QualType OrigT = Arg.getIntegralType();
6332
6333 // If this is an enum type that we're instantiating, we need to use an integer
6334 // type the same size as the enumerator. We don't want to build an
6335 // IntegerLiteral with enum type. The integer type of an enum type can be of
6336 // any integral type with C++11 enum classes, make sure we create the right
6337 // type of literal for it.
6338 QualType T = OrigT;
6339 if (const EnumType *ET = OrigT->getAs<EnumType>())
6340 T = ET->getDecl()->getIntegerType();
6341
6342 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00006343 if (T->isAnyCharacterType()) {
Aaron Ballman9a17c852016-01-07 20:59:26 +00006344 // This does not need to handle u8 character literals because those are
6345 // of type char, and so can also be covered by an ASCII character literal.
Douglas Gregorfb65e592011-07-27 05:40:30 +00006346 CharacterLiteral::CharacterKind Kind;
6347 if (T->isWideCharType())
6348 Kind = CharacterLiteral::Wide;
6349 else if (T->isChar16Type())
6350 Kind = CharacterLiteral::UTF16;
6351 else if (T->isChar32Type())
6352 Kind = CharacterLiteral::UTF32;
6353 else
6354 Kind = CharacterLiteral::Ascii;
6355
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006356 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
6357 Kind, T, Loc);
6358 } else if (T->isBooleanType()) {
6359 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
6360 T, Loc);
6361 } else if (T->isNullPtrType()) {
6362 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
6363 } else {
6364 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00006365 }
6366
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006367 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00006368 // FIXME: This is a hack. We need a better way to handle substituted
6369 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00006370 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
6371 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006372 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00006373 Loc, Loc);
6374 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006375
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006376 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006377}
6378
Richard Smith43a833b2017-01-09 23:54:33 +00006379static bool isDependentOnOuter(NonTypeTemplateParmDecl *NTTP) {
6380 if (NTTP->getDepth() == 0 || !NTTP->getType()->isDependentType())
6381 return false;
6382 DependencyChecker Checker(NTTP->getDepth(), /*IgnoreNonTypeDependent*/ false,
6383 /*FindLessThanDepth*/ true);
6384 Checker.TraverseType(NTTP->getType());
6385 return Checker.Match;
6386}
6387
Douglas Gregor641040a2011-01-12 23:45:44 +00006388/// \brief Match two template parameters within template parameter lists.
6389static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
6390 bool Complain,
6391 Sema::TemplateParameterListEqualKind Kind,
6392 SourceLocation TemplateArgLoc) {
6393 // Check the actual kind (type, non-type, template).
6394 if (Old->getKind() != New->getKind()) {
6395 if (Complain) {
6396 unsigned NextDiag = diag::err_template_param_different_kind;
6397 if (TemplateArgLoc.isValid()) {
6398 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6399 NextDiag = diag::note_template_param_different_kind;
6400 }
6401 S.Diag(New->getLocation(), NextDiag)
6402 << (Kind != Sema::TPL_TemplateMatch);
6403 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
6404 << (Kind != Sema::TPL_TemplateMatch);
6405 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006406
Douglas Gregor641040a2011-01-12 23:45:44 +00006407 return false;
6408 }
6409
Richard Smith26b86ea2016-12-31 21:41:23 +00006410 // Check that both are parameter packs or neither are parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006411 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006412 // template template parameter, the template template parameter can have
6413 // a parameter pack where the template template argument does not.
6414 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
6415 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
6416 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00006417 if (Complain) {
6418 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
6419 if (TemplateArgLoc.isValid()) {
6420 S.Diag(TemplateArgLoc,
6421 diag::err_template_arg_template_params_mismatch);
6422 NextDiag = diag::note_template_parameter_pack_non_pack;
6423 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006424
Douglas Gregor641040a2011-01-12 23:45:44 +00006425 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
6426 : isa<NonTypeTemplateParmDecl>(New)? 1
6427 : 2;
6428 S.Diag(New->getLocation(), NextDiag)
6429 << ParamKind << New->isParameterPack();
6430 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
6431 << ParamKind << Old->isParameterPack();
6432 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006433
Douglas Gregor641040a2011-01-12 23:45:44 +00006434 return false;
6435 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006436
Douglas Gregor641040a2011-01-12 23:45:44 +00006437 // For non-type template parameters, check the type of the parameter.
6438 if (NonTypeTemplateParmDecl *OldNTTP
6439 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
6440 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006441
Douglas Gregor641040a2011-01-12 23:45:44 +00006442 // If we are matching a template template argument to a template
6443 // template parameter and one of the non-type template parameter types
Richard Smith43a833b2017-01-09 23:54:33 +00006444 // is dependent on an outer template's parameter, then we must wait until
6445 // template instantiation time to actually compare the arguments.
Douglas Gregor641040a2011-01-12 23:45:44 +00006446 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
Richard Smith43a833b2017-01-09 23:54:33 +00006447 (isDependentOnOuter(OldNTTP) || isDependentOnOuter(NewNTTP)))
Douglas Gregor641040a2011-01-12 23:45:44 +00006448 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006449
Douglas Gregor641040a2011-01-12 23:45:44 +00006450 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
6451 if (Complain) {
6452 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
6453 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006454 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00006455 diag::err_template_arg_template_params_mismatch);
6456 NextDiag = diag::note_template_nontype_parm_different_type;
6457 }
6458 S.Diag(NewNTTP->getLocation(), NextDiag)
6459 << NewNTTP->getType()
6460 << (Kind != Sema::TPL_TemplateMatch);
6461 S.Diag(OldNTTP->getLocation(),
6462 diag::note_template_nontype_parm_prev_declaration)
6463 << OldNTTP->getType();
6464 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006465
Douglas Gregor641040a2011-01-12 23:45:44 +00006466 return false;
6467 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006468
Douglas Gregor641040a2011-01-12 23:45:44 +00006469 return true;
6470 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006471
Douglas Gregor641040a2011-01-12 23:45:44 +00006472 // For template template parameters, check the template parameter types.
6473 // The template parameter lists of template template
6474 // parameters must agree.
6475 if (TemplateTemplateParmDecl *OldTTP
6476 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006477 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00006478 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
6479 OldTTP->getTemplateParameters(),
6480 Complain,
6481 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006482 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00006483 : Kind),
6484 TemplateArgLoc);
6485 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006486
Douglas Gregor641040a2011-01-12 23:45:44 +00006487 return true;
6488}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006489
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006490/// \brief Diagnose a known arity mismatch when comparing template argument
6491/// lists.
6492static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006493void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006494 TemplateParameterList *New,
6495 TemplateParameterList *Old,
6496 Sema::TemplateParameterListEqualKind Kind,
6497 SourceLocation TemplateArgLoc) {
6498 unsigned NextDiag = diag::err_template_param_list_different_arity;
6499 if (TemplateArgLoc.isValid()) {
6500 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6501 NextDiag = diag::note_template_param_list_different_arity;
6502 }
6503 S.Diag(New->getTemplateLoc(), NextDiag)
6504 << (New->size() > Old->size())
6505 << (Kind != Sema::TPL_TemplateMatch)
6506 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
6507 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
6508 << (Kind != Sema::TPL_TemplateMatch)
6509 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
6510}
6511
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006512/// \brief Determine whether the given template parameter lists are
6513/// equivalent.
6514///
Mike Stump11289f42009-09-09 15:08:12 +00006515/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006516/// source code as part of a new template declaration.
6517///
6518/// \param Old The old template parameter list, typically found via
6519/// name lookup of the template declared with this template parameter
6520/// list.
6521///
6522/// \param Complain If true, this routine will produce a diagnostic if
6523/// the template parameter lists are not equivalent.
6524///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006525/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00006526///
6527/// \param TemplateArgLoc If this source location is valid, then we
6528/// are actually checking the template parameter list of a template
6529/// argument (New) against the template parameter list of its
6530/// corresponding template template parameter (Old). We produce
6531/// slightly different diagnostics in this scenario.
6532///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006533/// \returns True if the template parameter lists are equal, false
6534/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00006535bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006536Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
6537 TemplateParameterList *Old,
6538 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006539 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00006540 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006541 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
6542 if (Complain)
6543 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6544 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006545
6546 return false;
6547 }
6548
Douglas Gregor641040a2011-01-12 23:45:44 +00006549 // C++0x [temp.arg.template]p3:
6550 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00006551 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00006552 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00006553 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006554 // template-parameter-list of P. [...]
6555 TemplateParameterList::iterator NewParm = New->begin();
6556 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006557 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006558 OldParmEnd = Old->end();
6559 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00006560 if (Kind != TPL_TemplateTemplateArgumentMatch ||
6561 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006562 if (NewParm == NewParmEnd) {
6563 if (Complain)
6564 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6565 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006566
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006567 return false;
6568 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006569
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006570 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6571 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006572 return false;
6573
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006574 ++NewParm;
6575 continue;
6576 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006577
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006578 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00006579 // [...] When P's template- parameter-list contains a template parameter
6580 // pack (14.5.3), the template parameter pack will match zero or more
6581 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006582 // template-parameter-list of A with the same type and form as the
6583 // template parameter pack in P (ignoring whether those template
6584 // parameters are template parameter packs).
6585 for (; NewParm != NewParmEnd; ++NewParm) {
6586 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6587 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006588 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006589 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006590 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006591
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006592 // Make sure we exhausted all of the arguments.
6593 if (NewParm != NewParmEnd) {
6594 if (Complain)
6595 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6596 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006597
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006598 return false;
6599 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006600
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006601 return true;
6602}
6603
6604/// \brief Check whether a template can be declared within this scope.
6605///
6606/// If the template declaration is valid in this scope, returns
6607/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00006608bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006609Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00006610 if (!S)
6611 return false;
6612
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006613 // Find the nearest enclosing declaration scope.
6614 while ((S->getFlags() & Scope::DeclScope) == 0 ||
6615 (S->getFlags() & Scope::TemplateParamScope) != 0)
6616 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00006617
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00006618 // C++ [temp]p4:
6619 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00006620 DeclContext *Ctx = S->getEntity();
Alex Lorenz560ae562016-11-02 15:46:34 +00006621 if (Ctx && Ctx->isExternCContext()) {
6622 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
6623 << TemplateParams->getSourceRange();
6624 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
6625 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
6626 return true;
6627 }
Richard Smith8df390f2016-09-08 23:14:54 +00006628 Ctx = Ctx->getRedeclContext();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006629
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00006630 // C++ [temp]p2:
6631 // A template-declaration can appear only as a namespace scope or
6632 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00006633 if (Ctx) {
6634 if (Ctx->isFileContext())
6635 return false;
6636 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
6637 // C++ [temp.mem]p2:
6638 // A local class shall not have member templates.
6639 if (RD->isLocalClass())
6640 return Diag(TemplateParams->getTemplateLoc(),
6641 diag::err_template_inside_local_class)
6642 << TemplateParams->getSourceRange();
6643 else
6644 return false;
6645 }
6646 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006647
Mike Stump11289f42009-09-09 15:08:12 +00006648 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006649 diag::err_template_outside_namespace_or_class_scope)
6650 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006651}
Douglas Gregor67a65642009-02-17 23:15:12 +00006652
Douglas Gregor54888652009-10-07 00:13:32 +00006653/// \brief Determine what kind of template specialization the given declaration
6654/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006655static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00006656 if (!D)
6657 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006658
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006659 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
6660 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00006661 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
6662 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00006663 if (VarDecl *Var = dyn_cast<VarDecl>(D))
6664 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006665
Douglas Gregor54888652009-10-07 00:13:32 +00006666 return TSK_Undeclared;
6667}
6668
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006669/// \brief Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006670/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00006671///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006672/// This routine determines whether a template specialization can be declared
6673/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00006674///
6675/// \param S the semantic analysis object for which this check is being
6676/// performed.
6677///
6678/// \param Specialized the entity being specialized or instantiated, which
6679/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006680/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00006681/// member class).
6682///
6683/// \param PrevDecl the previous declaration of this entity, if any.
6684///
6685/// \param Loc the location of the explicit specialization or instantiation of
6686/// this entity.
6687///
6688/// \param IsPartialSpecialization whether this is a partial specialization of
6689/// a class template.
6690///
Douglas Gregor54888652009-10-07 00:13:32 +00006691/// \returns true if there was an error that we cannot recover from, false
6692/// otherwise.
6693static bool CheckTemplateSpecializationScope(Sema &S,
6694 NamedDecl *Specialized,
6695 NamedDecl *PrevDecl,
6696 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006697 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00006698 // Keep these "kind" numbers in sync with the %select statements in the
6699 // various diagnostics emitted by this routine.
6700 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00006701 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006702 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006703 else if (isa<VarTemplateDecl>(Specialized))
6704 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00006705 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006706 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006707 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006708 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006709 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00006710 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006711 else if (isa<RecordDecl>(Specialized))
6712 EntityKind = 7;
6713 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
6714 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00006715 else {
Richard Smith7d137e32012-03-23 03:33:32 +00006716 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006717 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006718 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00006719 return true;
6720 }
6721
Douglas Gregorf47b9112009-02-25 22:02:03 +00006722 // C++ [temp.expl.spec]p2:
6723 // An explicit specialization shall be declared in the namespace
6724 // of which the template is a member, or, for member templates, in
6725 // the namespace of which the enclosing class or enclosing class
6726 // template is a member. An explicit specialization of a member
6727 // function, member class or static data member of a class
6728 // template shall be declared in the namespace of which the class
6729 // template is a member. Such a declaration may also be a
6730 // definition. If the declaration is not a definition, the
6731 // specialization may be defined later in the name- space in which
6732 // the explicit specialization was declared, or in a namespace
6733 // that encloses the one in which the explicit specialization was
6734 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00006735 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00006736 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006737 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00006738 return true;
6739 }
Douglas Gregore4b05162009-10-07 17:21:34 +00006740
Douglas Gregor40fb7442009-10-07 17:30:37 +00006741 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006742 if (S.getLangOpts().MicrosoftExt) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006743 // Do not warn for class scope explicit specialization during
6744 // instantiation, warning was already emitted during pattern
6745 // semantic analysis.
6746 if (!S.ActiveTemplateInstantiations.size())
6747 S.Diag(Loc, diag::ext_function_specialization_in_class)
6748 << Specialized;
6749 } else {
6750 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
6751 << Specialized;
6752 return true;
6753 }
Douglas Gregor40fb7442009-10-07 17:30:37 +00006754 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006755
Douglas Gregor44e5a0a2011-10-20 16:41:18 +00006756 if (S.CurContext->isRecord() &&
6757 !S.CurContext->Equals(Specialized->getDeclContext())) {
6758 // Make sure that we're specializing in the right record context.
6759 // Otherwise, things can go horribly wrong.
6760 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
6761 << Specialized;
6762 return true;
6763 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006764
Douglas Gregore4b05162009-10-07 17:21:34 +00006765 // C++ [temp.class.spec]p6:
6766 // A class template partial specialization may be declared or redeclared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006767 // in any namespace scope in which its definition may be defined (14.5.1
6768 // and 14.5.2).
Richard Smitha98f8fc2013-12-07 05:09:50 +00006769 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00006770 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00006771 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00006772
6773 // Make sure that this redeclaration (or definition) occurs in an enclosing
6774 // namespace.
6775 // Note that HandleDeclarator() performs this check for explicit
6776 // specializations of function templates, static data members, and member
6777 // functions, so we skip the check here for those kinds of entities.
6778 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
6779 // Should we refactor that check, so that it occurs later?
6780 if (!DC->Encloses(SpecializedContext) &&
6781 !(isa<FunctionTemplateDecl>(Specialized) ||
6782 isa<FunctionDecl>(Specialized) ||
6783 isa<VarTemplateDecl>(Specialized) ||
6784 isa<VarDecl>(Specialized))) {
6785 if (isa<TranslationUnitDecl>(SpecializedContext))
6786 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
6787 << EntityKind << Specialized;
Alexey Bataev0068cb22015-03-20 07:21:46 +00006788 else if (isa<NamespaceDecl>(SpecializedContext)) {
6789 int Diag = diag::err_template_spec_redecl_out_of_scope;
6790 if (S.getLangOpts().MicrosoftExt)
6791 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
6792 S.Diag(Loc, Diag) << EntityKind << Specialized
6793 << cast<NamedDecl>(SpecializedContext);
6794 } else
Richard Smitha98f8fc2013-12-07 05:09:50 +00006795 llvm_unreachable("unexpected namespace context for specialization");
6796
6797 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
6798 } else if ((!PrevDecl ||
6799 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
6800 getTemplateSpecializationKind(PrevDecl) ==
6801 TSK_ImplicitInstantiation)) {
Douglas Gregorb1aab432010-09-12 05:08:28 +00006802 // C++ [temp.exp.spec]p2:
6803 // An explicit specialization shall be declared in the namespace of which
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006804 // the template is a member, or, for member templates, in the namespace
Douglas Gregorb1aab432010-09-12 05:08:28 +00006805 // of which the enclosing class or enclosing class template is a member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006806 // An explicit specialization of a member function, member class or
6807 // static data member of a class template shall be declared in the
Douglas Gregorb1aab432010-09-12 05:08:28 +00006808 // namespace of which the class template is a member.
6809 //
Richard Smitha98f8fc2013-12-07 05:09:50 +00006810 // C++11 [temp.expl.spec]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006811 // An explicit specialization shall be declared in a namespace enclosing
Douglas Gregorb1aab432010-09-12 05:08:28 +00006812 // the specialized template.
Richard Smitha98f8fc2013-12-07 05:09:50 +00006813 // C++11 [temp.explicit]p3:
6814 // An explicit instantiation shall appear in an enclosing namespace of its
6815 // template.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006816 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006817 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
Richard Smith0bf8a4922011-10-18 20:49:44 +00006818 if (isa<TranslationUnitDecl>(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006819 assert(!IsCPlusPlus11Extension &&
Richard Smith0bf8a4922011-10-18 20:49:44 +00006820 "DC encloses TU but isn't in enclosing namespace set");
6821 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor8ce63152010-09-12 05:24:55 +00006822 << EntityKind << Specialized;
Richard Smith0bf8a4922011-10-18 20:49:44 +00006823 } else if (isa<NamespaceDecl>(SpecializedContext)) {
6824 int Diag;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006825 if (!IsCPlusPlus11Extension)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006826 Diag = diag::err_template_spec_decl_out_of_scope;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006827 else if (!S.getLangOpts().CPlusPlus11)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006828 Diag = diag::ext_template_spec_decl_out_of_scope;
6829 else
6830 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
6831 S.Diag(Loc, Diag)
6832 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
6833 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006834
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006835 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00006836 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006837 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006838
Douglas Gregorf47b9112009-02-25 22:02:03 +00006839 return false;
6840}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006841
Richard Smith57aae072016-12-28 02:37:25 +00006842static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
6843 if (!E->isTypeDependent())
Richard Smith6056d5e2014-02-09 00:54:43 +00006844 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00006845 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00006846 Checker.TraverseStmt(E);
Richard Smith57aae072016-12-28 02:37:25 +00006847 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00006848 return E->getSourceRange();
6849 return Checker.MatchLoc;
6850}
6851
6852static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
6853 if (!TL.getType()->isDependentType())
6854 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00006855 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00006856 Checker.TraverseTypeLoc(TL);
Richard Smith57aae072016-12-28 02:37:25 +00006857 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00006858 return TL.getSourceRange();
6859 return Checker.MatchLoc;
6860}
6861
Larisse Voufo39a1e502013-08-06 01:03:05 +00006862/// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006863/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006864static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006865 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
6866 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006867 for (unsigned I = 0; I != NumArgs; ++I) {
6868 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006869 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006870 S, TemplateNameLoc, Param, Args[I].pack_begin(),
6871 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006872 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006873
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006874 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006875 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006876
Eli Friedmanb826a002012-09-26 02:36:12 +00006877 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006878 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00006879
6880 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006881
Douglas Gregor98318c22011-01-03 21:37:45 +00006882 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006883 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
6884 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00006885
6886 // Strip off any implicit casts we added as part of type checking.
6887 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
6888 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006889
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006890 // C++ [temp.class.spec]p8:
6891 // A non-type argument is non-specialized if it is the name of a
6892 // non-type parameter. All other non-type arguments are
6893 // specialized.
6894 //
6895 // Below, we check the two conditions that only apply to
6896 // specialized non-type arguments, so skip any non-specialized
6897 // arguments.
6898 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00006899 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006900 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006901
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006902 // C++ [temp.class.spec]p9:
6903 // Within the argument list of a class template partial
6904 // specialization, the following restrictions apply:
6905 // -- A partially specialized non-type argument expression
6906 // shall not involve a template parameter of the partial
6907 // specialization except when the argument expression is a
6908 // simple identifier.
Richard Smith57aae072016-12-28 02:37:25 +00006909 // -- The type of a template parameter corresponding to a
6910 // specialized non-type argument shall not be dependent on a
6911 // parameter of the specialization.
6912 // DR1315 removes the first bullet, leaving an incoherent set of rules.
6913 // We implement a compromise between the original rules and DR1315:
6914 // -- A specialized non-type template argument shall not be
6915 // type-dependent and the corresponding template parameter
6916 // shall have a non-dependent type.
Richard Smith6056d5e2014-02-09 00:54:43 +00006917 SourceRange ParamUseRange =
Richard Smith57aae072016-12-28 02:37:25 +00006918 findTemplateParameterInType(Param->getDepth(), ArgExpr);
Richard Smith6056d5e2014-02-09 00:54:43 +00006919 if (ParamUseRange.isValid()) {
6920 if (IsDefaultArgument) {
6921 S.Diag(TemplateNameLoc,
6922 diag::err_dependent_non_type_arg_in_partial_spec);
6923 S.Diag(ParamUseRange.getBegin(),
6924 diag::note_dependent_non_type_default_arg_in_partial_spec)
6925 << ParamUseRange;
6926 } else {
6927 S.Diag(ParamUseRange.getBegin(),
6928 diag::err_dependent_non_type_arg_in_partial_spec)
6929 << ParamUseRange;
6930 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006931 return true;
6932 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006933
Richard Smith6056d5e2014-02-09 00:54:43 +00006934 ParamUseRange = findTemplateParameter(
Richard Smith57aae072016-12-28 02:37:25 +00006935 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
Richard Smith6056d5e2014-02-09 00:54:43 +00006936 if (ParamUseRange.isValid()) {
6937 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
6938 diag::err_dependent_typed_non_type_arg_in_partial_spec)
Richard Smith57aae072016-12-28 02:37:25 +00006939 << Param->getType();
Richard Smith6056d5e2014-02-09 00:54:43 +00006940 S.Diag(Param->getLocation(), diag::note_template_param_here)
Richard Smith57aae072016-12-28 02:37:25 +00006941 << (IsDefaultArgument ? ParamUseRange : SourceRange())
6942 << ParamUseRange;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006943 return true;
6944 }
6945 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006946
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006947 return false;
6948}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006949
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006950/// \brief Check the non-type template arguments of a class template
6951/// partial specialization according to C++ [temp.class.spec]p9.
6952///
Richard Smith6056d5e2014-02-09 00:54:43 +00006953/// \param TemplateNameLoc the location of the template name.
Simon Pilgrim6905d222016-12-30 22:55:33 +00006954/// \param PrimaryTemplate the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00006955/// template.
6956/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00006957/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00006958/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006959///
Richard Smith6056d5e2014-02-09 00:54:43 +00006960/// \returns \c true if there was an error, \c false otherwise.
Richard Smith57aae072016-12-28 02:37:25 +00006961bool Sema::CheckTemplatePartialSpecializationArgs(
6962 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
6963 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
6964 // We have to be conservative when checking a template in a dependent
6965 // context.
6966 if (PrimaryTemplate->getDeclContext()->isDependentContext())
6967 return false;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006968
Richard Smith57aae072016-12-28 02:37:25 +00006969 TemplateParameterList *TemplateParams =
6970 PrimaryTemplate->getTemplateParameters();
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006971 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6972 NonTypeTemplateParmDecl *Param
6973 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
6974 if (!Param)
6975 continue;
6976
Richard Smith57aae072016-12-28 02:37:25 +00006977 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
6978 Param, &TemplateArgs[I],
6979 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006980 return true;
6981 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006982
6983 return false;
6984}
6985
John McCall48871652010-08-21 09:40:31 +00006986DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00006987Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
6988 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00006989 SourceLocation KWLoc,
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006990 SourceLocation ModulePrivateLoc,
Richard Smith4b55a9c2014-04-17 03:29:33 +00006991 TemplateIdAnnotation &TemplateId,
Douglas Gregor67a65642009-02-17 23:15:12 +00006992 AttributeList *Attr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00006993 MultiTemplateParamsArg
6994 TemplateParameterLists,
6995 SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006996 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00006997
Richard Smith4b55a9c2014-04-17 03:29:33 +00006998 CXXScopeSpec &SS = TemplateId.SS;
6999
Abramo Bagnara60804e12011-03-18 15:16:37 +00007000 // NOTE: KWLoc is the location of the tag keyword. This will instead
7001 // store the location of the outermost template keyword in the declaration.
7002 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00007003 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
7004 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
7005 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
7006 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00007007
Douglas Gregor67a65642009-02-17 23:15:12 +00007008 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00007009 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00007010 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00007011 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
7012
7013 if (!ClassTemplate) {
7014 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007015 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00007016 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
7017 return true;
7018 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007019
Richard Smithf445f192017-02-09 21:04:43 +00007020 bool isMemberSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00007021 bool isPartialSpecialization = false;
7022
Douglas Gregorf47b9112009-02-25 22:02:03 +00007023 // Check the validity of the template headers that introduce this
7024 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00007025 // FIXME: We probably shouldn't complain about these headers for
7026 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007027 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00007028 TemplateParameterList *TemplateParams =
7029 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00007030 KWLoc, TemplateNameLoc, SS, &TemplateId,
Richard Smithf445f192017-02-09 21:04:43 +00007031 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
Richard Smith4b55a9c2014-04-17 03:29:33 +00007032 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007033 if (Invalid)
7034 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007035
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007036 if (TemplateParams && TemplateParams->size() > 0) {
7037 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007038
Douglas Gregorec9518b2010-12-21 08:14:57 +00007039 if (TUK == TUK_Friend) {
7040 Diag(KWLoc, diag::err_partial_specialization_friend)
7041 << SourceRange(LAngleLoc, RAngleLoc);
7042 return true;
7043 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007044
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007045 // C++ [temp.class.spec]p10:
7046 // The template parameter list of a specialization shall not
7047 // contain default template argument values.
7048 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7049 Decl *Param = TemplateParams->getParam(I);
7050 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
7051 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00007052 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007053 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00007054 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007055 }
7056 } else if (NonTypeTemplateParmDecl *NTTP
7057 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
7058 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00007059 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007060 diag::err_default_arg_in_partial_spec)
7061 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00007062 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007063 }
7064 } else {
7065 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00007066 if (TTP->hasDefaultArgument()) {
7067 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007068 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00007069 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00007070 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00007071 }
7072 }
7073 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007074 } else if (TemplateParams) {
7075 if (TUK == TUK_Friend)
7076 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00007077 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007078 SourceRange(TemplateParams->getTemplateLoc(),
7079 TemplateParams->getRAngleLoc()))
7080 << SourceRange(LAngleLoc, RAngleLoc);
Richard Smith4b55a9c2014-04-17 03:29:33 +00007081 } else {
7082 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007083 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00007084
Douglas Gregor67a65642009-02-17 23:15:12 +00007085 // Check that the specialization uses the same tag kind as the
7086 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007087 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7088 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00007089 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007090 Kind, TUK == TUK_Definition, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00007091 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007092 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00007093 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007094 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00007095 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007096 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00007097 diag::note_previous_use);
7098 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7099 }
7100
Douglas Gregorc40290e2009-03-09 23:48:35 +00007101 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00007102 TemplateArgumentListInfo TemplateArgs =
7103 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00007104
Douglas Gregor14406932011-01-03 20:35:03 +00007105 // Check for unexpanded parameter packs in any of the template arguments.
7106 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007107 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00007108 UPPC_PartialSpecialization))
7109 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007110
Douglas Gregor67a65642009-02-17 23:15:12 +00007111 // Check that the template argument list is well-formed for this
7112 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007113 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007114 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7115 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00007116 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00007117
Douglas Gregor2373c592009-05-31 09:31:02 +00007118 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00007119 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00007120 if (isPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00007121 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
7122 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007123 return true;
7124
Richard Smith57aae072016-12-28 02:37:25 +00007125 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
7126 // also do it during instantiation.
Douglas Gregor678d76c2011-07-01 01:22:09 +00007127 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007128 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00007129 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00007130 TemplateArgs.arguments(), InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00007131 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
7132 << ClassTemplate->getDeclName();
7133 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00007134 }
7135 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007136
Craig Topperc3ec1492014-05-26 06:22:03 +00007137 void *InsertPos = nullptr;
7138 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00007139
7140 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007141 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00007142 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00007143 else
Craig Topper7e0daca2014-06-26 04:58:53 +00007144 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00007145
Craig Topperc3ec1492014-05-26 06:22:03 +00007146 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00007147
Douglas Gregorf47b9112009-02-25 22:02:03 +00007148 // Check whether we can declare a class template specialization in
7149 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00007150 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007151 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
7152 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007153 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00007154 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007155
Douglas Gregor15301382009-07-30 17:40:51 +00007156 // The canonical type
7157 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00007158 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00007159 // Build the canonical type that describes the converted template
7160 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00007161 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7162 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00007163 Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007164
7165 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007166 ClassTemplate->getInjectedClassNameSpecialization())) {
7167 // C++ [temp.class.spec]p9b3:
7168 //
7169 // -- The argument list of the specialization shall not be identical
7170 // to the implicit argument list of the primary template.
Richard Smith0e617ec2016-12-27 07:56:27 +00007171 //
7172 // This rule has since been removed, because it's redundant given DR1495,
7173 // but we keep it because it produces better diagnostics and recovery.
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007174 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00007175 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00007176 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007177 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
7178 ClassTemplate->getIdentifier(),
7179 TemplateNameLoc,
7180 Attr,
7181 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00007182 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00007183 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00007184 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007185 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007186 }
Douglas Gregor15301382009-07-30 17:40:51 +00007187
Douglas Gregor2373c592009-05-31 09:31:02 +00007188 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00007189 ClassTemplatePartialSpecializationDecl *PrevPartial
7190 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007191 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00007192 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00007193 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007194 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00007195 TemplateParams,
7196 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007197 Converted,
John McCall6b51f282009-11-23 01:53:49 +00007198 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00007199 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00007200 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00007201 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007202 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Benjamin Kramer9cc210652015-08-05 09:40:49 +00007203 Partial->setTemplateParameterListsInfo(
7204 Context, TemplateParameterLists.drop_back(1));
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007205 }
Douglas Gregor2373c592009-05-31 09:31:02 +00007206
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007207 if (!PrevPartial)
7208 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00007209 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00007210
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007211 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00007212 // template specialization, make a note of that.
7213 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
7214 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007215
Richard Smith57aae072016-12-28 02:37:25 +00007216 CheckTemplatePartialSpecialization(Partial);
Douglas Gregor67a65642009-02-17 23:15:12 +00007217 } else {
7218 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00007219 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00007220 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007221 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00007222 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007223 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007224 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007225 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00007226 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00007227 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007228 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00007229 Specialization->setTemplateParameterListsInfo(Context,
Benjamin Kramer9cc210652015-08-05 09:40:49 +00007230 TemplateParameterLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007231 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007232
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007233 if (!PrevDecl)
7234 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00007235
David Majnemer678f50b2015-11-18 19:49:19 +00007236 if (CurContext->isDependentContext()) {
7237 // -fms-extensions permits specialization of nested classes without
7238 // fully specializing the outer class(es).
7239 assert(getLangOpts().MicrosoftExt &&
7240 "Only possible with -fms-extensions!");
7241 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7242 CanonType = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00007243 CanonTemplate, Converted);
David Majnemer678f50b2015-11-18 19:49:19 +00007244 } else {
7245 CanonType = Context.getTypeDeclType(Specialization);
7246 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007247 }
7248
Douglas Gregor06db9f52009-10-12 20:18:28 +00007249 // C++ [temp.expl.spec]p6:
7250 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007251 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007252 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007253 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007254 // use occurs; no diagnostic is required.
7255 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007256 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007257 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007258 // Is there any previous explicit specialization declaration?
7259 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7260 Okay = true;
7261 break;
7262 }
7263 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007264
Douglas Gregorc854c662010-02-26 06:03:23 +00007265 if (!Okay) {
7266 SourceRange Range(TemplateNameLoc, RAngleLoc);
7267 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
7268 << Context.getTypeDeclType(Specialization) << Range;
7269
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007270 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00007271 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007272 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00007273 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00007274 return true;
7275 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007276 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007277
Douglas Gregor2208a292009-09-26 20:57:03 +00007278 // If this is not a friend, note that this is an explicit specialization.
7279 if (TUK != TUK_Friend)
7280 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00007281
7282 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00007283 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00007284 RecordDecl *Def = Specialization->getDefinition();
7285 NamedDecl *Hidden = nullptr;
7286 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
7287 SkipBody->ShouldSkip = true;
7288 makeMergedDefinitionVisible(Hidden, KWLoc);
7289 // From here on out, treat this as just a redeclaration.
7290 TUK = TUK_Declaration;
7291 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00007292 SourceRange Range(TemplateNameLoc, RAngleLoc);
Richard Smith792c22d2016-12-24 04:09:05 +00007293 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00007294 Diag(Def->getLocation(), diag::note_previous_definition);
7295 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00007296 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00007297 }
7298 }
7299
John McCall659a3372010-12-18 03:30:47 +00007300 if (Attr)
7301 ProcessDeclAttributeList(S, Specialization, Attr);
7302
Richard Smith034b94a2012-08-17 03:20:55 +00007303 // Add alignment attributes if necessary; these attributes are checked when
7304 // the ASTContext lays out the structure.
7305 if (TUK == TUK_Definition) {
7306 AddAlignmentAttributesForRecord(Specialization);
7307 AddMsStructLayoutForRecord(Specialization);
7308 }
7309
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00007310 if (ModulePrivateLoc.isValid())
7311 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
7312 << (isPartialSpecialization? 1 : 0)
7313 << FixItHint::CreateRemoval(ModulePrivateLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00007314
Douglas Gregord56a91e2009-02-26 22:19:44 +00007315 // Build the fully-sugared type for this class template
7316 // specialization as the user wrote in the specialization
7317 // itself. This means that we'll pretty-print the type retrieved
7318 // from the specialization's declaration the way that the user
7319 // actually wrote the specialization, rather than formatting the
7320 // name based on the "canonical" representation used to store the
7321 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007322 TypeSourceInfo *WrittenTy
7323 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7324 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007325 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00007326 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007327 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007328 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007329
Douglas Gregor1e249f82009-02-25 22:18:32 +00007330 // C++ [temp.expl.spec]p9:
7331 // A template explicit specialization is in the scope of the
7332 // namespace in which the template was defined.
7333 //
7334 // We actually implement this paragraph where we set the semantic
7335 // context (in the creation of the ClassTemplateSpecializationDecl),
7336 // but we also maintain the lexical context where the actual
7337 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00007338 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00007339
Douglas Gregor67a65642009-02-17 23:15:12 +00007340 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00007341 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00007342 Specialization->startDefinition();
7343
Douglas Gregor2208a292009-09-26 20:57:03 +00007344 if (TUK == TUK_Friend) {
7345 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
7346 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00007347 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00007348 /*FIXME:*/KWLoc);
7349 Friend->setAccess(AS_public);
7350 CurContext->addDecl(Friend);
7351 } else {
7352 // Add the specialization into its lexical context, so that it can
7353 // be seen when iterating through the list of declarations in that
7354 // context. However, specializations are not found by name lookup.
7355 CurContext->addDecl(Specialization);
7356 }
John McCall48871652010-08-21 09:40:31 +00007357 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00007358}
Douglas Gregor333489b2009-03-27 23:10:48 +00007359
John McCall48871652010-08-21 09:40:31 +00007360Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00007361 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00007362 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007363 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00007364 ActOnDocumentableDecl(NewDecl);
7365 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00007366}
7367
John McCall4f7ced62010-02-11 01:33:53 +00007368/// \brief Strips various properties off an implicit instantiation
7369/// that has just been explicitly specialized.
7370static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00007371 D->dropAttr<DLLImportAttr>();
7372 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00007373
Nico Webere4974382014-12-19 23:52:45 +00007374 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00007375 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00007376}
7377
Nico Webera8f80b32012-01-09 19:52:25 +00007378/// \brief Compute the diagnostic location for an explicit instantiation
7379// declaration or definition.
7380static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007381 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00007382 // Explicit instantiations following a specialization have no effect and
7383 // hence no PointOfInstantiation. In that case, walk decl backwards
7384 // until a valid name loc is found.
7385 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007386 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
7387 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00007388 PrevDiagLoc = Prev->getLocation();
7389 }
7390 assert(PrevDiagLoc.isValid() &&
7391 "Explicit instantiation without point of instantiation?");
7392 return PrevDiagLoc;
7393}
7394
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007395/// \brief Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007396/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007397/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007398/// new specialization/instantiation will have any effect.
7399///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007400/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007401/// instantiation.
7402///
7403/// \param NewTSK the kind of the new explicit specialization or instantiation.
7404///
7405/// \param PrevDecl the previous declaration of the entity.
7406///
7407/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
7408///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007409/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007410/// declaration was instantiated (either implicitly or explicitly).
7411///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007412/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007413/// specialization or instantiation has no effect and should be ignored.
7414///
7415/// \returns true if there was an error that should prevent the introduction of
7416/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00007417bool
7418Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7419 TemplateSpecializationKind NewTSK,
7420 NamedDecl *PrevDecl,
7421 TemplateSpecializationKind PrevTSK,
7422 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007423 bool &HasNoEffect) {
7424 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007425
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007426 switch (NewTSK) {
7427 case TSK_Undeclared:
7428 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00007429 assert(
7430 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
7431 "previous declaration must be implicit!");
7432 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007433
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007434 case TSK_ExplicitSpecialization:
7435 switch (PrevTSK) {
7436 case TSK_Undeclared:
7437 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007438 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007439 // explicitly specialized or has merely been mentioned without any
7440 // instantiation.
7441 return false;
7442
7443 case TSK_ImplicitInstantiation:
7444 if (PrevPointOfInstantiation.isInvalid()) {
7445 // The declaration itself has not actually been instantiated, so it is
7446 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00007447 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007448 return false;
7449 }
7450 // Fall through
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007451
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007452 case TSK_ExplicitInstantiationDeclaration:
7453 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007454 assert((PrevTSK == TSK_ImplicitInstantiation ||
7455 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007456 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007457
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007458 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007459 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007460 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007461 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007462 // implicit instantiation to take place, in every translation unit in
7463 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007464 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007465 // Is there any previous explicit specialization declaration?
7466 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
7467 return false;
7468 }
7469
Douglas Gregor1d957a32009-10-27 18:42:08 +00007470 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007471 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007472 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007473 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007474
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007475 return true;
7476 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007477
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007478 case TSK_ExplicitInstantiationDeclaration:
7479 switch (PrevTSK) {
7480 case TSK_ExplicitInstantiationDeclaration:
7481 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00007482 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007483 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007484
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007485 case TSK_Undeclared:
7486 case TSK_ImplicitInstantiation:
7487 // We're explicitly instantiating something that may have already been
7488 // implicitly instantiated; that's fine.
7489 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007490
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007491 case TSK_ExplicitSpecialization:
7492 // C++0x [temp.explicit]p4:
7493 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007494 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007495 // specialization for that template, the explicit instantiation has no
7496 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007497 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007498 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007499
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007500 case TSK_ExplicitInstantiationDefinition:
7501 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007502 // If an entity is the subject of both an explicit instantiation
7503 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007504 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007505 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00007506 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00007507
7508 // Explicit instantiations following a specialization have no effect and
7509 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
7510 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00007511 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7512 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007513 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007514 return false;
7515 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007516
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007517 case TSK_ExplicitInstantiationDefinition:
7518 switch (PrevTSK) {
7519 case TSK_Undeclared:
7520 case TSK_ImplicitInstantiation:
7521 // We're explicitly instantiating something that may have already been
7522 // implicitly instantiated; that's fine.
7523 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007524
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007525 case TSK_ExplicitSpecialization:
7526 // C++ DR 259, C++0x [temp.explicit]p4:
7527 // For a given set of template parameters, if an explicit
7528 // instantiation of a template appears after a declaration of
7529 // an explicit specialization for that template, the explicit
7530 // instantiation has no effect.
Richard Smithe4caa482016-08-31 23:23:25 +00007531 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
Richard Smith0bf8a4922011-10-18 20:49:44 +00007532 << PrevDecl;
7533 Diag(PrevDecl->getLocation(),
7534 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007535 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007536 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007537
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007538 case TSK_ExplicitInstantiationDeclaration:
7539 // We're explicity instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007540 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00007541
7542 // C++0x [temp.explicit]p4:
7543 // For a given set of template parameters, if an explicit instantiation
7544 // of a template appears after a declaration of an explicit
7545 // specialization for that template, the explicit instantiation has no
7546 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007547 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00007548 // Is there any previous explicit specialization declaration?
7549 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7550 HasNoEffect = true;
7551 break;
7552 }
7553 }
7554
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007555 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007556
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007557 case TSK_ExplicitInstantiationDefinition:
7558 // C++0x [temp.spec]p5:
7559 // For a given template and a given set of template-arguments,
7560 // - an explicit instantiation definition shall appear at most once
7561 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00007562
7563 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
7564 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00007565 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00007566 : diag::err_explicit_instantiation_duplicate)
7567 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00007568 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00007569 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007570 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007571 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007572 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007573 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007574
David Blaikie83d382b2011-09-23 05:06:16 +00007575 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007576}
7577
John McCallb9c78482010-04-08 09:05:18 +00007578/// \brief Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00007579/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00007580///
James Dennettf14a6e52012-06-15 22:23:43 +00007581/// The only possible way to get a dependent function template specialization
7582/// is with a friend declaration, like so:
7583///
7584/// \code
7585/// template \<class T> void foo(T);
7586/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00007587/// friend void foo<>(T);
7588/// };
James Dennettf14a6e52012-06-15 22:23:43 +00007589/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00007590///
7591/// There really isn't any useful analysis we can do here, so we
7592/// just store the information.
7593bool
7594Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
7595 const TemplateArgumentListInfo &ExplicitTemplateArgs,
7596 LookupResult &Previous) {
7597 // Remove anything from Previous that isn't a function template in
7598 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00007599 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00007600 LookupResult::Filter F = Previous.makeFilter();
7601 while (F.hasNext()) {
7602 NamedDecl *D = F.next()->getUnderlyingDecl();
7603 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00007604 !FDLookupContext->InEnclosingNamespaceSetOf(
7605 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00007606 F.erase();
7607 }
7608 F.done();
7609
7610 // Should this be diagnosed here?
7611 if (Previous.empty()) return true;
7612
7613 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
7614 ExplicitTemplateArgs);
7615 return false;
7616}
7617
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007618/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007619/// specialization.
7620///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007621/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007622/// explicit function template specialization. On successful completion,
7623/// the function declaration \p FD will become a function template
7624/// specialization.
7625///
7626/// \param FD the function declaration, which will be updated to become a
7627/// function template specialization.
7628///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007629/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
7630/// if any. Note that this may be valid info even when 0 arguments are
7631/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
7632/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007633///
Francois Pichet3a44e432011-07-08 06:21:47 +00007634/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007635/// this function specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007636bool Sema::CheckFunctionTemplateSpecialization(
7637 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
7638 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007639 // The set of function template specializations that could match this
7640 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00007641 UnresolvedSet<8> Candidates;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007642 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
7643 /*ForTakingAddress=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007644
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007645 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
7646 ConvertedTemplateArgs;
7647
Sebastian Redl50c68252010-08-31 00:36:30 +00007648 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00007649 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7650 I != E; ++I) {
7651 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
7652 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007653 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007654 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00007655 if (!FDLookupContext->InEnclosingNamespaceSetOf(
7656 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007657 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007658
Richard Smith574f4f62013-01-14 05:37:29 +00007659 // When matching a constexpr member function template specialization
7660 // against the primary template, we don't yet know whether the
7661 // specialization has an implicit 'const' (because we don't know whether
7662 // it will be a static member function until we know which template it
7663 // specializes), so adjust it now assuming it specializes this template.
7664 QualType FT = FD->getType();
7665 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00007666 CXXMethodDecl *OldMD =
7667 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00007668 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00007669 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00007670 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7671 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00007672 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00007673 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00007674 }
7675 }
7676
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007677 TemplateArgumentListInfo Args;
7678 if (ExplicitTemplateArgs)
7679 Args = *ExplicitTemplateArgs;
7680
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007681 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007682 // A trailing template-argument can be left unspecified in the
7683 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007684 // provided it can be deduced from the function argument type.
7685 // Perform template argument deduction to determine whether we may be
7686 // specializing this template.
7687 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00007688 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00007689 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00007690 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
7691 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
Richard Smithc2bebe92016-05-11 20:37:46 +00007692 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
7693 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00007694 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007695 // that we can provide nifty diagnostics.
Richard Smithc2bebe92016-05-11 20:37:46 +00007696 FailedCandidates.addCandidate().set(
7697 I.getPair(), FunTmpl->getTemplatedDecl(),
7698 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007699 (void)TDK;
7700 continue;
7701 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007702
Artem Belevich64135c32016-12-08 19:38:13 +00007703 // Target attributes are part of the cuda function signature, so
7704 // the deduced template's cuda target must match that of the
7705 // specialization. Given that C++ template deduction does not
7706 // take target attributes into account, we reject candidates
7707 // here that have a different target.
Artem Belevich13e9b4d2016-12-07 19:27:16 +00007708 if (LangOpts.CUDA &&
Artem Belevich64135c32016-12-08 19:38:13 +00007709 IdentifyCUDATarget(Specialization,
7710 /* IgnoreImplicitHDAttributes = */ true) !=
7711 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttributes = */ true)) {
Artem Belevich13e9b4d2016-12-07 19:27:16 +00007712 FailedCandidates.addCandidate().set(
7713 I.getPair(), FunTmpl->getTemplatedDecl(),
7714 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
7715 continue;
7716 }
7717
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007718 // Record this candidate.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007719 if (ExplicitTemplateArgs)
7720 ConvertedTemplateArgs[Specialization] = std::move(Args);
John McCall58cc69d2010-01-27 01:50:18 +00007721 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007722 }
7723 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007724
Douglas Gregor5de279c2009-09-26 03:41:46 +00007725 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007726 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00007727 Candidates.begin(), Candidates.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00007728 FD->getLocation(),
7729 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
7730 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00007731 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00007732 PDiag(diag::note_function_template_spec_matched));
7733
John McCall58cc69d2010-01-27 01:50:18 +00007734 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007735 return true;
John McCall58cc69d2010-01-27 01:50:18 +00007736
7737 // Ignore access information; it doesn't figure into redeclaration checking.
7738 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00007739
Nathan Wilson83839122016-04-09 02:55:27 +00007740 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
7741 // an explicit specialization (14.8.3) [...] of a concept definition.
7742 if (Specialization->getPrimaryTemplate()->isConcept()) {
7743 Diag(FD->getLocation(), diag::err_concept_specialized)
7744 << 0 /*function*/ << 1 /*explicitly specialized*/;
7745 Diag(Specialization->getLocation(), diag::note_previous_declaration);
7746 return true;
7747 }
7748
Abramo Bagnarab9893d62011-03-04 17:20:30 +00007749 FunctionTemplateSpecializationInfo *SpecInfo
7750 = Specialization->getTemplateSpecializationInfo();
7751 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00007752
7753 // Note: do not overwrite location info if previous template
7754 // specialization kind was explicit.
7755 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00007756 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00007757 Specialization->setLocation(FD->getLocation());
Richard Smith5b8b3db2012-02-20 23:28:05 +00007758 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
7759 // function can differ from the template declaration with respect to
7760 // the constexpr specifier.
7761 Specialization->setConstexpr(FD->isConstexpr());
7762 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007763
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007764 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00007765 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00007766
7767 // If this is a friend declaration, then we're not really declaring
7768 // an explicit specialization.
7769 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007770
Douglas Gregor54888652009-10-07 00:13:32 +00007771 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00007772 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007773 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00007774 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007775 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007776 false))
Douglas Gregor54888652009-10-07 00:13:32 +00007777 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00007778
7779 // C++ [temp.expl.spec]p6:
7780 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007781 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007782 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007783 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007784 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007785 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00007786 if (!isFriend &&
7787 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00007788 TSK_ExplicitSpecialization,
7789 Specialization,
7790 SpecInfo->getTemplateSpecializationKind(),
7791 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007792 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007793 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00007794
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007795 // Mark the prior declaration as an explicit specialization, so that later
7796 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007797 if (!isFriend) {
Faisal Vali81a88be2016-06-14 03:23:15 +00007798 // Since explicit specializations do not inherit '=delete' from their
7799 // primary function template - check if the 'specialization' that was
7800 // implicitly generated (during template argument deduction for partial
7801 // ordering) from the most specialized of all the function templates that
7802 // 'FD' could have been specializing, has a 'deleted' definition. If so,
7803 // first check that it was implicitly generated during template argument
7804 // deduction by making sure it wasn't referenced, and then reset the deleted
7805 // flag to not-deleted, so that we can inherit that information from 'FD'.
7806 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
7807 !Specialization->getCanonicalDecl()->isReferenced()) {
7808 assert(
7809 Specialization->getCanonicalDecl() == Specialization &&
7810 "This must be the only existing declaration of this specialization");
7811 Specialization->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007812 }
John McCall816d75b2010-03-24 07:46:06 +00007813 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007814 MarkUnusedFileScopedDecl(Specialization);
7815 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007816
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007817 // Turn the given function declaration into a function template
7818 // specialization, with the template arguments from the previous
7819 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007820 // Take copies of (semantic and syntactic) template argument lists.
7821 const TemplateArgumentList* TemplArgs = new (Context)
7822 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007823 FD->setFunctionTemplateSpecialization(
7824 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
7825 SpecInfo->getTemplateSpecializationKind(),
7826 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00007827
Artem Belevich64135c32016-12-08 19:38:13 +00007828 // A function template specialization inherits the target attributes
7829 // of its template. (We require the attributes explicitly in the
7830 // code to match, but a template may have implicit attributes by
7831 // virtue e.g. of being constexpr, and it passes these implicit
7832 // attributes on to its specializations.)
7833 if (LangOpts.CUDA)
7834 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
7835
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007836 // The "previous declaration" for this function template specialization is
7837 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00007838 Previous.clear();
7839 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007840 return false;
7841}
7842
Douglas Gregor86d142a2009-10-08 07:24:58 +00007843/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007844/// specialization.
7845///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007846/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007847/// explicit member function specialization. On successful completion,
7848/// the function declaration \p FD will become a member function
7849/// specialization.
7850///
Douglas Gregor86d142a2009-10-08 07:24:58 +00007851/// \param Member the member declaration, which will be updated to become a
7852/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007853///
John McCall1f82f242009-11-18 22:49:29 +00007854/// \param Previous the set of declarations, one of which may be specialized
7855/// by this function specialization; the set will be modified to contain the
7856/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007857bool
John McCall1f82f242009-11-18 22:49:29 +00007858Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007859 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00007860
Douglas Gregor86d142a2009-10-08 07:24:58 +00007861 // Try to find the member we are instantiating.
Richard Smith22e7cc62016-05-24 00:01:49 +00007862 NamedDecl *FoundInstantiation = nullptr;
Craig Topperc3ec1492014-05-26 06:22:03 +00007863 NamedDecl *Instantiation = nullptr;
7864 NamedDecl *InstantiatedFrom = nullptr;
7865 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00007866
John McCall1f82f242009-11-18 22:49:29 +00007867 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007868 // Nowhere to look anyway.
7869 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007870 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7871 I != E; ++I) {
7872 NamedDecl *D = (*I)->getUnderlyingDecl();
7873 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00007874 QualType Adjusted = Function->getType();
7875 if (!hasExplicitCallingConv(Adjusted))
7876 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
7877 if (Context.hasSameType(Adjusted, Method->getType())) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007878 FoundInstantiation = *I;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007879 Instantiation = Method;
7880 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007881 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007882 break;
7883 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007884 }
7885 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00007886 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007887 VarDecl *PrevVar;
7888 if (Previous.isSingleResult() &&
7889 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00007890 if (PrevVar->isStaticDataMember()) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007891 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00007892 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007893 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007894 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007895 }
7896 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007897 CXXRecordDecl *PrevRecord;
7898 if (Previous.isSingleResult() &&
7899 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007900 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00007901 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007902 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007903 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007904 }
Richard Smith7d137e32012-03-23 03:33:32 +00007905 } else if (isa<EnumDecl>(Member)) {
7906 EnumDecl *PrevEnum;
7907 if (Previous.isSingleResult() &&
7908 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007909 FoundInstantiation = Previous.getRepresentativeDecl();
Richard Smith7d137e32012-03-23 03:33:32 +00007910 Instantiation = PrevEnum;
7911 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
7912 MSInfo = PrevEnum->getMemberSpecializationInfo();
7913 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007914 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007915
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007916 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007917 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007918 // specializations are always out-of-line, the caller will complain about
7919 // this mismatch later.
7920 return false;
7921 }
John McCalle820e5e2010-04-13 20:37:33 +00007922
7923 // If this is a friend, just bail out here before we start turning
7924 // things into explicit specializations.
7925 if (Member->getFriendObjectKind() != Decl::FOK_None) {
7926 // Preserve instantiation information.
7927 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
7928 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
7929 cast<CXXMethodDecl>(InstantiatedFrom),
7930 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
7931 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
7932 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7933 cast<CXXRecordDecl>(InstantiatedFrom),
7934 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
7935 }
7936
7937 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00007938 Previous.addDecl(FoundInstantiation);
John McCalle820e5e2010-04-13 20:37:33 +00007939 return false;
7940 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007941
Douglas Gregor86d142a2009-10-08 07:24:58 +00007942 // Make sure that this is a specialization of a member.
7943 if (!InstantiatedFrom) {
7944 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
7945 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007946 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
7947 return true;
7948 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007949
Douglas Gregor06db9f52009-10-12 20:18:28 +00007950 // C++ [temp.expl.spec]p6:
7951 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00007952 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007953 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007954 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007955 // use occurs; no diagnostic is required.
7956 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00007957
Abramo Bagnara8075c852010-06-12 07:44:57 +00007958 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00007959 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
7960 TSK_ExplicitSpecialization,
7961 Instantiation,
7962 MSInfo->getTemplateSpecializationKind(),
7963 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007964 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007965 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007966
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007967 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007968 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00007969 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007970 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007971 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007972 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00007973
Douglas Gregor86d142a2009-10-08 07:24:58 +00007974 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007975 // the original declaration to note that it is an explicit specialization
7976 // (if it was previously an implicit instantiation). This latter step
7977 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00007978 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007979 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
7980 if (InstantiationFunction->getTemplateSpecializationKind() ==
7981 TSK_ImplicitInstantiation) {
7982 InstantiationFunction->setTemplateSpecializationKind(
7983 TSK_ExplicitSpecialization);
7984 InstantiationFunction->setLocation(Member->getLocation());
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007985 // Explicit specializations of member functions of class templates do not
7986 // inherit '=delete' from the member function they are specializing.
7987 if (InstantiationFunction->isDeleted()) {
7988 assert(InstantiationFunction->getCanonicalDecl() ==
7989 InstantiationFunction);
Richard Smith5f274382016-09-28 23:55:27 +00007990 InstantiationFunction->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007991 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007992 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007993
Douglas Gregor86d142a2009-10-08 07:24:58 +00007994 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
7995 cast<CXXMethodDecl>(InstantiatedFrom),
7996 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007997 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007998 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007999 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
8000 if (InstantiationVar->getTemplateSpecializationKind() ==
8001 TSK_ImplicitInstantiation) {
8002 InstantiationVar->setTemplateSpecializationKind(
8003 TSK_ExplicitSpecialization);
8004 InstantiationVar->setLocation(Member->getLocation());
8005 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008006
Larisse Voufo39a1e502013-08-06 01:03:05 +00008007 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
8008 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00008009 MarkUnusedFileScopedDecl(InstantiationVar);
Richard Smith7d137e32012-03-23 03:33:32 +00008010 } else if (isa<CXXRecordDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008011 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
8012 if (InstantiationClass->getTemplateSpecializationKind() ==
8013 TSK_ImplicitInstantiation) {
8014 InstantiationClass->setTemplateSpecializationKind(
8015 TSK_ExplicitSpecialization);
8016 InstantiationClass->setLocation(Member->getLocation());
8017 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008018
Douglas Gregor86d142a2009-10-08 07:24:58 +00008019 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008020 cast<CXXRecordDecl>(InstantiatedFrom),
8021 TSK_ExplicitSpecialization);
Richard Smith7d137e32012-03-23 03:33:32 +00008022 } else {
8023 assert(isa<EnumDecl>(Member) && "Only member enums remain");
8024 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
8025 if (InstantiationEnum->getTemplateSpecializationKind() ==
8026 TSK_ImplicitInstantiation) {
8027 InstantiationEnum->setTemplateSpecializationKind(
8028 TSK_ExplicitSpecialization);
8029 InstantiationEnum->setLocation(Member->getLocation());
8030 }
8031
8032 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
8033 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00008034 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008035
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008036 // Save the caller the trouble of having to figure out which declaration
8037 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00008038 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00008039 Previous.addDecl(FoundInstantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008040 return false;
8041}
8042
Douglas Gregore47f5a72009-10-14 23:41:34 +00008043/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008044///
8045/// \returns true if a serious error occurs, false otherwise.
8046static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00008047 SourceLocation InstLoc,
8048 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00008049 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
8050 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008051
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008052 if (CurContext->isRecord()) {
8053 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
8054 << D;
8055 return true;
8056 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008057
Richard Smith050d2612011-10-18 02:28:33 +00008058 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008059 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00008060 // template. If the name declared in the explicit instantiation is an
8061 // unqualified name, the explicit instantiation shall appear in the
8062 // namespace where its template is declared or, if that namespace is inline
8063 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008064 //
8065 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00008066 if (WasQualifiedName) {
8067 if (CurContext->Encloses(OrigContext))
8068 return false;
8069 } else {
8070 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
8071 return false;
8072 }
8073
8074 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
8075 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008076 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008077 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008078 diag::err_explicit_instantiation_out_of_scope :
8079 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008080 << D << NS;
8081 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008082 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008083 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008084 diag::err_explicit_instantiation_unqualified_wrong_namespace :
8085 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
8086 << D << NS;
8087 } else
8088 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008089 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008090 diag::err_explicit_instantiation_must_be_global :
8091 diag::warn_explicit_instantiation_must_be_global_0x)
8092 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00008093 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008094 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00008095}
8096
8097/// \brief Determine whether the given scope specifier has a template-id in it.
8098static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
8099 if (!SS.isSet())
8100 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008101
Richard Smith050d2612011-10-18 02:28:33 +00008102 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008103 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008104 // or a static data member of a class template specialization, the name of
8105 // the class template specialization in the qualified-id for the member
8106 // name shall be a simple-template-id.
8107 //
8108 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00008109 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
8110 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00008111 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00008112 if (isa<TemplateSpecializationType>(T))
8113 return true;
8114
8115 return false;
8116}
8117
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008118/// Make a dllexport or dllimport attr on a class template specialization take
8119/// effect.
8120static void dllExportImportClassTemplateSpecialization(
8121 Sema &S, ClassTemplateSpecializationDecl *Def) {
8122 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
8123 assert(A && "dllExportImportClassTemplateSpecialization called "
8124 "on Def without dllexport or dllimport");
8125
8126 // We reject explicit instantiations in class scope, so there should
8127 // never be any delayed exported classes to worry about.
8128 assert(S.DelayedDllExportClasses.empty() &&
8129 "delayed exports present at explicit instantiation");
8130 S.checkClassLevelDLLAttribute(Def);
8131
8132 // Propagate attribute to base class templates.
8133 for (auto &B : Def->bases()) {
8134 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
8135 B.getType()->getAsCXXRecordDecl()))
8136 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
8137 }
8138
8139 S.referenceDLLExportedClassMethods();
8140}
8141
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008142// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00008143DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00008144Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00008145 SourceLocation ExternLoc,
8146 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00008147 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00008148 SourceLocation KWLoc,
8149 const CXXScopeSpec &SS,
8150 TemplateTy TemplateD,
8151 SourceLocation TemplateNameLoc,
8152 SourceLocation LAngleLoc,
8153 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00008154 SourceLocation RAngleLoc,
8155 AttributeList *Attr) {
8156 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00008157 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00008158 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00008159 // Check that the specialization uses the same tag kind as the
8160 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00008161 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8162 assert(Kind != TTK_Enum &&
8163 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00008164
Richard Trieu265c3442016-04-05 21:13:54 +00008165 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
8166
8167 if (!ClassTemplate) {
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00008168 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
8169 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
Richard Trieu265c3442016-04-05 21:13:54 +00008170 Diag(TD->getLocation(), diag::note_previous_use);
Richard Smith392497b2013-06-22 22:03:31 +00008171 return true;
8172 }
8173
Douglas Gregord9034f02009-05-14 16:41:31 +00008174 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00008175 Kind, /*isDefinition*/false, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00008176 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00008177 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00008178 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00008179 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00008180 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00008181 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00008182 diag::note_previous_use);
8183 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8184 }
8185
Douglas Gregore47f5a72009-10-14 23:41:34 +00008186 // C++0x [temp.explicit]p2:
8187 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008188 // definition and an explicit instantiation declaration. An explicit
8189 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00008190 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
8191 ? TSK_ExplicitInstantiationDefinition
8192 : TSK_ExplicitInstantiationDeclaration;
8193
8194 if (TSK == TSK_ExplicitInstantiationDeclaration) {
8195 // Check for dllexport class template instantiation declarations.
8196 for (AttributeList *A = Attr; A; A = A->getNext()) {
8197 if (A->getKind() == AttributeList::AT_DLLExport) {
8198 Diag(ExternLoc,
8199 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8200 Diag(A->getLoc(), diag::note_attribute);
8201 break;
8202 }
8203 }
8204
8205 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
8206 Diag(ExternLoc,
8207 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8208 Diag(A->getLocation(), diag::note_attribute);
8209 }
8210 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008211
Hans Wennborga86a83b2016-05-26 19:42:56 +00008212 // In MSVC mode, dllimported explicit instantiation definitions are treated as
8213 // instantiation declarations for most purposes.
8214 bool DLLImportExplicitInstantiationDef = false;
8215 if (TSK == TSK_ExplicitInstantiationDefinition &&
8216 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
8217 // Check for dllimport class template instantiation definitions.
8218 bool DLLImport =
8219 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
8220 for (AttributeList *A = Attr; A; A = A->getNext()) {
8221 if (A->getKind() == AttributeList::AT_DLLImport)
8222 DLLImport = true;
8223 if (A->getKind() == AttributeList::AT_DLLExport) {
8224 // dllexport trumps dllimport here.
8225 DLLImport = false;
8226 break;
8227 }
8228 }
8229 if (DLLImport) {
8230 TSK = TSK_ExplicitInstantiationDeclaration;
8231 DLLImportExplicitInstantiationDef = true;
8232 }
8233 }
8234
Douglas Gregora1f49972009-05-13 00:25:59 +00008235 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00008236 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00008237 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00008238
8239 // Check that the template argument list is well-formed for this
8240 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008241 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00008242 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
8243 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00008244 return true;
8245
Douglas Gregora1f49972009-05-13 00:25:59 +00008246 // Find the class template specialization declaration that
8247 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00008248 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00008249 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00008250 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00008251
Abramo Bagnara8075c852010-06-12 07:44:57 +00008252 TemplateSpecializationKind PrevDecl_TSK
8253 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
8254
Douglas Gregor54888652009-10-07 00:13:32 +00008255 // C++0x [temp.explicit]p2:
8256 // [...] An explicit instantiation shall appear in an enclosing
8257 // namespace of its template. [...]
8258 //
8259 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008260 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
8261 SS.isSet()))
8262 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008263
Craig Topperc3ec1492014-05-26 06:22:03 +00008264 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00008265
Abramo Bagnara8075c852010-06-12 07:44:57 +00008266 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00008267 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00008268 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00008269 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00008270 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008271 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00008272 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00008273
Abramo Bagnara8075c852010-06-12 07:44:57 +00008274 // Even though HasNoEffect == true means that this explicit instantiation
8275 // has no effect on semantics, we go on to put its syntax in the AST.
8276
8277 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
8278 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008279 // Since the only prior class template specialization with these
8280 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00008281 // declaration node as our own, updating the source location
8282 // for the template name to reflect our new declaration.
8283 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008284 Specialization = PrevDecl;
8285 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00008286 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008287 }
Hans Wennborga86a83b2016-05-26 19:42:56 +00008288
8289 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
8290 DLLImportExplicitInstantiationDef) {
8291 // The new specialization might add a dllimport attribute.
8292 HasNoEffect = false;
8293 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00008294 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00008295
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008296 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00008297 // Create a new class template specialization declaration node for
8298 // this explicit specialization.
8299 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00008300 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00008301 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00008302 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00008303 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00008304 Converted,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008305 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00008306 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00008307
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00008308 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00008309 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00008310 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008311 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008312 }
8313
8314 // Build the fully-sugared type for this explicit instantiation as
8315 // the user wrote in the explicit instantiation itself. This means
8316 // that we'll pretty-print the type retrieved from the
8317 // specialization's declaration the way that the user actually wrote
8318 // the explicit instantiation, rather than formatting the name based
8319 // on the "canonical" representation used to store the template
8320 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00008321 TypeSourceInfo *WrittenTy
8322 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
8323 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00008324 Context.getTypeDeclType(Specialization));
8325 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00008326
Abramo Bagnara8075c852010-06-12 07:44:57 +00008327 // Set source locations for keywords.
8328 Specialization->setExternLoc(ExternLoc);
8329 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00008330 Specialization->setBraceRange(SourceRange());
Abramo Bagnara8075c852010-06-12 07:44:57 +00008331
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00008332 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
Rafael Espindola0b062072012-01-03 06:04:21 +00008333 if (Attr)
8334 ProcessDeclAttributeList(S, Specialization, Attr);
8335
Abramo Bagnara8075c852010-06-12 07:44:57 +00008336 // Add the explicit instantiation into its lexical context. However,
8337 // since explicit instantiations are never found by name lookup, we
8338 // just put it into the declaration context directly.
8339 Specialization->setLexicalDeclContext(CurContext);
8340 CurContext->addDecl(Specialization);
8341
8342 // Syntax is now OK, so return if it has no other effect on semantics.
8343 if (HasNoEffect) {
8344 // Set the template specialization kind.
8345 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00008346 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00008347 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008348
8349 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00008350 // A definition of a class template or class member template
8351 // shall be in scope at the point of the explicit instantiation of
8352 // the class template or class member template.
8353 //
8354 // This check comes when we actually try to perform the
8355 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00008356 ClassTemplateSpecializationDecl *Def
8357 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008358 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00008359 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00008360 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008361 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00008362 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008363 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
8364 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00008365
Douglas Gregor1d957a32009-10-27 18:42:08 +00008366 // Instantiate the members of this class template specialization.
8367 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008368 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00008369 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008370 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008371 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
8372 // TSK_ExplicitInstantiationDefinition
8373 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborga86a83b2016-05-26 19:42:56 +00008374 (TSK == TSK_ExplicitInstantiationDefinition ||
8375 DLLImportExplicitInstantiationDef)) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00008376 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008377 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00008378
Hans Wennborgc0875502015-06-09 00:39:05 +00008379 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
Shoaib Meenaiab3f96c2016-11-09 23:52:20 +00008380 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8381 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
Hans Wennborgc0875502015-06-09 00:39:05 +00008382 // In the MS ABI, an explicit instantiation definition can add a dll
8383 // attribute to a template with a previous instantiation declaration.
8384 // MinGW doesn't allow this.
Hans Wennborg17f9b442015-05-27 00:06:45 +00008385 auto *A = cast<InheritableAttr>(
8386 getDLLAttr(Specialization)->clone(getASTContext()));
8387 A->setInherited(true);
8388 Def->addAttr(A);
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008389 dllExportImportClassTemplateSpecialization(*this, Def);
Hans Wennborg17f9b442015-05-27 00:06:45 +00008390 }
8391 }
8392
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008393 // Fix a TSK_ImplicitInstantiation followed by a
8394 // TSK_ExplicitInstantiationDefinition
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00008395 bool NewlyDLLExported =
8396 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
8397 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008398 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8399 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
8400 // In the MS ABI, an explicit instantiation definition can add a dll
8401 // attribute to a template with a previous implicit instantiation.
8402 // MinGW doesn't allow this. We limit clang to only adding dllexport, to
8403 // avoid potentially strange codegen behavior. For example, if we extend
8404 // this conditional to dllimport, and we have a source file calling a
8405 // method on an implicitly instantiated template class instance and then
8406 // declaring a dllimport explicit instantiation definition for the same
8407 // template class, the codegen for the method call will not respect the
8408 // dllimport, while it will with cl. The Def will already have the DLL
8409 // attribute, since the Def and Specialization will be the same in the
8410 // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
8411 // attribute to the Specialization; we just need to make it take effect.
8412 assert(Def == Specialization &&
8413 "Def and Specialization should match for implicit instantiation");
8414 dllExportImportClassTemplateSpecialization(*this, Def);
8415 }
8416
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00008417 // Set the template specialization kind. Make sure it is set before
8418 // instantiating the members which will trigger ASTConsumer callbacks.
8419 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregor12e49d32009-10-15 22:53:21 +00008420 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00008421 } else {
8422
8423 // Set the template specialization kind.
8424 Specialization->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00008425 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008426
John McCall48871652010-08-21 09:40:31 +00008427 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00008428}
8429
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008430// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00008431DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00008432Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00008433 SourceLocation ExternLoc,
8434 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00008435 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008436 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00008437 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008438 IdentifierInfo *Name,
8439 SourceLocation NameLoc,
8440 AttributeList *Attr) {
8441
Douglas Gregord6ab8742009-05-28 23:31:59 +00008442 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00008443 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00008444 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00008445 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00008446 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00008447 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00008448 SourceLocation(), false, TypeResult(),
8449 /*IsTypeSpecifier*/false);
John McCall7f41d982009-09-11 04:59:25 +00008450 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
8451
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008452 if (!TagD)
8453 return true;
8454
John McCall48871652010-08-21 09:40:31 +00008455 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00008456 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008457
Douglas Gregorb8006faf2009-05-27 17:30:49 +00008458 if (Tag->isInvalidDecl())
8459 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008460
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008461 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
8462 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
8463 if (!Pattern) {
8464 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
8465 << Context.getTypeDeclType(Record);
8466 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
8467 return true;
8468 }
8469
Douglas Gregore47f5a72009-10-14 23:41:34 +00008470 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008471 // If the explicit instantiation is for a class or member class, the
8472 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00008473 // simple-template-id.
8474 //
8475 // C++98 has the same restriction, just worded differently.
8476 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00008477 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008478 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008479
Douglas Gregore47f5a72009-10-14 23:41:34 +00008480 // C++0x [temp.explicit]p2:
8481 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008482 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00008483 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00008484 TemplateSpecializationKind TSK
8485 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8486 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008487
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008488 // C++0x [temp.explicit]p2:
8489 // [...] An explicit instantiation shall appear in an enclosing
8490 // namespace of its template. [...]
8491 //
8492 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008493 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008494
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008495 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008496 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00008497 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008498 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00008499 PrevDecl = Record;
8500 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008501 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00008502 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008503 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008504 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008505 PrevDecl,
8506 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008507 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008508 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008509 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00008510 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008511 return TagD;
8512 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008513
Douglas Gregor12e49d32009-10-15 22:53:21 +00008514 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008515 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00008516 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00008517 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008518 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00008519 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008520 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008521 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00008522 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00008523 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
8524 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00008525 Diag(Pattern->getLocation(), diag::note_forward_declaration)
8526 << Pattern;
8527 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008528 } else {
8529 if (InstantiateClass(NameLoc, Record, Def,
8530 getTemplateInstantiationArgs(Record),
8531 TSK))
8532 return true;
8533
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008534 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00008535 if (!RecordDef)
8536 return true;
8537 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008538 }
8539
Douglas Gregor1d957a32009-10-27 18:42:08 +00008540 // Instantiate all of the members of the class.
8541 InstantiateClassMembers(NameLoc, RecordDef,
8542 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008543
Douglas Gregor88d292c2010-05-13 16:44:06 +00008544 if (TSK == TSK_ExplicitInstantiationDefinition)
8545 MarkVTableUsed(NameLoc, RecordDef, true);
8546
Mike Stump87c57ac2009-05-16 07:39:55 +00008547 // FIXME: We don't have any representation for explicit instantiations of
8548 // member classes. Such a representation is not needed for compilation, but it
8549 // should be available for clients that want to see all of the declarations in
8550 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008551 return TagD;
8552}
8553
John McCallfaf5fb42010-08-26 23:41:50 +00008554DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
8555 SourceLocation ExternLoc,
8556 SourceLocation TemplateLoc,
8557 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00008558 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008559 // TODO: check if/when DNInfo should replace Name.
8560 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8561 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00008562 if (!Name) {
8563 if (!D.isInvalidType())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008564 Diag(D.getDeclSpec().getLocStart(),
Douglas Gregor450f00842009-09-25 18:43:00 +00008565 diag::err_explicit_instantiation_requires_name)
8566 << D.getDeclSpec().getSourceRange()
8567 << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008568
Douglas Gregor450f00842009-09-25 18:43:00 +00008569 return true;
8570 }
8571
8572 // The scope passed in may not be a decl scope. Zip up the scope tree until
8573 // we find one that is.
8574 while ((S->getFlags() & Scope::DeclScope) == 0 ||
8575 (S->getFlags() & Scope::TemplateParamScope) != 0)
8576 S = S->getParent();
8577
8578 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00008579 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
8580 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00008581 if (R.isNull())
8582 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008583
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008584 // C++ [dcl.stc]p1:
Simon Pilgrim6905d222016-12-30 22:55:33 +00008585 // A storage-class-specifier shall not be specified in [...] an explicit
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008586 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00008587 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00008588 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
8589 << Name;
8590 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008591 } else if (D.getDeclSpec().getStorageClassSpec()
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008592 != DeclSpec::SCS_unspecified) {
8593 // Complain about then remove the storage class specifier.
8594 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
8595 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Simon Pilgrim6905d222016-12-30 22:55:33 +00008596
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008597 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00008598 }
8599
Douglas Gregor3c74d412009-10-14 20:14:33 +00008600 // C++0x [temp.explicit]p1:
8601 // [...] An explicit instantiation of a function template shall not use the
8602 // inline or constexpr specifiers.
8603 // Presumably, this also applies to member functions of class templates as
8604 // well.
Richard Smith83c19292011-10-18 03:44:03 +00008605 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008606 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008607 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00008608 diag::err_explicit_instantiation_inline :
8609 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00008610 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00008611 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00008612 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
8613 // not already specified.
8614 Diag(D.getDeclSpec().getConstexprSpecLoc(),
8615 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008616
Nathan Wilsonde498452016-02-08 05:34:00 +00008617 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8618 // applied only to the definition of a function template or variable template,
8619 // declared in namespace scope.
8620 if (D.getDeclSpec().isConceptSpecified()) {
8621 Diag(D.getDeclSpec().getConceptSpecLoc(),
8622 diag::err_concept_specified_specialization) << 0;
8623 return true;
8624 }
8625
Richard Smith19a311a2017-02-09 22:47:51 +00008626 // A deduction guide is not on the list of entities that can be explicitly
8627 // instantiated.
8628 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8629 Diag(D.getDeclSpec().getLocStart(), diag::err_deduction_guide_specialized)
8630 << /*explicit instantiation*/ 0;
8631 return true;
8632 }
8633
Douglas Gregore47f5a72009-10-14 23:41:34 +00008634 // C++0x [temp.explicit]p2:
8635 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008636 // definition and an explicit instantiation declaration. An explicit
8637 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00008638 TemplateSpecializationKind TSK
8639 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8640 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008641
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008642 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00008643 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00008644
8645 if (!R->isFunctionType()) {
8646 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008647 // A [...] static data member of a class template can be explicitly
8648 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00008649 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00008650 // C++1y [temp.explicit]p1:
8651 // A [...] variable [...] template specialization can be explicitly
8652 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00008653 if (Previous.isAmbiguous())
8654 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008655
John McCall67c00872009-12-02 08:25:40 +00008656 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00008657 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008658
Larisse Voufo39a1e502013-08-06 01:03:05 +00008659 if (!PrevTemplate) {
8660 if (!Prev || !Prev->isStaticDataMember()) {
8661 // We expect to see a data data member here.
8662 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
8663 << Name;
8664 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
8665 P != PEnd; ++P)
8666 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
8667 return true;
8668 }
8669
8670 if (!Prev->getInstantiatedFromStaticDataMember()) {
8671 // FIXME: Check for explicit specialization?
8672 Diag(D.getIdentifierLoc(),
8673 diag::err_explicit_instantiation_data_member_not_instantiated)
8674 << Prev;
8675 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
8676 // FIXME: Can we provide a note showing where this was declared?
8677 return true;
8678 }
8679 } else {
8680 // Explicitly instantiate a variable template.
8681
8682 // C++1y [dcl.spec.auto]p6:
8683 // ... A program that uses auto or decltype(auto) in a context not
8684 // explicitly allowed in this section is ill-formed.
8685 //
8686 // This includes auto-typed variable template instantiations.
8687 if (R->isUndeducedType()) {
8688 Diag(T->getTypeLoc().getLocStart(),
8689 diag::err_auto_not_allowed_var_inst);
8690 return true;
8691 }
8692
Richard Smithef985ac2013-09-18 02:10:12 +00008693 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
8694 // C++1y [temp.explicit]p3:
8695 // If the explicit instantiation is for a variable, the unqualified-id
8696 // in the declaration shall be a template-id.
8697 Diag(D.getIdentifierLoc(),
8698 diag::err_explicit_instantiation_without_template_id)
8699 << PrevTemplate;
8700 Diag(PrevTemplate->getLocation(),
8701 diag::note_explicit_instantiation_here);
8702 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00008703 }
8704
Nathan Wilson83839122016-04-09 02:55:27 +00008705 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
8706 // explicit instantiation (14.8.2) [...] of a concept definition.
8707 if (PrevTemplate->isConcept()) {
8708 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
8709 << 1 /*variable*/ << 0 /*explicitly instantiated*/;
8710 Diag(PrevTemplate->getLocation(), diag::note_previous_declaration);
8711 return true;
8712 }
8713
Richard Smithef985ac2013-09-18 02:10:12 +00008714 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00008715 TemplateArgumentListInfo TemplateArgs =
8716 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00008717
Larisse Voufo39a1e502013-08-06 01:03:05 +00008718 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
8719 D.getIdentifierLoc(), TemplateArgs);
8720 if (Res.isInvalid())
8721 return true;
8722
8723 // Ignore access control bits, we don't need them for redeclaration
8724 // checking.
8725 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00008726 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008727
Douglas Gregore47f5a72009-10-14 23:41:34 +00008728 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008729 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008730 // or a static data member of a class template specialization, the name of
8731 // the class template specialization in the qualified-id for the member
8732 // name shall be a simple-template-id.
8733 //
8734 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00008735 //
Richard Smith5977d872013-09-18 21:55:14 +00008736 // This does not apply to variable template specializations, where the
8737 // template-id is in the unqualified-id instead.
8738 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008739 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00008740 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008741 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008742
Douglas Gregore47f5a72009-10-14 23:41:34 +00008743 // Check the scope of this explicit instantiation.
8744 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008745
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008746 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00008747 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
8748 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00008749 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008750 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00008751 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008752 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008753
Larisse Voufo39a1e502013-08-06 01:03:05 +00008754 if (!HasNoEffect) {
8755 // Instantiate static data member or variable template.
8756
8757 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
8758 if (PrevTemplate) {
8759 // Merge attributes.
8760 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
8761 ProcessDeclAttributeList(S, Prev, Attr);
8762 }
8763 if (TSK == TSK_ExplicitInstantiationDefinition)
8764 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
8765 }
8766
8767 // Check the new variable specialization against the parsed input.
8768 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
8769 Diag(T->getTypeLoc().getLocStart(),
8770 diag::err_invalid_var_template_spec_type)
8771 << 0 << PrevTemplate << R << Prev->getType();
8772 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
8773 << 2 << PrevTemplate->getDeclName();
8774 return true;
8775 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008776
Douglas Gregor450f00842009-09-25 18:43:00 +00008777 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00008778 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008779 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008780
8781 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00008782 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00008783 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00008784 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00008785 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00008786 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00008787 HasExplicitTemplateArgs = true;
8788 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008789
Douglas Gregor450f00842009-09-25 18:43:00 +00008790 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008791 // A [...] function [...] can be explicitly instantiated from its template.
8792 // A member function [...] of a class template can be explicitly
8793 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00008794 // template.
John McCall58cc69d2010-01-27 01:50:18 +00008795 UnresolvedSet<8> Matches;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008796 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
Larisse Voufo98b20f12013-07-19 23:00:19 +00008797 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00008798 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
8799 P != PEnd; ++P) {
8800 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00008801 if (!HasExplicitTemplateArgs) {
8802 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Richard Smithbaa47832016-12-01 02:11:49 +00008803 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
8804 /*AdjustExceptionSpec*/true);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00008805 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
Douglas Gregord90fd522009-09-25 21:45:23 +00008806 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00008807
John McCall58cc69d2010-01-27 01:50:18 +00008808 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00008809 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
8810 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00008811 }
Douglas Gregor450f00842009-09-25 18:43:00 +00008812 }
8813 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008814
Douglas Gregor450f00842009-09-25 18:43:00 +00008815 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
8816 if (!FunTmpl)
8817 continue;
8818
Larisse Voufo98b20f12013-07-19 23:00:19 +00008819 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00008820 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008821 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008822 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00008823 (HasExplicitTemplateArgs ? &TemplateArgs
8824 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00008825 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008826 // Keep track of almost-matches.
8827 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +00008828 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +00008829 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00008830 (void)TDK;
8831 continue;
8832 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008833
Artem Belevich64135c32016-12-08 19:38:13 +00008834 // Target attributes are part of the cuda function signature, so
8835 // the cuda target of the instantiated function must match that of its
8836 // template. Given that C++ template deduction does not take
8837 // target attributes into account, we reject candidates here that
8838 // have a different target.
8839 if (LangOpts.CUDA &&
8840 IdentifyCUDATarget(Specialization,
8841 /* IgnoreImplicitHDAttributes = */ true) !=
8842 IdentifyCUDATarget(Attr)) {
8843 FailedCandidates.addCandidate().set(
8844 P.getPair(), FunTmpl->getTemplatedDecl(),
8845 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
8846 continue;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008847 }
8848
John McCall58cc69d2010-01-27 01:50:18 +00008849 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00008850 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008851
Douglas Gregor450f00842009-09-25 18:43:00 +00008852 // Find the most specialized function template specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008853 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00008854 Matches.begin(), Matches.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00008855 D.getIdentifierLoc(),
8856 PDiag(diag::err_explicit_instantiation_not_known) << Name,
8857 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
8858 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00008859
John McCall58cc69d2010-01-27 01:50:18 +00008860 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00008861 return true;
John McCall58cc69d2010-01-27 01:50:18 +00008862
8863 // Ignore access control bits, we don't need them for redeclaration checking.
8864 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008865
Alexey Bataev73983912014-11-06 10:10:50 +00008866 // C++11 [except.spec]p4
8867 // In an explicit instantiation an exception-specification may be specified,
8868 // but is not required.
8869 // If an exception-specification is specified in an explicit instantiation
8870 // directive, it shall be compatible with the exception-specifications of
8871 // other declarations of that function.
8872 if (auto *FPT = R->getAs<FunctionProtoType>())
8873 if (FPT->hasExceptionSpec()) {
8874 unsigned DiagID =
8875 diag::err_mismatched_exception_spec_explicit_instantiation;
8876 if (getLangOpts().MicrosoftExt)
8877 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
8878 bool Result = CheckEquivalentExceptionSpec(
8879 PDiag(DiagID) << Specialization->getType(),
8880 PDiag(diag::note_explicit_instantiation_here),
8881 Specialization->getType()->getAs<FunctionProtoType>(),
8882 Specialization->getLocation(), FPT, D.getLocStart());
8883 // In Microsoft mode, mismatching exception specifications just cause a
8884 // warning.
8885 if (!getLangOpts().MicrosoftExt && Result)
8886 return true;
8887 }
8888
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008889 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008890 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00008891 diag::err_explicit_instantiation_member_function_not_instantiated)
8892 << Specialization
8893 << (Specialization->getTemplateSpecializationKind() ==
8894 TSK_ExplicitSpecialization);
8895 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
8896 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008897 }
8898
Douglas Gregorec9fd132012-01-14 16:38:05 +00008899 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00008900 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
8901 PrevDecl = Specialization;
8902
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008903 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00008904 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008905 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008906 PrevDecl,
8907 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008908 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008909 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008910 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008911
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008912 // FIXME: We may still want to build some representation of this
8913 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00008914 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00008915 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008916 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00008917
8918 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Rafael Espindola2aa7acf2012-01-04 05:40:59 +00008919 if (Attr)
8920 ProcessDeclAttributeList(S, Specialization, Attr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008921
Richard Smitheb36ddf2014-04-24 22:45:46 +00008922 if (Specialization->isDefined()) {
8923 // Let the ASTConsumer know that this function has been explicitly
8924 // instantiated now, and its linkage might have changed.
8925 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
8926 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00008927 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008928
Douglas Gregore47f5a72009-10-14 23:41:34 +00008929 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008930 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008931 // or a static data member of a class template specialization, the name of
8932 // the class template specialization in the qualified-id for the member
8933 // name shall be a simple-template-id.
8934 //
8935 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008936 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00008937 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008938 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00008939 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008940 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00008941 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008942 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008943
Nathan Wilson83839122016-04-09 02:55:27 +00008944 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
8945 // explicit instantiation (14.8.2) [...] of a concept definition.
8946 if (FunTmpl && FunTmpl->isConcept() &&
8947 !D.getDeclSpec().isConceptSpecified()) {
8948 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
8949 << 0 /*function*/ << 0 /*explicitly instantiated*/;
8950 Diag(FunTmpl->getLocation(), diag::note_previous_declaration);
8951 return true;
8952 }
8953
Douglas Gregore47f5a72009-10-14 23:41:34 +00008954 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008955 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregore47f5a72009-10-14 23:41:34 +00008956 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008957 D.getIdentifierLoc(),
Douglas Gregore47f5a72009-10-14 23:41:34 +00008958 D.getCXXScopeSpec().isSet());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008959
Douglas Gregor450f00842009-09-25 18:43:00 +00008960 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00008961 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008962}
8963
John McCallfaf5fb42010-08-26 23:41:50 +00008964TypeResult
John McCall7f41d982009-09-11 04:59:25 +00008965Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
8966 const CXXScopeSpec &SS, IdentifierInfo *Name,
8967 SourceLocation TagLoc, SourceLocation NameLoc) {
8968 // This has to hold, because SS is expected to be defined.
8969 assert(Name && "Expected a name in a dependent tag");
8970
Aaron Ballman4a979672014-01-03 13:56:08 +00008971 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00008972 if (!NNS)
8973 return true;
8974
Abramo Bagnara6150c882010-05-11 21:36:43 +00008975 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00008976
Douglas Gregorba41d012010-04-24 16:38:41 +00008977 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
8978 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00008979 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00008980 return true;
8981 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00008982
Douglas Gregore7c20652011-03-02 00:47:37 +00008983 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00008984 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00008985 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
Simon Pilgrim6905d222016-12-30 22:55:33 +00008986
Douglas Gregore7c20652011-03-02 00:47:37 +00008987 // Create type-source location information for this type.
8988 TypeLocBuilder TLB;
8989 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008990 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00008991 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8992 TL.setNameLoc(NameLoc);
8993 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00008994}
8995
John McCallfaf5fb42010-08-26 23:41:50 +00008996TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008997Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
8998 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00008999 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009000 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00009001 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009002
Richard Smith0bf8a4922011-10-18 20:49:44 +00009003 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9004 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009005 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00009006 diag::warn_cxx98_compat_typename_outside_of_template :
9007 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009008 << FixItHint::CreateRemoval(TypenameLoc);
9009
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009010 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00009011 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
9012 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00009013 if (T.isNull())
9014 return true;
John McCall99b2fe52010-04-29 23:50:39 +00009015
9016 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9017 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00009018 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009019 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009020 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00009021 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00009022 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00009023 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009024 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009025 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00009026 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00009027 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009028
John McCallba7bf592010-08-24 05:47:05 +00009029 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00009030}
9031
John McCallfaf5fb42010-08-26 23:41:50 +00009032TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009033Sema::ActOnTypenameType(Scope *S,
9034 SourceLocation TypenameLoc,
9035 const CXXScopeSpec &SS,
9036 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00009037 TemplateTy TemplateIn,
Richard Smith74f02342017-01-19 21:00:13 +00009038 IdentifierInfo *TemplateII,
9039 SourceLocation TemplateIILoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00009040 SourceLocation LAngleLoc,
9041 ASTTemplateArgsPtr TemplateArgsIn,
9042 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00009043 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9044 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009045 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00009046 diag::warn_cxx98_compat_typename_outside_of_template :
9047 diag::ext_typename_outside_of_template)
9048 << FixItHint::CreateRemoval(TypenameLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009049
Richard Smith74f02342017-01-19 21:00:13 +00009050 // Strangely, non-type results are not ignored by this lookup, so the
9051 // program is ill-formed if it finds an injected-class-name.
Richard Smith62559bd2017-02-01 21:36:38 +00009052 if (TypenameLoc.isValid()) {
9053 auto *LookupRD =
9054 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
9055 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
9056 Diag(TemplateIILoc,
9057 diag::ext_out_of_line_qualified_id_type_names_constructor)
9058 << TemplateII << 0 /*injected-class-name used as template name*/
9059 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
9060 }
Richard Smith74f02342017-01-19 21:00:13 +00009061 }
9062
Douglas Gregorb09518c2011-02-27 22:46:49 +00009063 // Translate the parser's template argument list in our AST format.
9064 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9065 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009066
Douglas Gregorb09518c2011-02-27 22:46:49 +00009067 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009068 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
9069 // Construct a dependent template specialization type.
9070 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00009071 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009072 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
9073 DTN->getQualifier(),
9074 DTN->getIdentifier(),
9075 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009076
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009077 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00009078 TypeLocBuilder Builder;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009079 DependentTemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009080 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009081 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
9082 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00009083 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00009084 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009085 SpecTL.setLAngleLoc(LAngleLoc);
9086 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009087 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9088 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009089 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00009090 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009091
Richard Smith74f02342017-01-19 21:00:13 +00009092 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009093 if (T.isNull())
9094 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009095
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009096 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00009097 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009098 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009099 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009100 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00009101 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009102 SpecTL.setLAngleLoc(LAngleLoc);
9103 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009104 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9105 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009106
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009107 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
9108 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009109 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009110 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Simon Pilgrim6905d222016-12-30 22:55:33 +00009111
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009112 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
9113 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00009114}
9115
Douglas Gregorb09518c2011-02-27 22:46:49 +00009116
Richard Smith6f8d2c62012-05-09 05:17:00 +00009117/// Determine whether this failed name lookup should be treated as being
9118/// disabled by a usage of std::enable_if.
9119static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
9120 SourceRange &CondRange) {
9121 // We must be looking for a ::type...
9122 if (!II.isStr("type"))
9123 return false;
9124
9125 // ... within an explicitly-written template specialization...
9126 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
9127 return false;
9128 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00009129 TemplateSpecializationTypeLoc EnableIfTSTLoc =
9130 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
9131 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00009132 return false;
9133 const TemplateSpecializationType *EnableIfTST =
David Blaikie6adc78e2013-02-18 22:06:02 +00009134 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
Richard Smith6f8d2c62012-05-09 05:17:00 +00009135
9136 // ... which names a complete class template declaration...
9137 const TemplateDecl *EnableIfDecl =
9138 EnableIfTST->getTemplateName().getAsTemplateDecl();
9139 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
9140 return false;
9141
9142 // ... called "enable_if".
9143 const IdentifierInfo *EnableIfII =
9144 EnableIfDecl->getDeclName().getAsIdentifierInfo();
9145 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
9146 return false;
9147
9148 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00009149 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009150 return true;
9151}
9152
Douglas Gregor333489b2009-03-27 23:10:48 +00009153/// \brief Build the type that describes a C++ typename specifier,
9154/// e.g., "typename T::type".
9155QualType
Simon Pilgrim6905d222016-12-30 22:55:33 +00009156Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009157 SourceLocation KeywordLoc,
Simon Pilgrim6905d222016-12-30 22:55:33 +00009158 NestedNameSpecifierLoc QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009159 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00009160 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00009161 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009162 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00009163
John McCall0b66eb32010-05-01 00:40:08 +00009164 DeclContext *Ctx = computeDeclContext(SS);
9165 if (!Ctx) {
9166 // If the nested-name-specifier is dependent and couldn't be
9167 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009168 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009169 return Context.getDependentNameType(Keyword,
9170 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009171 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00009172 }
Douglas Gregor333489b2009-03-27 23:10:48 +00009173
John McCall0b66eb32010-05-01 00:40:08 +00009174 // If the nested-name-specifier refers to the current instantiation,
9175 // the "typename" keyword itself is superfluous. In C++03, the
9176 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
9177 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00009178 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00009179
John McCall0b66eb32010-05-01 00:40:08 +00009180 if (RequireCompleteDeclContext(SS, Ctx))
9181 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00009182
9183 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00009184 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00009185 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00009186 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00009187 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00009188 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00009189 case LookupResult::NotFound: {
9190 // If we're looking up 'type' within a template named 'enable_if', produce
9191 // a more specific diagnostic.
9192 SourceRange CondRange;
9193 if (isEnableIf(QualifierLoc, II, CondRange)) {
9194 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
9195 << Ctx << CondRange;
9196 return QualType();
9197 }
9198
Douglas Gregore40876a2009-10-13 21:16:44 +00009199 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00009200 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009201 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009202
9203 case LookupResult::FoundUnresolvedValue: {
9204 // We found a using declaration that is a value. Most likely, the using
9205 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009206 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009207 IILoc);
9208 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
9209 << Name << Ctx << FullRange;
9210 if (UnresolvedUsingValueDecl *Using
9211 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009212 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009213 Diag(Loc, diag::note_using_value_decl_missing_typename)
9214 << FixItHint::CreateInsertion(Loc, "typename ");
9215 }
9216 }
9217 // Fall through to create a dependent typename type, from which we can recover
9218 // better.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009219
Douglas Gregord0d2ee02010-01-15 01:44:47 +00009220 case LookupResult::NotFoundInCurrentInstantiation:
9221 // Okay, it's a member of an unknown instantiation.
Simon Pilgrim6905d222016-12-30 22:55:33 +00009222 return Context.getDependentNameType(Keyword,
9223 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009224 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00009225
9226 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009227 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Richard Smith74f02342017-01-19 21:00:13 +00009228 // C++ [class.qual]p2:
9229 // In a lookup in which function names are not ignored and the
9230 // nested-name-specifier nominates a class C, if the name specified
9231 // after the nested-name-specifier, when looked up in C, is the
9232 // injected-class-name of C [...] then the name is instead considered
9233 // to name the constructor of class C.
9234 //
9235 // Unlike in an elaborated-type-specifier, function names are not ignored
9236 // in typename-specifier lookup. However, they are ignored in all the
9237 // contexts where we form a typename type with no keyword (that is, in
9238 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
9239 //
9240 // FIXME: That's not strictly true: mem-initializer-id lookup does not
9241 // ignore functions, but that appears to be an oversight.
9242 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
9243 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
9244 if (Keyword == ETK_Typename && LookupRD && FoundRD &&
9245 FoundRD->isInjectedClassName() &&
9246 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
9247 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
9248 << &II << 1 << 0 /*'typename' keyword used*/;
9249
Abramo Bagnara6150c882010-05-11 21:36:43 +00009250 // We found a type. Build an ElaboratedType, since the
9251 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00009252 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Richard Smith74f02342017-01-19 21:00:13 +00009253 return Context.getElaboratedType(Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009254 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00009255 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00009256 }
9257
Richard Smithee579842017-01-30 20:39:26 +00009258 // C++ [dcl.type.simple]p2:
9259 // A type-specifier of the form
9260 // typename[opt] nested-name-specifier[opt] template-name
9261 // is a placeholder for a deduced class type [...].
9262 if (getLangOpts().CPlusPlus1z) {
9263 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
9264 return Context.getElaboratedType(
9265 Keyword, QualifierLoc.getNestedNameSpecifier(),
9266 Context.getDeducedTemplateSpecializationType(TemplateName(TD),
9267 QualType(), false));
9268 }
9269 }
Richard Smith600b5262017-01-26 20:40:47 +00009270
Douglas Gregor333489b2009-03-27 23:10:48 +00009271 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00009272 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00009273 break;
9274
9275 case LookupResult::FoundOverloaded:
9276 DiagID = diag::err_typename_nested_not_type;
9277 Referenced = *Result.begin();
9278 break;
9279
John McCall6538c932009-10-10 05:48:19 +00009280 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00009281 return QualType();
9282 }
9283
9284 // If we get here, it's because name lookup did not find a
9285 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009286 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00009287 IILoc);
9288 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00009289 if (Referenced)
9290 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
9291 << Name;
9292 return QualType();
9293}
Douglas Gregor15acfb92009-08-06 16:20:37 +00009294
9295namespace {
9296 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00009297 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00009298 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00009299 SourceLocation Loc;
9300 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00009301
Douglas Gregor15acfb92009-08-06 16:20:37 +00009302 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00009303 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009304
Mike Stump11289f42009-09-09 15:08:12 +00009305 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00009306 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00009307 DeclarationName Entity)
9308 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00009309 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00009310
9311 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00009312 /// transformed.
9313 ///
9314 /// For the purposes of type reconstruction, a type has already been
9315 /// transformed if it is NULL or if it is not dependent.
9316 bool AlreadyTransformed(QualType T) {
9317 return T.isNull() || !T->isDependentType();
9318 }
Mike Stump11289f42009-09-09 15:08:12 +00009319
9320 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00009321 /// rebuilt.
9322 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00009323
Douglas Gregor15acfb92009-08-06 16:20:37 +00009324 /// \brief Returns the name of the entity whose type is being rebuilt.
9325 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00009326
Douglas Gregoref6ab412009-10-27 06:26:26 +00009327 /// \brief Sets the "base" location and entity when that
9328 /// information is known based on another transformation.
9329 void setBase(SourceLocation Loc, DeclarationName Entity) {
9330 this->Loc = Loc;
9331 this->Entity = Entity;
9332 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009333
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00009334 ExprResult TransformLambdaExpr(LambdaExpr *E) {
9335 // Lambdas never need to be transformed.
9336 return E;
9337 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00009338 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009339} // end anonymous namespace
Douglas Gregor15acfb92009-08-06 16:20:37 +00009340
Douglas Gregor15acfb92009-08-06 16:20:37 +00009341/// \brief Rebuilds a type within the context of the current instantiation.
9342///
Mike Stump11289f42009-09-09 15:08:12 +00009343/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00009344/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00009345/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00009346/// partial specialization thereof). This routine will rebuild that type now
9347/// that we have entered the declarator's scope, which may produce different
9348/// canonical types, e.g.,
9349///
9350/// \code
9351/// template<typename T>
9352/// struct X {
9353/// typedef T* pointer;
9354/// pointer data();
9355/// };
9356///
9357/// template<typename T>
9358/// typename X<T>::pointer X<T>::data() { ... }
9359/// \endcode
9360///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00009361/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00009362/// since we do not know that we can look into X<T> when we parsed the type.
9363/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00009364/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00009365/// as the canonical type of T*, allowing the return types of the out-of-line
9366/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00009367TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
9368 SourceLocation Loc,
9369 DeclarationName Name) {
9370 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00009371 return T;
Mike Stump11289f42009-09-09 15:08:12 +00009372
Douglas Gregor15acfb92009-08-06 16:20:37 +00009373 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
9374 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00009375}
Douglas Gregorbe999392009-09-15 16:23:51 +00009376
John McCalldadc5752010-08-24 06:29:42 +00009377ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00009378 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
9379 DeclarationName());
9380 return Rebuilder.TransformExpr(E);
9381}
9382
John McCall99b2fe52010-04-29 23:50:39 +00009383bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00009384 if (SS.isInvalid())
Douglas Gregor10176412011-02-25 16:07:42 +00009385 return true;
John McCall2408e322010-04-27 00:57:59 +00009386
Douglas Gregor10176412011-02-25 16:07:42 +00009387 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00009388 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
9389 DeclarationName());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009390 NestedNameSpecifierLoc Rebuilt
Douglas Gregor10176412011-02-25 16:07:42 +00009391 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009392 if (!Rebuilt)
Douglas Gregor10176412011-02-25 16:07:42 +00009393 return true;
John McCall99b2fe52010-04-29 23:50:39 +00009394
Douglas Gregor10176412011-02-25 16:07:42 +00009395 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00009396 return false;
John McCall2408e322010-04-27 00:57:59 +00009397}
9398
Douglas Gregor041b0842011-10-14 15:31:12 +00009399/// \brief Rebuild the template parameters now that we know we're in a current
9400/// instantiation.
9401bool Sema::RebuildTemplateParamsInCurrentInstantiation(
9402 TemplateParameterList *Params) {
9403 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
9404 Decl *Param = Params->getParam(I);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009405
Douglas Gregor041b0842011-10-14 15:31:12 +00009406 // There is nothing to rebuild in a type parameter.
9407 if (isa<TemplateTypeParmDecl>(Param))
9408 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009409
Douglas Gregor041b0842011-10-14 15:31:12 +00009410 // Rebuild the template parameter list of a template template parameter.
Simon Pilgrim6905d222016-12-30 22:55:33 +00009411 if (TemplateTemplateParmDecl *TTP
Douglas Gregor041b0842011-10-14 15:31:12 +00009412 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
9413 if (RebuildTemplateParamsInCurrentInstantiation(
9414 TTP->getTemplateParameters()))
9415 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009416
Douglas Gregor041b0842011-10-14 15:31:12 +00009417 continue;
9418 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009419
Douglas Gregor041b0842011-10-14 15:31:12 +00009420 // Rebuild the type of a non-type template parameter.
9421 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009422 TypeSourceInfo *NewTSI
9423 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
9424 NTTP->getLocation(),
Douglas Gregor041b0842011-10-14 15:31:12 +00009425 NTTP->getDeclName());
9426 if (!NewTSI)
9427 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009428
Douglas Gregor041b0842011-10-14 15:31:12 +00009429 if (NewTSI != NTTP->getTypeSourceInfo()) {
9430 NTTP->setTypeSourceInfo(NewTSI);
9431 NTTP->setType(NewTSI->getType());
9432 }
9433 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009434
Douglas Gregor041b0842011-10-14 15:31:12 +00009435 return false;
9436}
9437
Douglas Gregorbe999392009-09-15 16:23:51 +00009438/// \brief Produces a formatted string that describes the binding of
9439/// template parameters to template arguments.
9440std::string
9441Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9442 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009443 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00009444}
9445
9446std::string
9447Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9448 const TemplateArgument *Args,
9449 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009450 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +00009451 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +00009452
Douglas Gregore62e6a02009-11-11 19:13:48 +00009453 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00009454 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009455
Douglas Gregorbe999392009-09-15 16:23:51 +00009456 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00009457 if (I >= NumArgs)
9458 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009459
Douglas Gregorbe999392009-09-15 16:23:51 +00009460 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00009461 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +00009462 else
Douglas Gregor0192c232010-12-20 16:52:59 +00009463 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009464
Douglas Gregorbe999392009-09-15 16:23:51 +00009465 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +00009466 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +00009467 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +00009468 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +00009469 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009470
Douglas Gregor0192c232010-12-20 16:52:59 +00009471 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +00009472 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +00009473 }
Douglas Gregor0192c232010-12-20 16:52:59 +00009474
9475 Out << ']';
9476 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +00009477}
Francois Pichet1c229c02011-04-22 22:18:13 +00009478
Richard Smithe40f2ba2013-08-07 21:41:30 +00009479void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
9480 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +00009481 if (!FD)
9482 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +00009483
Justin Lebar28f09c52016-10-10 16:26:08 +00009484 auto LPT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00009485
9486 // Take tokens to avoid allocations
9487 LPT->Toks.swap(Toks);
9488 LPT->D = FnD;
Justin Lebar28f09c52016-10-10 16:26:08 +00009489 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00009490
9491 FD->setLateTemplateParsed(true);
9492}
9493
9494void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
9495 if (!FD)
9496 return;
9497 FD->setLateTemplateParsed(false);
9498}
Francois Pichet1c229c02011-04-22 22:18:13 +00009499
9500bool Sema::IsInsideALocalClassWithinATemplateFunction() {
9501 DeclContext *DC = CurContext;
9502
9503 while (DC) {
9504 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
9505 const FunctionDecl *FD = RD->isLocalClass();
9506 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
9507 } else if (DC->isTranslationUnit() || DC->isNamespace())
9508 return false;
9509
9510 DC = DC->getParent();
9511 }
9512 return false;
9513}
Richard Smith6739a102016-05-05 00:56:12 +00009514
Benjamin Kramera0a13c32016-08-06 11:21:04 +00009515namespace {
Richard Smith6739a102016-05-05 00:56:12 +00009516/// \brief Walk the path from which a declaration was instantiated, and check
9517/// that every explicit specialization along that path is visible. This enforces
9518/// C++ [temp.expl.spec]/6:
9519///
9520/// If a template, a member template or a member of a class template is
9521/// explicitly specialized then that specialization shall be declared before
9522/// the first use of that specialization that would cause an implicit
9523/// instantiation to take place, in every translation unit in which such a
9524/// use occurs; no diagnostic is required.
9525///
9526/// and also C++ [temp.class.spec]/1:
9527///
9528/// A partial specialization shall be declared before the first use of a
9529/// class template specialization that would make use of the partial
9530/// specialization as the result of an implicit or explicit instantiation
9531/// in every translation unit in which such a use occurs; no diagnostic is
9532/// required.
9533class ExplicitSpecializationVisibilityChecker {
9534 Sema &S;
9535 SourceLocation Loc;
9536 llvm::SmallVector<Module *, 8> Modules;
9537
9538public:
9539 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
9540 : S(S), Loc(Loc) {}
9541
9542 void check(NamedDecl *ND) {
9543 if (auto *FD = dyn_cast<FunctionDecl>(ND))
9544 return checkImpl(FD);
9545 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
9546 return checkImpl(RD);
9547 if (auto *VD = dyn_cast<VarDecl>(ND))
9548 return checkImpl(VD);
9549 if (auto *ED = dyn_cast<EnumDecl>(ND))
9550 return checkImpl(ED);
9551 }
9552
9553private:
9554 void diagnose(NamedDecl *D, bool IsPartialSpec) {
9555 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
9556 : Sema::MissingImportKind::ExplicitSpecialization;
9557 const bool Recover = true;
9558
9559 // If we got a custom set of modules (because only a subset of the
9560 // declarations are interesting), use them, otherwise let
9561 // diagnoseMissingImport intelligently pick some.
9562 if (Modules.empty())
9563 S.diagnoseMissingImport(Loc, D, Kind, Recover);
9564 else
9565 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
9566 }
9567
9568 // Check a specific declaration. There are three problematic cases:
9569 //
9570 // 1) The declaration is an explicit specialization of a template
9571 // specialization.
9572 // 2) The declaration is an explicit specialization of a member of an
9573 // templated class.
9574 // 3) The declaration is an instantiation of a template, and that template
9575 // is an explicit specialization of a member of a templated class.
9576 //
9577 // We don't need to go any deeper than that, as the instantiation of the
9578 // surrounding class / etc is not triggered by whatever triggered this
9579 // instantiation, and thus should be checked elsewhere.
9580 template<typename SpecDecl>
9581 void checkImpl(SpecDecl *Spec) {
9582 bool IsHiddenExplicitSpecialization = false;
9583 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
9584 IsHiddenExplicitSpecialization =
9585 Spec->getMemberSpecializationInfo()
9586 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
9587 : !S.hasVisibleDeclaration(Spec);
9588 } else {
9589 checkInstantiated(Spec);
9590 }
9591
9592 if (IsHiddenExplicitSpecialization)
9593 diagnose(Spec->getMostRecentDecl(), false);
9594 }
9595
9596 void checkInstantiated(FunctionDecl *FD) {
9597 if (auto *TD = FD->getPrimaryTemplate())
9598 checkTemplate(TD);
9599 }
9600
9601 void checkInstantiated(CXXRecordDecl *RD) {
9602 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
9603 if (!SD)
9604 return;
9605
9606 auto From = SD->getSpecializedTemplateOrPartial();
9607 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
9608 checkTemplate(TD);
9609 else if (auto *TD =
9610 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
9611 if (!S.hasVisibleDeclaration(TD))
9612 diagnose(TD, true);
9613 checkTemplate(TD);
9614 }
9615 }
9616
9617 void checkInstantiated(VarDecl *RD) {
9618 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
9619 if (!SD)
9620 return;
9621
9622 auto From = SD->getSpecializedTemplateOrPartial();
9623 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
9624 checkTemplate(TD);
9625 else if (auto *TD =
9626 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
9627 if (!S.hasVisibleDeclaration(TD))
9628 diagnose(TD, true);
9629 checkTemplate(TD);
9630 }
9631 }
9632
9633 void checkInstantiated(EnumDecl *FD) {}
9634
9635 template<typename TemplDecl>
9636 void checkTemplate(TemplDecl *TD) {
9637 if (TD->isMemberSpecialization()) {
9638 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
9639 diagnose(TD->getMostRecentDecl(), false);
9640 }
9641 }
9642};
Benjamin Kramera0a13c32016-08-06 11:21:04 +00009643} // end anonymous namespace
Richard Smith6739a102016-05-05 00:56:12 +00009644
9645void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
9646 if (!getLangOpts().Modules)
9647 return;
9648
9649 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
9650}
9651
9652/// \brief Check whether a template partial specialization that we've discovered
9653/// is hidden, and produce suitable diagnostics if so.
9654void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
9655 NamedDecl *Spec) {
9656 llvm::SmallVector<Module *, 8> Modules;
9657 if (!hasVisibleDeclaration(Spec, &Modules))
9658 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
9659 MissingImportKind::PartialSpecialization,
9660 /*Recover*/true);
9661}