blob: 61b4df40964c618eb338f358c972acbbaa75fbf3 [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.
Richard Smithbc491202017-02-17 20:05:37 +00001441 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
1442 CXXConstructorDecl *CD) {
Richard Smith32918772017-02-14 00:25:28 +00001443 SmallVector<TemplateArgument, 16> SubstArgs;
1444
Richard Smithb4f96252017-02-21 06:30:38 +00001445 LocalInstantiationScope Scope(SemaRef);
1446
Richard Smith32918772017-02-14 00:25:28 +00001447 // C++ [over.match.class.deduct]p1:
1448 // -- For each constructor of the class template designated by the
1449 // template-name, a function template with the following properties:
1450
1451 // -- The template parameters are the template parameters of the class
1452 // template followed by the template parameters (including default
1453 // template arguments) of the constructor, if any.
1454 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
1455 if (FTD) {
1456 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
1457 SmallVector<NamedDecl *, 16> AllParams;
1458 AllParams.reserve(TemplateParams->size() + InnerParams->size());
1459 AllParams.insert(AllParams.begin(),
1460 TemplateParams->begin(), TemplateParams->end());
1461 SubstArgs.reserve(InnerParams->size());
1462
1463 // Later template parameters could refer to earlier ones, so build up
1464 // a list of substituted template arguments as we go.
1465 for (NamedDecl *Param : *InnerParams) {
1466 MultiLevelTemplateArgumentList Args;
1467 Args.addOuterTemplateArguments(SubstArgs);
Richard Smithb4f96252017-02-21 06:30:38 +00001468 Args.addOuterRetainedLevel();
Richard Smith32918772017-02-14 00:25:28 +00001469 NamedDecl *NewParam = transformTemplateParameter(Param, Args);
1470 if (!NewParam)
1471 return nullptr;
1472 AllParams.push_back(NewParam);
1473 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
1474 SemaRef.Context.getInjectedTemplateArg(NewParam)));
1475 }
1476 TemplateParams = TemplateParameterList::Create(
1477 SemaRef.Context, InnerParams->getTemplateLoc(),
1478 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
1479 /*FIXME: RequiresClause*/ nullptr);
1480 }
1481
1482 // If we built a new template-parameter-list, track that we need to
1483 // substitute references to the old parameters into references to the
1484 // new ones.
1485 MultiLevelTemplateArgumentList Args;
1486 if (FTD) {
1487 Args.addOuterTemplateArguments(SubstArgs);
Richard Smithb4f96252017-02-21 06:30:38 +00001488 Args.addOuterRetainedLevel();
Richard Smith32918772017-02-14 00:25:28 +00001489 }
1490
Richard Smithbc491202017-02-17 20:05:37 +00001491 FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
Richard Smith32918772017-02-14 00:25:28 +00001492 .getAsAdjusted<FunctionProtoTypeLoc>();
1493 assert(FPTL && "no prototype for constructor declaration");
1494
1495 // Transform the type of the function, adjusting the return type and
1496 // replacing references to the old parameters with references to the
1497 // new ones.
1498 TypeLocBuilder TLB;
1499 SmallVector<ParmVarDecl*, 8> Params;
1500 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args);
1501 if (NewType.isNull())
1502 return nullptr;
1503 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
1504
Richard Smithbc491202017-02-17 20:05:37 +00001505 return buildDeductionGuide(TemplateParams, CD->isExplicit(), NewTInfo,
1506 CD->getLocStart(), CD->getLocation(),
1507 CD->getLocEnd());
Richard Smith32918772017-02-14 00:25:28 +00001508 }
1509
1510 /// Build a deduction guide with the specified parameter types.
1511 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
1512 SourceLocation Loc = Template->getLocation();
1513
1514 // Build the requested type.
1515 FunctionProtoType::ExtProtoInfo EPI;
1516 EPI.HasTrailingReturn = true;
1517 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
1518 DeductionGuideName, EPI);
1519 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
1520
1521 FunctionProtoTypeLoc FPTL =
1522 TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
1523
1524 // Build the parameters, needed during deduction / substitution.
1525 SmallVector<ParmVarDecl*, 4> Params;
1526 for (auto T : ParamTypes) {
1527 ParmVarDecl *NewParam = ParmVarDecl::Create(
1528 SemaRef.Context, DC, Loc, Loc, nullptr, T,
1529 SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
1530 NewParam->setScopeInfo(0, Params.size());
1531 FPTL.setParam(Params.size(), NewParam);
1532 Params.push_back(NewParam);
1533 }
1534
1535 return buildDeductionGuide(Template->getTemplateParameters(), false, TSI,
1536 Loc, Loc, Loc);
1537 }
1538
1539private:
1540 /// Transform a constructor template parameter into a deduction guide template
1541 /// parameter, rebuilding any internal references to earlier parameters and
1542 /// renumbering as we go.
1543 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
1544 MultiLevelTemplateArgumentList &Args) {
1545 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
1546 // TemplateTypeParmDecl's index cannot be changed after creation, so
1547 // substitute it directly.
1548 auto *NewTTP = TemplateTypeParmDecl::Create(
1549 SemaRef.Context, DC, TTP->getLocStart(), TTP->getLocation(),
1550 /*Depth*/0, Depth1IndexAdjustment + TTP->getIndex(),
1551 TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
1552 TTP->isParameterPack());
1553 if (TTP->hasDefaultArgument()) {
1554 TypeSourceInfo *InstantiatedDefaultArg =
1555 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
1556 TTP->getDefaultArgumentLoc(), TTP->getDeclName());
1557 if (InstantiatedDefaultArg)
1558 NewTTP->setDefaultArgument(InstantiatedDefaultArg);
1559 }
Richard Smithb4f96252017-02-21 06:30:38 +00001560 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
1561 NewTTP);
Richard Smith32918772017-02-14 00:25:28 +00001562 return NewTTP;
1563 }
1564
1565 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
1566 return transformTemplateParameterImpl(TTP, Args);
1567
1568 return transformTemplateParameterImpl(
1569 cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
1570 }
1571 template<typename TemplateParmDecl>
1572 TemplateParmDecl *
1573 transformTemplateParameterImpl(TemplateParmDecl *OldParam,
1574 MultiLevelTemplateArgumentList &Args) {
1575 // Ask the template instantiator to do the heavy lifting for us, then adjust
1576 // the index of the parameter once it's done.
1577 auto *NewParam =
1578 cast_or_null<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
1579 assert(NewParam->getDepth() == 0 && "unexpected template param depth");
1580 NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
1581 return NewParam;
1582 }
1583
1584 QualType transformFunctionProtoType(TypeLocBuilder &TLB,
1585 FunctionProtoTypeLoc TL,
1586 SmallVectorImpl<ParmVarDecl*> &Params,
1587 MultiLevelTemplateArgumentList &Args) {
1588 SmallVector<QualType, 4> ParamTypes;
1589 const FunctionProtoType *T = TL.getTypePtr();
1590
1591 // -- The types of the function parameters are those of the constructor.
1592 for (auto *OldParam : TL.getParams()) {
Richard Smithc27b3d72017-02-14 01:49:59 +00001593 ParmVarDecl *NewParam = transformFunctionTypeParam(OldParam, Args);
Richard Smith32918772017-02-14 00:25:28 +00001594 if (!NewParam)
1595 return QualType();
1596 ParamTypes.push_back(NewParam->getType());
1597 Params.push_back(NewParam);
1598 }
1599
1600 // -- The return type is the class template specialization designated by
1601 // the template-name and template arguments corresponding to the
1602 // template parameters obtained from the class template.
1603 //
1604 // We use the injected-class-name type of the primary template instead.
1605 // This has the convenient property that it is different from any type that
1606 // the user can write in a deduction-guide (because they cannot enter the
1607 // context of the template), so implicit deduction guides can never collide
1608 // with explicit ones.
1609 QualType ReturnType = DeducedType;
1610 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
1611
1612 // Resolving a wording defect, we also inherit the variadicness of the
1613 // constructor.
1614 FunctionProtoType::ExtProtoInfo EPI;
1615 EPI.Variadic = T->isVariadic();
1616 EPI.HasTrailingReturn = true;
1617
1618 QualType Result = SemaRef.BuildFunctionType(
1619 ReturnType, ParamTypes, TL.getLocStart(), DeductionGuideName, EPI);
1620 if (Result.isNull())
1621 return QualType();
1622
1623 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
1624 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
1625 NewTL.setLParenLoc(TL.getLParenLoc());
1626 NewTL.setRParenLoc(TL.getRParenLoc());
1627 NewTL.setExceptionSpecRange(SourceRange());
1628 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
1629 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
1630 NewTL.setParam(I, Params[I]);
1631
1632 return Result;
1633 }
1634
1635 ParmVarDecl *
1636 transformFunctionTypeParam(ParmVarDecl *OldParam,
1637 MultiLevelTemplateArgumentList &Args) {
1638 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
Richard Smith479ba8e2017-04-20 01:15:31 +00001639 TypeSourceInfo *NewDI;
1640 if (!Args.getNumLevels())
1641 NewDI = OldDI;
1642 else if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
1643 // Expand out the one and only element in each inner pack.
1644 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
1645 NewDI =
1646 SemaRef.SubstType(PackTL.getPatternLoc(), Args,
1647 OldParam->getLocation(), OldParam->getDeclName());
1648 if (!NewDI) return nullptr;
1649 NewDI =
1650 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
1651 PackTL.getTypePtr()->getNumExpansions());
1652 } else
1653 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
1654 OldParam->getDeclName());
Richard Smith32918772017-02-14 00:25:28 +00001655 if (!NewDI)
1656 return nullptr;
1657
Richard Smithc27b3d72017-02-14 01:49:59 +00001658 // Canonicalize the type. This (for instance) replaces references to
1659 // typedef members of the current instantiations with the definitions of
1660 // those typedefs, avoiding triggering instantiation of the deduced type
1661 // during deduction.
1662 // FIXME: It would be preferable to retain type sugar and source
1663 // information here (and handle this in substitution instead).
1664 NewDI = SemaRef.Context.getTrivialTypeSourceInfo(
1665 SemaRef.Context.getCanonicalType(NewDI->getType()),
1666 OldParam->getLocation());
1667
Richard Smith32918772017-02-14 00:25:28 +00001668 // Resolving a wording defect, we also inherit default arguments from the
1669 // constructor.
1670 ExprResult NewDefArg;
1671 if (OldParam->hasDefaultArg()) {
Richard Smithc27b3d72017-02-14 01:49:59 +00001672 NewDefArg = Args.getNumLevels()
1673 ? SemaRef.SubstExpr(OldParam->getDefaultArg(), Args)
1674 : OldParam->getDefaultArg();
Richard Smith32918772017-02-14 00:25:28 +00001675 if (NewDefArg.isInvalid())
1676 return nullptr;
1677 }
1678
1679 ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
1680 OldParam->getInnerLocStart(),
1681 OldParam->getLocation(),
1682 OldParam->getIdentifier(),
1683 NewDI->getType(),
1684 NewDI,
1685 OldParam->getStorageClass(),
1686 NewDefArg.get());
1687 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
1688 OldParam->getFunctionScopeIndex());
1689 return NewParam;
1690 }
1691
1692 NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams,
1693 bool Explicit, TypeSourceInfo *TInfo,
1694 SourceLocation LocStart, SourceLocation Loc,
1695 SourceLocation LocEnd) {
Richard Smithbc491202017-02-17 20:05:37 +00001696 DeclarationNameInfo Name(DeductionGuideName, Loc);
Richard Smithefa919a2017-02-16 21:29:21 +00001697 ArrayRef<ParmVarDecl *> Params =
1698 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
1699
Richard Smith32918772017-02-14 00:25:28 +00001700 // Build the implicit deduction guide template.
Richard Smithbc491202017-02-17 20:05:37 +00001701 auto *Guide =
1702 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, Explicit,
1703 Name, TInfo->getType(), TInfo, LocEnd);
Richard Smith32918772017-02-14 00:25:28 +00001704 Guide->setImplicit();
Richard Smithefa919a2017-02-16 21:29:21 +00001705 Guide->setParams(Params);
1706
1707 for (auto *Param : Params)
1708 Param->setDeclContext(Guide);
Richard Smith32918772017-02-14 00:25:28 +00001709
1710 auto *GuideTemplate = FunctionTemplateDecl::Create(
1711 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
1712 GuideTemplate->setImplicit();
1713 Guide->setDescribedFunctionTemplate(GuideTemplate);
1714
1715 if (isa<CXXRecordDecl>(DC)) {
1716 Guide->setAccess(AS_public);
1717 GuideTemplate->setAccess(AS_public);
1718 }
1719
1720 DC->addDecl(GuideTemplate);
1721 return GuideTemplate;
1722 }
1723};
1724}
1725
1726void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
1727 SourceLocation Loc) {
1728 DeclContext *DC = Template->getDeclContext();
1729 if (DC->isDependentContext())
1730 return;
1731
1732 ConvertConstructorToDeductionGuideTransform Transform(
1733 *this, cast<ClassTemplateDecl>(Template));
1734 if (!isCompleteType(Loc, Transform.DeducedType))
1735 return;
1736
1737 // Check whether we've already declared deduction guides for this template.
1738 // FIXME: Consider storing a flag on the template to indicate this.
1739 auto Existing = DC->lookup(Transform.DeductionGuideName);
1740 for (auto *D : Existing)
1741 if (D->isImplicit())
1742 return;
1743
1744 // In case we were expanding a pack when we attempted to declare deduction
1745 // guides, turn off pack expansion for everything we're about to do.
1746 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1747 // Create a template instantiation record to track the "instantiation" of
1748 // constructors into deduction guides.
1749 // FIXME: Add a kind for this to give more meaningful diagnostics. But can
1750 // this substitution process actually fail?
1751 InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
1752
1753 // Convert declared constructors into deduction guide templates.
1754 // FIXME: Skip constructors for which deduction must necessarily fail (those
1755 // for which some class template parameter without a default argument never
1756 // appears in a deduced context).
1757 bool AddedAny = false;
1758 bool AddedCopyOrMove = false;
1759 for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
1760 D = D->getUnderlyingDecl();
1761 if (D->isInvalidDecl() || D->isImplicit())
1762 continue;
1763 D = cast<NamedDecl>(D->getCanonicalDecl());
1764
1765 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
Richard Smithbc491202017-02-17 20:05:37 +00001766 auto *CD =
1767 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
Richard Smith32918772017-02-14 00:25:28 +00001768 // Class-scope explicit specializations (MS extension) do not result in
1769 // deduction guides.
Richard Smithbc491202017-02-17 20:05:37 +00001770 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
Richard Smith32918772017-02-14 00:25:28 +00001771 continue;
1772
Richard Smithbc491202017-02-17 20:05:37 +00001773 Transform.transformConstructor(FTD, CD);
Richard Smith32918772017-02-14 00:25:28 +00001774 AddedAny = true;
1775
Richard Smith32918772017-02-14 00:25:28 +00001776 AddedCopyOrMove |= CD->isCopyOrMoveConstructor();
1777 }
1778
1779 // Synthesize an X() -> X<...> guide if there were no declared constructors.
1780 // FIXME: The standard doesn't say (how) to do this.
1781 if (!AddedAny)
1782 Transform.buildSimpleDeductionGuide(None);
1783
1784 // Synthesize an X(X<...>) -> X<...> guide if there was no declared constructor
1785 // resembling a copy or move constructor.
1786 // FIXME: The standard doesn't say (how) to do this.
1787 if (!AddedCopyOrMove)
1788 Transform.buildSimpleDeductionGuide(Transform.DeducedType);
1789}
1790
Douglas Gregored5731f2009-11-25 17:50:39 +00001791/// \brief Diagnose the presence of a default template argument on a
1792/// template parameter, which is ill-formed in certain contexts.
1793///
1794/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001795static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00001796 Sema::TemplateParamListContext TPC,
1797 SourceLocation ParamLoc,
1798 SourceRange DefArgRange) {
1799 switch (TPC) {
1800 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00001801 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00001802 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001803 return false;
1804
1805 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001806 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001807 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00001808 // A default template-argument shall not be specified in a
1809 // function template declaration or a function template
1810 // definition [...]
Simon Pilgrim6905d222016-12-30 22:55:33 +00001811 // If a friend function template declaration specifies a default
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001812 // template-argument, that declaration shall be a definition and shall be
1813 // the only declaration of the function template in the translation unit.
1814 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001815 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00001816 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1817 : diag::ext_template_parameter_default_in_function_template)
1818 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00001819 return false;
1820
1821 case Sema::TPC_ClassTemplateMember:
1822 // C++0x [temp.param]p9:
1823 // A default template-argument shall not be specified in the
1824 // template-parameter-lists of the definition of a member of a
1825 // class template that appears outside of the member's class.
1826 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1827 << DefArgRange;
1828 return true;
1829
David Majnemerba8f17a2013-06-25 22:08:55 +00001830 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001831 case Sema::TPC_FriendFunctionTemplate:
1832 // C++ [temp.param]p9:
1833 // A default template-argument shall not be specified in a
1834 // friend template declaration.
1835 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1836 << DefArgRange;
1837 return true;
1838
1839 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1840 // for friend function templates if there is only a single
1841 // declaration (and it is a definition). Strange!
1842 }
1843
David Blaikie8a40f702012-01-17 06:56:22 +00001844 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00001845}
1846
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001847/// \brief Check for unexpanded parameter packs within the template parameters
1848/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00001849static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1850 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001851 // A template template parameter which is a parameter pack is also a pack
1852 // expansion.
1853 if (TTP->isParameterPack())
1854 return false;
1855
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001856 TemplateParameterList *Params = TTP->getTemplateParameters();
1857 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1858 NamedDecl *P = Params->getParam(I);
1859 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001860 if (!NTTP->isParameterPack() &&
1861 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001862 NTTP->getTypeSourceInfo(),
1863 Sema::UPPC_NonTypeTemplateParameterType))
1864 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001865
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001866 continue;
1867 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001868
1869 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001870 = dyn_cast<TemplateTemplateParmDecl>(P))
1871 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1872 return true;
1873 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001874
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001875 return false;
1876}
1877
Douglas Gregordba32632009-02-10 19:49:53 +00001878/// \brief Checks the validity of a template parameter list, possibly
1879/// considering the template parameter list from a previous
1880/// declaration.
1881///
1882/// If an "old" template parameter list is provided, it must be
1883/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1884/// template parameter list.
1885///
1886/// \param NewParams Template parameter list for a new template
1887/// declaration. This template parameter list will be updated with any
1888/// default arguments that are carried through from the previous
1889/// template parameter list.
1890///
1891/// \param OldParams If provided, template parameter list from a
1892/// previous declaration of the same template. Default template
1893/// arguments will be merged from the old template parameter list to
1894/// the new template parameter list.
1895///
Douglas Gregored5731f2009-11-25 17:50:39 +00001896/// \param TPC Describes the context in which we are checking the given
1897/// template parameter list.
1898///
Douglas Gregordba32632009-02-10 19:49:53 +00001899/// \returns true if an error occurred, false otherwise.
1900bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001901 TemplateParameterList *OldParams,
1902 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001903 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001904
Douglas Gregordba32632009-02-10 19:49:53 +00001905 // C++ [temp.param]p10:
1906 // The set of default template-arguments available for use with a
1907 // template declaration or definition is obtained by merging the
1908 // default arguments from the definition (if in scope) and all
1909 // declarations in scope in the same way default function
1910 // arguments are (8.3.6).
1911 bool SawDefaultArgument = false;
1912 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001913
Mike Stumpc89c8e32009-02-11 23:03:27 +00001914 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001915 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001916 if (OldParams)
1917 OldParam = OldParams->begin();
1918
Douglas Gregor0693def2011-01-27 01:40:17 +00001919 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00001920 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1921 NewParamEnd = NewParams->end();
1922 NewParam != NewParamEnd; ++NewParam) {
1923 // Variables used to diagnose redundant default arguments
1924 bool RedundantDefaultArg = false;
1925 SourceLocation OldDefaultLoc;
1926 SourceLocation NewDefaultLoc;
1927
David Blaikie651c73c2011-10-19 05:19:50 +00001928 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00001929 bool MissingDefaultArg = false;
1930
David Blaikie651c73c2011-10-19 05:19:50 +00001931 // Variable used to diagnose non-final parameter packs
1932 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00001933
Douglas Gregordba32632009-02-10 19:49:53 +00001934 if (TemplateTypeParmDecl *NewTypeParm
1935 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001936 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001937 if (NewTypeParm->hasDefaultArgument() &&
1938 DiagnoseDefaultTemplateArgument(*this, TPC,
1939 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001940 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001941 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001942 NewTypeParm->removeDefaultArgument();
1943
1944 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001945 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001946 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Anders Carlsson327865d2009-06-12 23:20:15 +00001947 if (NewTypeParm->isParameterPack()) {
1948 assert(!NewTypeParm->hasDefaultArgument() &&
1949 "Parameter packs can't have a default argument!");
1950 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001951 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
John McCall0ad16662009-10-29 08:12:44 +00001952 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001953 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1954 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1955 SawDefaultArgument = true;
1956 RedundantDefaultArg = true;
1957 PreviousDefaultArgLoc = NewDefaultLoc;
1958 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1959 // Merge the default argument from the old declaration to the
1960 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001961 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001962 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1963 } else if (NewTypeParm->hasDefaultArgument()) {
1964 SawDefaultArgument = true;
1965 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1966 } else if (SawDefaultArgument)
1967 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001968 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001969 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001970 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001971 if (!NewNonTypeParm->isParameterPack() &&
1972 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001973 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001974 UPPC_NonTypeTemplateParameterType)) {
1975 Invalid = true;
1976 continue;
1977 }
1978
Douglas Gregored5731f2009-11-25 17:50:39 +00001979 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001980 if (NewNonTypeParm->hasDefaultArgument() &&
1981 DiagnoseDefaultTemplateArgument(*this, TPC,
1982 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001983 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001984 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001985 }
1986
Mike Stump12b8ce12009-08-04 21:02:39 +00001987 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001988 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001989 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001990 if (NewNonTypeParm->isParameterPack()) {
1991 assert(!NewNonTypeParm->hasDefaultArgument() &&
1992 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001993 if (!NewNonTypeParm->isPackExpansion())
1994 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001995 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
Richard Smith35828f12013-07-22 03:31:14 +00001996 NewNonTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001997 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1998 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1999 SawDefaultArgument = true;
2000 RedundantDefaultArg = true;
2001 PreviousDefaultArgLoc = NewDefaultLoc;
2002 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2003 // Merge the default argument from the old declaration to the
2004 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002005 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00002006 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2007 } else if (NewNonTypeParm->hasDefaultArgument()) {
2008 SawDefaultArgument = true;
2009 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2010 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002011 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00002012 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00002013 TemplateTemplateParmDecl *NewTemplateParm
2014 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002015
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002016 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00002017 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002018 Invalid = true;
2019 continue;
2020 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002021
David Blaikie651c73c2011-10-19 05:19:50 +00002022 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002023 if (NewTemplateParm->hasDefaultArgument() &&
2024 DiagnoseDefaultTemplateArgument(*this, TPC,
2025 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002026 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00002027 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00002028
2029 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00002030 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002031 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00002032 if (NewTemplateParm->isParameterPack()) {
2033 assert(!NewTemplateParm->hasDefaultArgument() &&
2034 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00002035 if (!NewTemplateParm->isPackExpansion())
2036 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002037 } else if (OldTemplateParm &&
2038 hasVisibleDefaultArgument(OldTemplateParm) &&
2039 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002040 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2041 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002042 SawDefaultArgument = true;
2043 RedundantDefaultArg = true;
2044 PreviousDefaultArgLoc = NewDefaultLoc;
2045 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2046 // Merge the default argument from the old declaration to the
2047 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002048 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002049 PreviousDefaultArgLoc
2050 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002051 } else if (NewTemplateParm->hasDefaultArgument()) {
2052 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002053 PreviousDefaultArgLoc
2054 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002055 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002056 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00002057 }
2058
Richard Smith1fde8ec2012-09-07 02:06:42 +00002059 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00002060 // If a template parameter of a primary class template or alias template
2061 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002062 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00002063 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2064 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00002065 Diag((*NewParam)->getLocation(),
2066 diag::err_template_param_pack_must_be_last_template_parameter);
2067 Invalid = true;
2068 }
2069
Douglas Gregordba32632009-02-10 19:49:53 +00002070 if (RedundantDefaultArg) {
2071 // C++ [temp.param]p12:
2072 // A template-parameter shall not be given default arguments
2073 // by two different declarations in the same scope.
2074 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2075 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2076 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00002077 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00002078 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002079 // If a template-parameter of a class template has a default
2080 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00002081 // have a default template-argument supplied or be a template parameter
2082 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00002083 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00002084 diag::err_template_param_default_arg_missing);
2085 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2086 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00002087 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00002088 }
2089
2090 // If we have an old template parameter list that we're merging
2091 // in, move on to the next parameter.
2092 if (OldParams)
2093 ++OldParam;
2094 }
2095
Douglas Gregor0693def2011-01-27 01:40:17 +00002096 // We were missing some default arguments at the end of the list, so remove
2097 // all of the default arguments.
2098 if (RemoveDefaultArguments) {
2099 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2100 NewParamEnd = NewParams->end();
2101 NewParam != NewParamEnd; ++NewParam) {
2102 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2103 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002104 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00002105 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2106 NTTP->removeDefaultArgument();
2107 else
2108 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2109 }
2110 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002111
Douglas Gregordba32632009-02-10 19:49:53 +00002112 return Invalid;
2113}
Douglas Gregord32e0282009-02-09 23:23:08 +00002114
John McCalla020a012010-10-20 05:44:58 +00002115namespace {
2116
2117/// A class which looks for a use of a certain level of template
2118/// parameter.
2119struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2120 typedef RecursiveASTVisitor<DependencyChecker> super;
2121
2122 unsigned Depth;
Richard Smith57aae072016-12-28 02:37:25 +00002123
2124 // Whether we're looking for a use of a template parameter that makes the
2125 // overall construct type-dependent / a dependent type. This is strictly
2126 // best-effort for now; we may fail to match at all for a dependent type
2127 // in some cases if this is set.
2128 bool IgnoreNonTypeDependent;
2129
John McCalla020a012010-10-20 05:44:58 +00002130 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00002131 SourceLocation MatchLoc;
2132
Richard Smith13894182017-04-13 21:37:24 +00002133 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2134 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2135 Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00002136
Richard Smith57aae072016-12-28 02:37:25 +00002137 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
Richard Smith13894182017-04-13 21:37:24 +00002138 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2139 NamedDecl *ND = Params->getParam(0);
2140 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2141 Depth = PD->getDepth();
2142 } else if (NonTypeTemplateParmDecl *PD =
2143 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2144 Depth = PD->getDepth();
2145 } else {
2146 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2147 }
2148 }
John McCalla020a012010-10-20 05:44:58 +00002149
Richard Smith6056d5e2014-02-09 00:54:43 +00002150 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
Richard Smith13894182017-04-13 21:37:24 +00002151 if (ParmDepth >= Depth) {
John McCalla020a012010-10-20 05:44:58 +00002152 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00002153 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00002154 return true;
2155 }
2156 return false;
2157 }
2158
Richard Smith57aae072016-12-28 02:37:25 +00002159 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2160 // Prune out non-type-dependent expressions if requested. This can
2161 // sometimes result in us failing to find a template parameter reference
2162 // (if a value-dependent expression creates a dependent type), but this
2163 // mode is best-effort only.
2164 if (auto *E = dyn_cast_or_null<Expr>(S))
2165 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2166 return true;
2167 return super::TraverseStmt(S, Q);
2168 }
2169
2170 bool TraverseTypeLoc(TypeLoc TL) {
2171 if (IgnoreNonTypeDependent && !TL.isNull() &&
2172 !TL.getType()->isDependentType())
2173 return true;
2174 return super::TraverseTypeLoc(TL);
2175 }
2176
Richard Smith6056d5e2014-02-09 00:54:43 +00002177 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2178 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2179 }
2180
John McCalla020a012010-10-20 05:44:58 +00002181 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
Richard Smith57aae072016-12-28 02:37:25 +00002182 // For a best-effort search, keep looking until we find a location.
2183 return IgnoreNonTypeDependent || !Matches(T->getDepth());
John McCalla020a012010-10-20 05:44:58 +00002184 }
2185
2186 bool TraverseTemplateName(TemplateName N) {
2187 if (TemplateTemplateParmDecl *PD =
2188 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00002189 if (Matches(PD->getDepth()))
2190 return false;
John McCalla020a012010-10-20 05:44:58 +00002191 return super::TraverseTemplateName(N);
2192 }
2193
2194 bool VisitDeclRefExpr(DeclRefExpr *E) {
2195 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00002196 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2197 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00002198 return false;
John McCalla020a012010-10-20 05:44:58 +00002199 return super::VisitDeclRefExpr(E);
2200 }
Richard Smith6056d5e2014-02-09 00:54:43 +00002201
2202 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2203 return TraverseType(T->getReplacementType());
2204 }
2205
2206 bool
2207 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2208 return TraverseTemplateArgument(T->getArgumentPack());
2209 }
2210
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00002211 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2212 return TraverseType(T->getInjectedSpecializationType());
2213 }
John McCalla020a012010-10-20 05:44:58 +00002214};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002215} // end anonymous namespace
John McCalla020a012010-10-20 05:44:58 +00002216
Douglas Gregor972fe532011-05-10 18:27:06 +00002217/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00002218/// list.
2219static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00002220DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
Richard Smith57aae072016-12-28 02:37:25 +00002221 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
Douglas Gregor972fe532011-05-10 18:27:06 +00002222 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00002223 return Checker.Match;
2224}
2225
Douglas Gregor972fe532011-05-10 18:27:06 +00002226// Find the source range corresponding to the named type in the given
2227// nested-name-specifier, if any.
2228static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2229 QualType T,
2230 const CXXScopeSpec &SS) {
2231 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2232 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2233 if (const Type *CurType = NNS->getAsType()) {
2234 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2235 return NNSLoc.getTypeLoc().getSourceRange();
2236 } else
2237 break;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002238
Douglas Gregor972fe532011-05-10 18:27:06 +00002239 NNSLoc = NNSLoc.getPrefix();
2240 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002241
Douglas Gregor972fe532011-05-10 18:27:06 +00002242 return SourceRange();
2243}
2244
Mike Stump11289f42009-09-09 15:08:12 +00002245/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00002246/// specifier, returning the template parameter list that applies to the
2247/// name.
2248///
2249/// \param DeclStartLoc the start of the declaration that has a scope
2250/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00002251///
Douglas Gregor972fe532011-05-10 18:27:06 +00002252/// \param DeclLoc The location of the declaration itself.
2253///
Douglas Gregord8d297c2009-07-21 23:53:31 +00002254/// \param SS the scope specifier that will be matched to the given template
2255/// parameter lists. This scope specifier precedes a qualified name that is
2256/// being declared.
2257///
Richard Smith4b55a9c2014-04-17 03:29:33 +00002258/// \param TemplateId The template-id following the scope specifier, if there
2259/// is one. Used to check for a missing 'template<>'.
2260///
Douglas Gregord8d297c2009-07-21 23:53:31 +00002261/// \param ParamLists the template parameter lists, from the outermost to the
2262/// innermost template parameter lists.
2263///
John McCalle820e5e2010-04-13 20:37:33 +00002264/// \param IsFriend Whether to apply the slightly different rules for
2265/// matching template parameters to scope specifiers in friend
2266/// declarations.
2267///
Richard Smithf445f192017-02-09 21:04:43 +00002268/// \param IsMemberSpecialization will be set true if the scope specifier
2269/// denotes a fully-specialized type, and therefore this is a declaration of
2270/// a member specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002271///
Mike Stump11289f42009-09-09 15:08:12 +00002272/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00002273/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00002274/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00002275/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00002276/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00002277/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002278TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2279 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00002280 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002281 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
Richard Smithf445f192017-02-09 21:04:43 +00002282 bool &IsMemberSpecialization, bool &Invalid) {
2283 IsMemberSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00002284 Invalid = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002285
Douglas Gregor972fe532011-05-10 18:27:06 +00002286 // The sequence of nested types to which we will match up the template
2287 // parameter lists. We first build this list by starting with the type named
2288 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002289 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00002290 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00002291 if (SS.getScopeRep()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002292 if (CXXRecordDecl *Record
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00002293 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2294 T = Context.getTypeDeclType(Record);
2295 else
2296 T = QualType(SS.getScopeRep()->getAsType(), 0);
2297 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002298
Douglas Gregor972fe532011-05-10 18:27:06 +00002299 // If we found an explicit specialization that prevents us from needing
2300 // 'template<>' headers, this will be set to the location of that
2301 // explicit specialization.
2302 SourceLocation ExplicitSpecLoc;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002303
Douglas Gregor972fe532011-05-10 18:27:06 +00002304 while (!T.isNull()) {
2305 NestedTypes.push_back(T);
Simon Pilgrim6905d222016-12-30 22:55:33 +00002306
Douglas Gregor972fe532011-05-10 18:27:06 +00002307 // Retrieve the parent of a record type.
2308 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2309 // If this type is an explicit specialization, we're done.
2310 if (ClassTemplateSpecializationDecl *Spec
2311 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002312 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002313 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2314 ExplicitSpecLoc = Spec->getLocation();
2315 break;
Douglas Gregor65911492009-11-23 12:11:45 +00002316 }
Douglas Gregor972fe532011-05-10 18:27:06 +00002317 } else if (Record->getTemplateSpecializationKind()
2318 == TSK_ExplicitSpecialization) {
2319 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00002320 break;
2321 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002322
Douglas Gregor972fe532011-05-10 18:27:06 +00002323 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2324 T = Context.getTypeDeclType(Parent);
2325 else
2326 T = QualType();
2327 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002328 }
2329
Douglas Gregor972fe532011-05-10 18:27:06 +00002330 if (const TemplateSpecializationType *TST
2331 = T->getAs<TemplateSpecializationType>()) {
2332 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2333 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2334 T = Context.getTypeDeclType(Parent);
2335 else
2336 T = QualType();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002337 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002338 }
Douglas Gregor972fe532011-05-10 18:27:06 +00002339 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002340
Douglas Gregor972fe532011-05-10 18:27:06 +00002341 // Look one step prior in a dependent template specialization type.
2342 if (const DependentTemplateSpecializationType *DependentTST
2343 = T->getAs<DependentTemplateSpecializationType>()) {
2344 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2345 T = QualType(NNS->getAsType(), 0);
2346 else
2347 T = QualType();
2348 continue;
2349 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002350
Douglas Gregor972fe532011-05-10 18:27:06 +00002351 // Look one step prior in a dependent name type.
2352 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2353 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2354 T = QualType(NNS->getAsType(), 0);
2355 else
2356 T = QualType();
2357 continue;
2358 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002359
Douglas Gregor972fe532011-05-10 18:27:06 +00002360 // Retrieve the parent of an enumeration type.
2361 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2362 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2363 // check here.
2364 EnumDecl *Enum = EnumT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002365
Douglas Gregor972fe532011-05-10 18:27:06 +00002366 // Get to the parent type.
2367 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2368 T = Context.getTypeDeclType(Parent);
2369 else
Simon Pilgrim6905d222016-12-30 22:55:33 +00002370 T = QualType();
Douglas Gregor972fe532011-05-10 18:27:06 +00002371 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002372 }
Mike Stump11289f42009-09-09 15:08:12 +00002373
Douglas Gregor972fe532011-05-10 18:27:06 +00002374 T = QualType();
2375 }
2376 // Reverse the nested types list, since we want to traverse from the outermost
2377 // to the innermost while checking template-parameter-lists.
2378 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00002379
Douglas Gregor972fe532011-05-10 18:27:06 +00002380 // C++0x [temp.expl.spec]p17:
2381 // A member or a member template may be nested within many
2382 // enclosing class templates. In an explicit specialization for
2383 // such a member, the member declaration shall be preceded by a
2384 // template<> for each enclosing class template that is
2385 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002386 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00002387
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002388 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00002389 if (SawNonEmptyTemplateParameterList) {
2390 Diag(DeclLoc, diag::err_specialize_member_of_template)
2391 << !Recovery << Range;
2392 Invalid = true;
Richard Smithf445f192017-02-09 21:04:43 +00002393 IsMemberSpecialization = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00002394 return true;
2395 }
2396
2397 return false;
2398 };
2399
2400 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2401 // Check that we can have an explicit specialization here.
2402 if (CheckExplicitSpecialization(Range, true))
2403 return true;
2404
2405 // We don't have a template header, but we should.
2406 SourceLocation ExpectedTemplateLoc;
2407 if (!ParamLists.empty())
2408 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2409 else
2410 ExpectedTemplateLoc = DeclStartLoc;
2411
2412 Diag(DeclLoc, diag::err_template_spec_needs_header)
2413 << Range
2414 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2415 return false;
2416 };
2417
Douglas Gregor972fe532011-05-10 18:27:06 +00002418 unsigned ParamIdx = 0;
2419 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2420 ++TypeIdx) {
2421 T = NestedTypes[TypeIdx];
Simon Pilgrim6905d222016-12-30 22:55:33 +00002422
Douglas Gregor972fe532011-05-10 18:27:06 +00002423 // Whether we expect a 'template<>' header.
2424 bool NeedEmptyTemplateHeader = false;
2425
2426 // Whether we expect a template header with parameters.
2427 bool NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002428
Douglas Gregor972fe532011-05-10 18:27:06 +00002429 // For a dependent type, the set of template parameters that we
2430 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00002431 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002432
Douglas Gregor373af9b2011-05-11 23:26:17 +00002433 // C++0x [temp.expl.spec]p15:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002434 // A member or a member template may be nested within many enclosing
2435 // class templates. In an explicit specialization for such a member, the
2436 // member declaration shall be preceded by a template<> for each
Douglas Gregor373af9b2011-05-11 23:26:17 +00002437 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00002438 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2439 if (ClassTemplatePartialSpecializationDecl *Partial
2440 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2441 ExpectedTemplateParams = Partial->getTemplateParameters();
2442 NeedNonemptyTemplateHeader = true;
2443 } else if (Record->isDependentType()) {
2444 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00002445 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00002446 ->getTemplateParameters();
2447 NeedNonemptyTemplateHeader = true;
2448 }
2449 } else if (ClassTemplateSpecializationDecl *Spec
2450 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2451 // C++0x [temp.expl.spec]p4:
2452 // Members of an explicitly specialized class template are defined
Simon Pilgrim6905d222016-12-30 22:55:33 +00002453 // in the same manner as members of normal classes, and not using
2454 // the template<> syntax.
Douglas Gregor972fe532011-05-10 18:27:06 +00002455 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2456 NeedEmptyTemplateHeader = true;
2457 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00002458 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002459 } else if (Record->getTemplateSpecializationKind()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002460 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00002461 != TSK_ExplicitSpecialization &&
2462 TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002463 IsMemberSpecialization = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002464
Douglas Gregor373af9b2011-05-11 23:26:17 +00002465 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002466 }
2467 } else if (const TemplateSpecializationType *TST
2468 = T->getAs<TemplateSpecializationType>()) {
Nico Weber28900612015-01-30 02:35:21 +00002469 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002470 ExpectedTemplateParams = Template->getTemplateParameters();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002471 NeedNonemptyTemplateHeader = true;
Douglas Gregor972fe532011-05-10 18:27:06 +00002472 }
2473 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2474 // FIXME: We actually could/should check the template arguments here
2475 // against the corresponding template parameter list.
2476 NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002477 }
2478
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002479 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002480 // In an explicit specialization declaration for a member of a class
2481 // template or a member template that ap- pears in namespace scope, the
2482 // member template and some of its enclosing class templates may remain
2483 // unspecialized, except that the declaration shall not explicitly
2484 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002485 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002486 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002487 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002488 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2489 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002490 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002491 } else
2492 SawNonEmptyTemplateParameterList = true;
2493 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002494
Douglas Gregor972fe532011-05-10 18:27:06 +00002495 if (NeedEmptyTemplateHeader) {
2496 // If we're on the last of the types, and we need a 'template<>' header
Richard Smithf445f192017-02-09 21:04:43 +00002497 // here, then it's a member specialization.
Douglas Gregor972fe532011-05-10 18:27:06 +00002498 if (TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002499 IsMemberSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002500
2501 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002502 if (ParamLists[ParamIdx]->size() > 0) {
2503 // The header has template parameters when it shouldn't. Complain.
Simon Pilgrim6905d222016-12-30 22:55:33 +00002504 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregor972fe532011-05-10 18:27:06 +00002505 diag::err_template_param_list_matches_nontemplate)
2506 << T
2507 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2508 ParamLists[ParamIdx]->getRAngleLoc())
2509 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2510 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002511 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002512 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002513
Douglas Gregor972fe532011-05-10 18:27:06 +00002514 // Consume this template header.
2515 ++ParamIdx;
2516 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002517 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002518
2519 if (!IsFriend)
2520 if (DiagnoseMissingExplicitSpecialization(
2521 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00002522 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002523
Douglas Gregor972fe532011-05-10 18:27:06 +00002524 continue;
2525 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002526
Douglas Gregor972fe532011-05-10 18:27:06 +00002527 if (NeedNonemptyTemplateHeader) {
2528 // In friend declarations we can have template-ids which don't
2529 // depend on the corresponding template parameter lists. But
2530 // assume that empty parameter lists are supposed to match this
2531 // template-id.
2532 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002533 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002534 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00002535 ExpectedTemplateParams = nullptr;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002536 else
Douglas Gregor972fe532011-05-10 18:27:06 +00002537 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002538 }
Douglas Gregored5731f2009-11-25 17:50:39 +00002539
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002540 if (ParamIdx < ParamLists.size()) {
2541 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00002542 if (ExpectedTemplateParams &&
2543 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2544 ExpectedTemplateParams,
2545 true, TPL_TemplateMatch))
2546 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002547
Douglas Gregor972fe532011-05-10 18:27:06 +00002548 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00002549 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00002550 TPC_ClassTemplateMember))
2551 Invalid = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002552
Douglas Gregor972fe532011-05-10 18:27:06 +00002553 ++ParamIdx;
2554 continue;
2555 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002556
Douglas Gregor972fe532011-05-10 18:27:06 +00002557 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2558 << T
2559 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2560 Invalid = true;
2561 continue;
2562 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00002563 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00002564
Douglas Gregord8d297c2009-07-21 23:53:31 +00002565 // If there were at least as many template-ids as there were template
2566 // parameter lists, then there are no template parameter lists remaining for
2567 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00002568 if (ParamIdx >= ParamLists.size()) {
2569 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00002570 // We don't have a template header for the declaration itself, but we
2571 // should.
Richard Smith11a80dc2014-04-17 03:52:20 +00002572 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2573 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00002574
2575 // Fabricate an empty template parameter list for the invented header.
2576 return TemplateParameterList::Create(Context, SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +00002577 SourceLocation(), None,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00002578 SourceLocation(), nullptr);
Richard Smith4b55a9c2014-04-17 03:29:33 +00002579 }
2580
Craig Topperc3ec1492014-05-26 06:22:03 +00002581 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002582 }
Mike Stump11289f42009-09-09 15:08:12 +00002583
Douglas Gregord8d297c2009-07-21 23:53:31 +00002584 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002585 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002586 bool HasAnyExplicitSpecHeader = false;
2587 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002588 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002589 if (ParamLists[I]->size() == 0)
2590 HasAnyExplicitSpecHeader = true;
2591 else
2592 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002593 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002594
Douglas Gregor972fe532011-05-10 18:27:06 +00002595 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002596 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2597 : diag::err_template_spec_extra_headers)
2598 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2599 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00002600
2601 // If there was a specialization somewhere, such that 'template<>' is
2602 // not required, and there were any 'template<>' headers, note where the
2603 // specialization occurred.
2604 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
Simon Pilgrim6905d222016-12-30 22:55:33 +00002605 Diag(ExplicitSpecLoc,
Douglas Gregor972fe532011-05-10 18:27:06 +00002606 diag::note_explicit_template_spec_does_not_need_header)
2607 << NestedTypes.back();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002608
Douglas Gregor972fe532011-05-10 18:27:06 +00002609 // We have a template parameter list with no corresponding scope, which
2610 // means that the resulting template declaration can't be instantiated
2611 // properly (we'll end up with dependent nodes when we shouldn't).
2612 if (!AllExplicitSpecHeaders)
2613 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002614 }
Mike Stump11289f42009-09-09 15:08:12 +00002615
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002616 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002617 // In an explicit specialization declaration for a member of a class
2618 // template or a member template that ap- pears in namespace scope, the
2619 // member template and some of its enclosing class templates may remain
2620 // unspecialized, except that the declaration shall not explicitly
2621 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002622 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00002623 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002624 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2625 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002626 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002627
Douglas Gregord8d297c2009-07-21 23:53:31 +00002628 // Return the last template parameter list, which corresponds to the
2629 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002630 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00002631}
2632
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002633void Sema::NoteAllFoundTemplates(TemplateName Name) {
2634 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2635 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002636 << (isa<FunctionTemplateDecl>(Template)
2637 ? 0
2638 : isa<ClassTemplateDecl>(Template)
2639 ? 1
2640 : isa<VarTemplateDecl>(Template)
2641 ? 2
2642 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2643 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002644 return;
2645 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002646
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002647 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002648 for (OverloadedTemplateStorage::iterator I = OST->begin(),
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002649 IEnd = OST->end();
2650 I != IEnd; ++I)
2651 Diag((*I)->getLocation(), diag::note_template_declared_here)
2652 << 0 << (*I)->getDeclName();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002653
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002654 return;
2655 }
2656}
2657
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002658static QualType
2659checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2660 const SmallVectorImpl<TemplateArgument> &Converted,
2661 SourceLocation TemplateLoc,
2662 TemplateArgumentListInfo &TemplateArgs) {
2663 ASTContext &Context = SemaRef.getASTContext();
2664 switch (BTD->getBuiltinTemplateKind()) {
Eric Fiselier6ad68552016-07-01 01:24:09 +00002665 case BTK__make_integer_seq: {
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002666 // Specializations of __make_integer_seq<S, T, N> are treated like
2667 // S<T, 0, ..., N-1>.
2668
2669 // C++14 [inteseq.intseq]p1:
2670 // T shall be an integer type.
2671 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2672 SemaRef.Diag(TemplateArgs[1].getLocation(),
2673 diag::err_integer_sequence_integral_element_type);
2674 return QualType();
2675 }
2676
2677 // C++14 [inteseq.make]p1:
2678 // If N is negative the program is ill-formed.
2679 TemplateArgument NumArgsArg = Converted[2];
2680 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2681 if (NumArgs < 0) {
2682 SemaRef.Diag(TemplateArgs[2].getLocation(),
2683 diag::err_integer_sequence_negative_length);
2684 return QualType();
2685 }
2686
2687 QualType ArgTy = NumArgsArg.getIntegralType();
2688 TemplateArgumentListInfo SyntheticTemplateArgs;
2689 // The type argument gets reused as the first template argument in the
2690 // synthetic template argument list.
2691 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2692 // Expand N into 0 ... N-1.
2693 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2694 I < NumArgs; ++I) {
2695 TemplateArgument TA(Context, I, ArgTy);
Richard Smith7873de02016-08-11 22:25:46 +00002696 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
2697 TA, ArgTy, TemplateArgs[2].getLocation()));
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002698 }
2699 // The first template argument will be reused as the template decl that
2700 // our synthetic template arguments will be applied to.
2701 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2702 TemplateLoc, SyntheticTemplateArgs);
2703 }
Eric Fiselier6ad68552016-07-01 01:24:09 +00002704
2705 case BTK__type_pack_element:
2706 // Specializations of
2707 // __type_pack_element<Index, T_1, ..., T_N>
2708 // are treated like T_Index.
2709 assert(Converted.size() == 2 &&
2710 "__type_pack_element should be given an index and a parameter pack");
2711
2712 // If the Index is out of bounds, the program is ill-formed.
2713 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
2714 llvm::APSInt Index = IndexArg.getAsIntegral();
2715 assert(Index >= 0 && "the index used with __type_pack_element should be of "
2716 "type std::size_t, and hence be non-negative");
2717 if (Index >= Ts.pack_size()) {
2718 SemaRef.Diag(TemplateArgs[0].getLocation(),
2719 diag::err_type_pack_element_out_of_bounds);
2720 return QualType();
2721 }
2722
2723 // We simply return the type at index `Index`.
2724 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
2725 return Nth->getAsType();
2726 }
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002727 llvm_unreachable("unexpected BuiltinTemplateDecl!");
2728}
2729
Douglas Gregordc572a32009-03-30 22:58:21 +00002730QualType Sema::CheckTemplateIdType(TemplateName Name,
2731 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002732 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00002733 DependentTemplateName *DTN
2734 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00002735 if (DTN && DTN->isIdentifier())
2736 // When building a template-id where the template-name is dependent,
2737 // assume the template is a type template. Either our assumption is
2738 // correct, or the code is ill-formed and will be diagnosed when the
2739 // dependent name is substituted.
2740 return Context.getDependentTemplateSpecializationType(ETK_None,
2741 DTN->getQualifier(),
2742 DTN->getIdentifier(),
2743 TemplateArgs);
2744
Douglas Gregordc572a32009-03-30 22:58:21 +00002745 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00002746 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2747 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002748 // We might have a substituted template template parameter pack. If so,
2749 // build a template specialization type for it.
2750 if (Name.getAsSubstTemplateTemplateParmPack())
2751 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002752
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002753 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2754 << Name;
2755 NoteAllFoundTemplates(Name);
2756 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00002757 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002758
Douglas Gregorc40290e2009-03-09 23:48:35 +00002759 // Check that the template argument list is well-formed for this
2760 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002761 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00002762 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00002763 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00002764 return QualType();
2765
Douglas Gregorc40290e2009-03-09 23:48:35 +00002766 QualType CanonType;
2767
Douglas Gregor678d76c2011-07-01 01:22:09 +00002768 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00002769 if (TypeAliasTemplateDecl *AliasTemplate =
2770 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00002771 // Find the canonical type for this type alias template specialization.
2772 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2773 if (Pattern->isInvalidDecl())
2774 return QualType();
2775
2776 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00002777 Converted);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002778
2779 // Only substitute for the innermost template argument list.
2780 MultiLevelTemplateArgumentList TemplateArgLists;
Richard Smith0c4a34b2011-05-14 15:04:18 +00002781 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00002782 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2783 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00002784 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002785
Richard Smith802c4b72012-08-23 06:16:52 +00002786 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002787 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002788 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00002789 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00002790
Richard Smith3f1b5d02011-05-05 21:57:07 +00002791 CanonType = SubstType(Pattern->getUnderlyingType(),
2792 TemplateArgLists, AliasTemplate->getLocation(),
2793 AliasTemplate->getDeclName());
2794 if (CanonType.isNull())
2795 return QualType();
2796 } else if (Name.isDependent() ||
2797 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00002798 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002799 // This class template specialization is a dependent
2800 // type. Therefore, its canonical type is another class template
2801 // specialization type that contains all of the converted
2802 // arguments in canonical form. This ensures that, e.g., A<T> and
2803 // A<T, T> have identical types when A is declared as:
2804 //
2805 // template<typename T, typename U = T> struct A;
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00002806 CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
John McCall2408e322010-04-27 00:57:59 +00002807
2808 // This might work out to be a current instantiation, in which
2809 // case the canonical type needs to be the InjectedClassNameType.
2810 //
2811 // TODO: in theory this could be a simple hashtable lookup; most
2812 // changes to CurContext don't change the set of current
2813 // instantiations.
2814 if (isa<ClassTemplateDecl>(Template)) {
2815 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2816 // If we get out to a namespace, we're done.
2817 if (Ctx->isFileContext()) break;
2818
2819 // If this isn't a record, keep looking.
2820 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2821 if (!Record) continue;
2822
2823 // Look for one of the two cases with InjectedClassNameTypes
2824 // and check whether it's the same template.
2825 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2826 !Record->getDescribedClassTemplate())
2827 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002828
John McCall2408e322010-04-27 00:57:59 +00002829 // Fetch the injected class name type and check whether its
2830 // injected type is equal to the type we just built.
2831 QualType ICNT = Context.getTypeDeclType(Record);
2832 QualType Injected = cast<InjectedClassNameType>(ICNT)
2833 ->getInjectedSpecializationType();
2834
2835 if (CanonType != Injected->getCanonicalTypeInternal())
2836 continue;
2837
2838 // If so, the canonical type of this TST is the injected
2839 // class name type of the record we just found.
2840 assert(ICNT.isCanonical());
2841 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00002842 break;
2843 }
2844 }
Mike Stump11289f42009-09-09 15:08:12 +00002845 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002846 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002847 // Find the class template specialization declaration that
2848 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002849 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002850 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00002851 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002852 if (!Decl) {
2853 // This is the first time we have referenced this class template
2854 // specialization. Create the canonical declaration and add it to
2855 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002856 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002857 ClassTemplate->getTemplatedDecl()->getTagKind(),
2858 ClassTemplate->getDeclContext(),
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002859 ClassTemplate->getTemplatedDecl()->getLocStart(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002860 ClassTemplate->getLocation(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002861 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00002862 Converted, nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00002863 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00002864 if (ClassTemplate->isOutOfLine())
2865 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00002866 }
2867
Erich Keanea32910d2017-03-23 18:51:54 +00002868 if (Decl->getSpecializationKind() == TSK_Undeclared) {
2869 MultiLevelTemplateArgumentList TemplateArgLists;
2870 TemplateArgLists.addOuterTemplateArguments(Converted);
2871 InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(),
2872 Decl);
2873 }
2874
Chandler Carruth2acfb222013-09-27 22:14:40 +00002875 // Diagnose uses of this specialization.
2876 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2877
Douglas Gregorc40290e2009-03-09 23:48:35 +00002878 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00002879 assert(isa<RecordType>(CanonType) &&
2880 "type of non-dependent specialization is not a RecordType");
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002881 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
2882 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
2883 TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002884 }
Mike Stump11289f42009-09-09 15:08:12 +00002885
Douglas Gregorc40290e2009-03-09 23:48:35 +00002886 // Build the fully-sugared type for this class template
2887 // specialization, which refers back to the class template
2888 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00002889 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002890}
2891
John McCallfaf5fb42010-08-26 23:41:50 +00002892TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002893Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Richard Smith74f02342017-01-19 21:00:13 +00002894 TemplateTy TemplateD, IdentifierInfo *TemplateII,
2895 SourceLocation TemplateIILoc,
Mike Stump11289f42009-09-09 15:08:12 +00002896 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00002897 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002898 SourceLocation RAngleLoc,
Richard Smith62559bd2017-02-01 21:36:38 +00002899 bool IsCtorOrDtorName, bool IsClassName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002900 if (SS.isInvalid())
2901 return true;
2902
Richard Smith62559bd2017-02-01 21:36:38 +00002903 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
2904 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
2905
2906 // C++ [temp.res]p3:
2907 // A qualified-id that refers to a type and in which the
2908 // nested-name-specifier depends on a template-parameter (14.6.2)
2909 // shall be prefixed by the keyword typename to indicate that the
2910 // qualified-id denotes a type, forming an
2911 // elaborated-type-specifier (7.1.5.3).
2912 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
Richard Smith3411fbf2017-02-01 21:41:18 +00002913 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
Richard Smith62559bd2017-02-01 21:36:38 +00002914 << SS.getScopeRep() << TemplateII->getName();
2915 // Recover as if 'typename' were specified.
2916 // FIXME: This is not quite correct recovery as we don't transform SS
2917 // into the corresponding dependent form (and we don't diagnose missing
2918 // 'template' keywords within SS as a result).
2919 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
2920 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
2921 TemplateArgsIn, RAngleLoc);
2922 }
2923
2924 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
2925 // it's not actually allowed to be used as a type in most cases. Because
2926 // we annotate it before we know whether it's valid, we have to check for
2927 // this case here.
2928 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
Richard Smith74f02342017-01-19 21:00:13 +00002929 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
2930 Diag(TemplateIILoc,
2931 TemplateKWLoc.isInvalid()
2932 ? diag::err_out_of_line_qualified_id_type_names_constructor
2933 : diag::ext_out_of_line_qualified_id_type_names_constructor)
2934 << TemplateII << 0 /*injected-class-name used as template name*/
2935 << 1 /*if any keyword was present, it was 'template'*/;
2936 }
2937 }
2938
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002939 TemplateName Template = TemplateD.get();
Douglas Gregor8bf42052009-02-09 18:46:07 +00002940
Douglas Gregorc40290e2009-03-09 23:48:35 +00002941 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00002942 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002943 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00002944
Douglas Gregor5a064722011-02-28 17:23:35 +00002945 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00002946 QualType T
2947 = Context.getDependentTemplateSpecializationType(ETK_None,
2948 DTN->getQualifier(),
2949 DTN->getIdentifier(),
2950 TemplateArgs);
2951 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00002952 TypeLocBuilder TLB;
2953 DependentTemplateSpecializationTypeLoc SpecTL
2954 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002955 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2956 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002957 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00002958 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002959 SpecTL.setLAngleLoc(LAngleLoc);
2960 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002961 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2962 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2963 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2964 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002965
Richard Smith74f02342017-01-19 21:00:13 +00002966 QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002967 if (Result.isNull())
2968 return true;
2969
Douglas Gregore7c20652011-03-02 00:47:37 +00002970 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002971 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00002972 TemplateSpecializationTypeLoc SpecTL
2973 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002974 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00002975 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002976 SpecTL.setLAngleLoc(LAngleLoc);
2977 SpecTL.setRAngleLoc(RAngleLoc);
2978 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2979 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00002980
Abramo Bagnara4244b432012-01-27 08:46:19 +00002981 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2982 // constructor or destructor name (in such a case, the scope specifier
2983 // will be attached to the enclosing Decl or Expr node).
2984 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002985 // Create an elaborated-type-specifier containing the nested-name-specifier.
2986 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2987 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002988 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00002989 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2990 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002991
Douglas Gregore7c20652011-03-02 00:47:37 +00002992 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00002993}
John McCall06f6fe8d2009-09-04 01:14:41 +00002994
Douglas Gregore7c20652011-03-02 00:47:37 +00002995TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00002996 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00002997 SourceLocation TagLoc,
2998 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002999 SourceLocation TemplateKWLoc,
3000 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00003001 SourceLocation TemplateLoc,
3002 SourceLocation LAngleLoc,
3003 ASTTemplateArgsPtr TemplateArgsIn,
3004 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003005 TemplateName Template = TemplateD.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00003006
Douglas Gregore7c20652011-03-02 00:47:37 +00003007 // Translate the parser's template argument list in our AST format.
3008 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3009 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003010
Douglas Gregore7c20652011-03-02 00:47:37 +00003011 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00003012 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00003013 ElaboratedTypeKeyword Keyword
3014 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00003015
Douglas Gregore7c20652011-03-02 00:47:37 +00003016 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3017 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
Simon Pilgrim6905d222016-12-30 22:55:33 +00003018 DTN->getQualifier(),
3019 DTN->getIdentifier(),
Douglas Gregore7c20652011-03-02 00:47:37 +00003020 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003021
3022 // Build type-source information.
Douglas Gregore7c20652011-03-02 00:47:37 +00003023 TypeLocBuilder TLB;
3024 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003025 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3026 SpecTL.setElaboratedKeywordLoc(TagLoc);
3027 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00003028 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003029 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003030 SpecTL.setLAngleLoc(LAngleLoc);
3031 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003032 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3033 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3034 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3035 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00003036
3037 if (TypeAliasTemplateDecl *TAT =
3038 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3039 // C++0x [dcl.type.elab]p2:
3040 // If the identifier resolves to a typedef-name or the simple-template-id
3041 // resolves to an alias template specialization, the
3042 // elaborated-type-specifier is ill-formed.
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00003043 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3044 << TAT << NTK_TypeAliasTemplate << TagKind;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003045 Diag(TAT->getLocation(), diag::note_declared_at);
3046 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003047
Douglas Gregore7c20652011-03-02 00:47:37 +00003048 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3049 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00003050 return TypeResult(true);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003051
Douglas Gregore7c20652011-03-02 00:47:37 +00003052 // Check the tag kind
3053 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00003054 RecordDecl *D = RT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00003055
John McCalld8fe9af2009-09-08 17:47:29 +00003056 IdentifierInfo *Id = D->getIdentifier();
3057 assert(Id && "templated class must have an identifier");
Simon Pilgrim6905d222016-12-30 22:55:33 +00003058
Richard Trieucaa33d32011-06-10 03:11:26 +00003059 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00003060 TagLoc, Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00003061 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00003062 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00003063 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00003064 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00003065 }
3066 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003067
Douglas Gregore7c20652011-03-02 00:47:37 +00003068 // Provide source-location information for the template specialization.
3069 TypeLocBuilder TLB;
3070 TemplateSpecializationTypeLoc SpecTL
3071 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003072 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003073 SpecTL.setTemplateNameLoc(TemplateLoc);
3074 SpecTL.setLAngleLoc(LAngleLoc);
3075 SpecTL.setRAngleLoc(RAngleLoc);
3076 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3077 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00003078
Douglas Gregore7c20652011-03-02 00:47:37 +00003079 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003080 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00003081 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3082 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00003083 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003084 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3085 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003086}
3087
Larisse Voufo39a1e502013-08-06 01:03:05 +00003088static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3089 NamedDecl *PrevDecl,
3090 SourceLocation Loc,
3091 bool IsPartialSpecialization);
3092
3093static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003094
Richard Smith300e0c32013-09-24 04:49:23 +00003095static bool isTemplateArgumentTemplateParameter(
3096 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3097 switch (Arg.getKind()) {
3098 case TemplateArgument::Null:
3099 case TemplateArgument::NullPtr:
3100 case TemplateArgument::Integral:
3101 case TemplateArgument::Declaration:
3102 case TemplateArgument::Pack:
3103 case TemplateArgument::TemplateExpansion:
3104 return false;
3105
3106 case TemplateArgument::Type: {
3107 QualType Type = Arg.getAsType();
3108 const TemplateTypeParmType *TPT =
3109 Arg.getAsType()->getAs<TemplateTypeParmType>();
3110 return TPT && !Type.hasQualifiers() &&
3111 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3112 }
3113
3114 case TemplateArgument::Expression: {
3115 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3116 if (!DRE || !DRE->getDecl())
3117 return false;
3118 const NonTypeTemplateParmDecl *NTTP =
3119 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3120 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3121 }
3122
3123 case TemplateArgument::Template:
3124 const TemplateTemplateParmDecl *TTP =
3125 dyn_cast_or_null<TemplateTemplateParmDecl>(
3126 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
3127 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3128 }
3129 llvm_unreachable("unexpected kind of template argument");
3130}
3131
3132static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
3133 ArrayRef<TemplateArgument> Args) {
3134 if (Params->size() != Args.size())
3135 return false;
3136
3137 unsigned Depth = Params->getDepth();
3138
3139 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3140 TemplateArgument Arg = Args[I];
3141
3142 // If the parameter is a pack expansion, the argument must be a pack
3143 // whose only element is a pack expansion.
3144 if (Params->getParam(I)->isParameterPack()) {
3145 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3146 !Arg.pack_begin()->isPackExpansion())
3147 return false;
3148 Arg = Arg.pack_begin()->getPackExpansionPattern();
3149 }
3150
3151 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3152 return false;
3153 }
3154
3155 return true;
3156}
3157
Richard Smith4b55a9c2014-04-17 03:29:33 +00003158/// Convert the parser's template argument list representation into our form.
3159static TemplateArgumentListInfo
3160makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
3161 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
3162 TemplateId.RAngleLoc);
3163 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
3164 TemplateId.NumArgs);
3165 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
3166 return TemplateArgs;
3167}
3168
Richard Smith0e617ec2016-12-27 07:56:27 +00003169template<typename PartialSpecDecl>
3170static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3171 if (Partial->getDeclContext()->isDependentContext())
3172 return;
3173
3174 // FIXME: Get the TDK from deduction in order to provide better diagnostics
3175 // for non-substitution-failure issues?
3176 TemplateDeductionInfo Info(Partial->getLocation());
3177 if (S.isMoreSpecializedThanPrimary(Partial, Info))
3178 return;
3179
3180 auto *Template = Partial->getSpecializedTemplate();
3181 S.Diag(Partial->getLocation(),
Richard Smithfa4a09d2016-12-27 20:03:09 +00003182 diag::ext_partial_spec_not_more_specialized_than_primary)
3183 << isa<VarTemplateDecl>(Template);
Richard Smith0e617ec2016-12-27 07:56:27 +00003184
3185 if (Info.hasSFINAEDiagnostic()) {
3186 PartialDiagnosticAt Diag = {SourceLocation(),
3187 PartialDiagnostic::NullDiagnostic()};
3188 Info.takeSFINAEDiagnostic(Diag);
3189 SmallString<128> SFINAEArgString;
3190 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3191 S.Diag(Diag.first,
3192 diag::note_partial_spec_not_more_specialized_than_primary)
3193 << SFINAEArgString;
3194 }
3195
3196 S.Diag(Template->getLocation(), diag::note_template_decl_here);
3197}
3198
Richard Smith4e05eaa2017-02-16 00:36:47 +00003199static void
3200noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
3201 const llvm::SmallBitVector &DeducibleParams) {
3202 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3203 if (!DeducibleParams[I]) {
3204 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3205 if (Param->getDeclName())
3206 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3207 << Param->getDeclName();
3208 else
3209 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3210 << "(anonymous)";
3211 }
3212 }
3213}
3214
3215
Richard Smith57aae072016-12-28 02:37:25 +00003216template<typename PartialSpecDecl>
3217static void checkTemplatePartialSpecialization(Sema &S,
3218 PartialSpecDecl *Partial) {
3219 // C++1z [temp.class.spec]p8: (DR1495)
3220 // - The specialization shall be more specialized than the primary
3221 // template (14.5.5.2).
3222 checkMoreSpecializedThanPrimary(S, Partial);
3223
3224 // C++ [temp.class.spec]p8: (DR1315)
3225 // - Each template-parameter shall appear at least once in the
3226 // template-id outside a non-deduced context.
3227 // C++1z [temp.class.spec.match]p3 (P0127R2)
3228 // If the template arguments of a partial specialization cannot be
3229 // deduced because of the structure of its template-parameter-list
3230 // and the template-id, the program is ill-formed.
3231 auto *TemplateParams = Partial->getTemplateParameters();
3232 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3233 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3234 TemplateParams->getDepth(), DeducibleParams);
3235
3236 if (!DeducibleParams.all()) {
3237 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3238 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3239 << isa<VarTemplatePartialSpecializationDecl>(Partial)
3240 << (NumNonDeducible > 1)
3241 << SourceRange(Partial->getLocation(),
3242 Partial->getTemplateArgsAsWritten()->RAngleLoc);
Richard Smith4e05eaa2017-02-16 00:36:47 +00003243 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
Richard Smith57aae072016-12-28 02:37:25 +00003244 }
3245}
3246
3247void Sema::CheckTemplatePartialSpecialization(
3248 ClassTemplatePartialSpecializationDecl *Partial) {
3249 checkTemplatePartialSpecialization(*this, Partial);
3250}
3251
3252void Sema::CheckTemplatePartialSpecialization(
3253 VarTemplatePartialSpecializationDecl *Partial) {
3254 checkTemplatePartialSpecialization(*this, Partial);
3255}
3256
Richard Smith4e05eaa2017-02-16 00:36:47 +00003257void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
3258 // C++1z [temp.param]p11:
3259 // A template parameter of a deduction guide template that does not have a
3260 // default-argument shall be deducible from the parameter-type-list of the
3261 // deduction guide template.
3262 auto *TemplateParams = TD->getTemplateParameters();
3263 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3264 MarkDeducedTemplateParameters(TD, DeducibleParams);
3265 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3266 // A parameter pack is deducible (to an empty pack).
3267 auto *Param = TemplateParams->getParam(I);
3268 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3269 DeducibleParams[I] = true;
3270 }
3271
3272 if (!DeducibleParams.all()) {
3273 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3274 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3275 << (NumNonDeducible > 1);
3276 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3277 }
3278}
3279
Larisse Voufo39a1e502013-08-06 01:03:05 +00003280DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00003281 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00003282 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00003283 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003284 // D must be variable template id.
3285 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
3286 "Variable template specialization is declared with a template it.");
3287
3288 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00003289 TemplateArgumentListInfo TemplateArgs =
3290 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003291 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3292 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3293 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00003294
Richard Smithbeef3452014-01-16 23:39:20 +00003295 TemplateName Name = TemplateId->Template.get();
3296
3297 // The template-id must name a variable template.
3298 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00003299 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3300 if (!VarTemplate) {
3301 NamedDecl *FnTemplate;
3302 if (auto *OTS = Name.getAsOverloadedTemplate())
3303 FnTemplate = *OTS->begin();
3304 else
3305 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3306 if (FnTemplate)
3307 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3308 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00003309 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3310 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00003311 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003312
3313 // Check for unexpanded parameter packs in any of the template arguments.
3314 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3315 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3316 UPPC_PartialSpecialization))
3317 return true;
3318
3319 // Check that the template argument list is well-formed for this
3320 // template.
3321 SmallVector<TemplateArgument, 4> Converted;
3322 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
3323 false, Converted))
3324 return true;
3325
Larisse Voufo39a1e502013-08-06 01:03:05 +00003326 // Find the variable template (partial) specialization declaration that
3327 // corresponds to these arguments.
3328 if (IsPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00003329 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
3330 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00003331 return true;
3332
Richard Smith57aae072016-12-28 02:37:25 +00003333 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
3334 // also do them during instantiation.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003335 bool InstantiationDependent;
3336 if (!Name.isDependent() &&
3337 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00003338 TemplateArgs.arguments(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00003339 InstantiationDependent)) {
3340 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3341 << VarTemplate->getDeclName();
3342 IsPartialSpecialization = false;
3343 }
Richard Smith300e0c32013-09-24 04:49:23 +00003344
3345 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
3346 Converted)) {
3347 // C++ [temp.class.spec]p9b3:
3348 //
3349 // -- The argument list of the specialization shall not be identical
3350 // to the implicit argument list of the primary template.
3351 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3352 << /*variable template*/ 1
3353 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
3354 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
3355 // FIXME: Recover from this by treating the declaration as a redeclaration
3356 // of the primary template.
3357 return true;
3358 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003359 }
3360
Craig Topperc3ec1492014-05-26 06:22:03 +00003361 void *InsertPos = nullptr;
3362 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003363
3364 if (IsPartialSpecialization)
3365 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00003366 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003367 else
Craig Topper7e0daca2014-06-26 04:58:53 +00003368 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003369
Craig Topperc3ec1492014-05-26 06:22:03 +00003370 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003371
3372 // Check whether we can declare a variable template specialization in
3373 // the current scope.
3374 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
3375 TemplateNameLoc,
3376 IsPartialSpecialization))
3377 return true;
3378
3379 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3380 // Since the only prior variable template specialization with these
3381 // arguments was referenced but not declared, reuse that
3382 // declaration node as our own, updating its source location and
3383 // the list of outer template parameters to reflect our new declaration.
3384 Specialization = PrevDecl;
3385 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00003386 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003387 } else if (IsPartialSpecialization) {
3388 // Create a new class template partial specialization declaration node.
3389 VarTemplatePartialSpecializationDecl *PrevPartial =
3390 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003391 VarTemplatePartialSpecializationDecl *Partial =
3392 VarTemplatePartialSpecializationDecl::Create(
3393 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
3394 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
David Majnemer8b622692016-07-03 21:17:51 +00003395 Converted, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003396
3397 if (!PrevPartial)
3398 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
3399 Specialization = Partial;
3400
3401 // If we are providing an explicit specialization of a member variable
3402 // template specialization, make a note of that.
3403 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00003404 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00003405
Richard Smith57aae072016-12-28 02:37:25 +00003406 CheckTemplatePartialSpecialization(Partial);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003407 } else {
3408 // Create a new class template specialization declaration node for
3409 // this explicit specialization or friend declaration.
3410 Specialization = VarTemplateSpecializationDecl::Create(
3411 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
David Majnemer8b622692016-07-03 21:17:51 +00003412 VarTemplate, DI->getType(), DI, SC, Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003413 Specialization->setTemplateArgsInfo(TemplateArgs);
3414
3415 if (!PrevDecl)
3416 VarTemplate->AddSpecialization(Specialization, InsertPos);
3417 }
3418
3419 // C++ [temp.expl.spec]p6:
3420 // If a template, a member template or the member of a class template is
3421 // explicitly specialized then that specialization shall be declared
3422 // before the first use of that specialization that would cause an implicit
3423 // instantiation to take place, in every translation unit in which such a
3424 // use occurs; no diagnostic is required.
3425 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3426 bool Okay = false;
3427 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
3428 // Is there any previous explicit specialization declaration?
3429 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3430 Okay = true;
3431 break;
3432 }
3433 }
3434
3435 if (!Okay) {
3436 SourceRange Range(TemplateNameLoc, RAngleLoc);
3437 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3438 << Name << Range;
3439
3440 Diag(PrevDecl->getPointOfInstantiation(),
3441 diag::note_instantiation_required_here)
3442 << (PrevDecl->getTemplateSpecializationKind() !=
3443 TSK_ImplicitInstantiation);
3444 return true;
3445 }
3446 }
3447
3448 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
3449 Specialization->setLexicalDeclContext(CurContext);
3450
3451 // Add the specialization into its lexical context, so that it can
3452 // be seen when iterating through the list of declarations in that
3453 // context. However, specializations are not found by name lookup.
3454 CurContext->addDecl(Specialization);
3455
3456 // Note that this is an explicit specialization.
3457 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
3458
3459 if (PrevDecl) {
3460 // Check that this isn't a redefinition of this specialization,
3461 // merging with previous declarations.
3462 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
3463 ForRedeclaration);
3464 PrevSpec.addDecl(PrevDecl);
3465 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00003466 } else if (Specialization->isStaticDataMember() &&
3467 Specialization->isOutOfLine()) {
3468 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00003469 }
3470
3471 // Link instantiations of static data members back to the template from
3472 // which they were instantiated.
3473 if (Specialization->isStaticDataMember())
3474 Specialization->setInstantiationOfStaticDataMember(
3475 VarTemplate->getTemplatedDecl(),
3476 Specialization->getSpecializationKind());
3477
3478 return Specialization;
3479}
3480
3481namespace {
3482/// \brief A partial specialization whose template arguments have matched
3483/// a given template-id.
3484struct PartialSpecMatchResult {
3485 VarTemplatePartialSpecializationDecl *Partial;
3486 TemplateArgumentList *Args;
3487};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003488} // end anonymous namespace
Larisse Voufo39a1e502013-08-06 01:03:05 +00003489
3490DeclResult
3491Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
3492 SourceLocation TemplateNameLoc,
3493 const TemplateArgumentListInfo &TemplateArgs) {
3494 assert(Template && "A variable template id without template?");
3495
3496 // Check that the template argument list is well-formed for this template.
3497 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003498 if (CheckTemplateArgumentList(
3499 Template, TemplateNameLoc,
3500 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00003501 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00003502 return true;
3503
3504 // Find the variable template specialization declaration that
3505 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00003506 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003507 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Richard Smith6739a102016-05-05 00:56:12 +00003508 Converted, InsertPos)) {
3509 checkSpecializationVisibility(TemplateNameLoc, Spec);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003510 // If we already have a variable template specialization, return it.
3511 return Spec;
Richard Smith6739a102016-05-05 00:56:12 +00003512 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003513
3514 // This is the first time we have referenced this variable template
3515 // specialization. Create the canonical declaration and add it to
3516 // the set of specializations, based on the closest partial specialization
3517 // that it represents. That is,
3518 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
3519 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00003520 Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003521 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
3522 bool AmbiguousPartialSpec = false;
3523 typedef PartialSpecMatchResult MatchResult;
3524 SmallVector<MatchResult, 4> Matched;
3525 SourceLocation PointOfInstantiation = TemplateNameLoc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003526 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
3527 /*ForTakingAddress=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003528
3529 // 1. Attempt to find the closest partial specialization that this
3530 // specializes, if any.
3531 // If any of the template arguments is dependent, then this is probably
3532 // a placeholder for an incomplete declarative context; which must be
3533 // complete by instantiation time. Thus, do not search through the partial
3534 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00003535 // TODO: Unify with InstantiateClassTemplateSpecialization()?
3536 // Perhaps better after unification of DeduceTemplateArguments() and
3537 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00003538 bool InstantiationDependent = false;
3539 if (!TemplateSpecializationType::anyDependentTemplateArguments(
3540 TemplateArgs, InstantiationDependent)) {
3541
3542 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3543 Template->getPartialSpecializations(PartialSpecs);
3544
3545 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3546 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3547 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3548
3549 if (TemplateDeductionResult Result =
3550 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
3551 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00003552 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00003553 FailedCandidates.addCandidate().set(
3554 DeclAccessPair::make(Template, AS_public), Partial,
3555 MakeDeductionFailureInfo(Context, Result, Info));
Larisse Voufo39a1e502013-08-06 01:03:05 +00003556 (void)Result;
3557 } else {
3558 Matched.push_back(PartialSpecMatchResult());
3559 Matched.back().Partial = Partial;
3560 Matched.back().Args = Info.take();
3561 }
3562 }
3563
Larisse Voufo39a1e502013-08-06 01:03:05 +00003564 if (Matched.size() >= 1) {
3565 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
3566 if (Matched.size() == 1) {
3567 // -- If exactly one matching specialization is found, the
3568 // instantiation is generated from that specialization.
3569 // We don't need to do anything for this.
3570 } else {
3571 // -- If more than one matching specialization is found, the
3572 // partial order rules (14.5.4.2) are used to determine
3573 // whether one of the specializations is more specialized
3574 // than the others. If none of the specializations is more
3575 // specialized than all of the other matching
3576 // specializations, then the use of the variable template is
3577 // ambiguous and the program is ill-formed.
3578 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
3579 PEnd = Matched.end();
3580 P != PEnd; ++P) {
3581 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
3582 PointOfInstantiation) ==
3583 P->Partial)
3584 Best = P;
3585 }
3586
3587 // Determine if the best partial specialization is more specialized than
3588 // the others.
3589 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
3590 PEnd = Matched.end();
3591 P != PEnd; ++P) {
3592 if (P != Best && getMoreSpecializedPartialSpecialization(
3593 P->Partial, Best->Partial,
3594 PointOfInstantiation) != Best->Partial) {
3595 AmbiguousPartialSpec = true;
3596 break;
3597 }
3598 }
3599 }
3600
3601 // Instantiate using the best variable template partial specialization.
3602 InstantiationPattern = Best->Partial;
3603 InstantiationArgs = Best->Args;
3604 } else {
3605 // -- If no match is found, the instantiation is generated
3606 // from the primary template.
3607 // InstantiationPattern = Template->getTemplatedDecl();
3608 }
3609 }
3610
Larisse Voufo39a1e502013-08-06 01:03:05 +00003611 // 2. Create the canonical declaration.
Richard Smith6739a102016-05-05 00:56:12 +00003612 // Note that we do not instantiate a definition until we see an odr-use
3613 // in DoMarkVarDeclReferenced().
Larisse Voufo39a1e502013-08-06 01:03:05 +00003614 // FIXME: LateAttrs et al.?
3615 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
3616 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
3617 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
3618 if (!Decl)
3619 return true;
3620
3621 if (AmbiguousPartialSpec) {
3622 // Partial ordering did not produce a clear winner. Complain.
3623 Decl->setInvalidDecl();
3624 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
3625 << Decl;
3626
3627 // Print the matching partial specializations.
Yaron Keren1cb81462016-11-16 13:45:34 +00003628 for (MatchResult P : Matched)
3629 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
3630 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
3631 *P.Args);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003632 return true;
3633 }
3634
3635 if (VarTemplatePartialSpecializationDecl *D =
3636 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
3637 Decl->setInstantiationOf(D, InstantiationArgs);
3638
Richard Smith6739a102016-05-05 00:56:12 +00003639 checkSpecializationVisibility(TemplateNameLoc, Decl);
3640
Larisse Voufo39a1e502013-08-06 01:03:05 +00003641 assert(Decl && "No variable template specialization?");
3642 return Decl;
3643}
3644
3645ExprResult
3646Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
3647 const DeclarationNameInfo &NameInfo,
3648 VarTemplateDecl *Template, SourceLocation TemplateLoc,
3649 const TemplateArgumentListInfo *TemplateArgs) {
3650
3651 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
3652 *TemplateArgs);
3653 if (Decl.isInvalid())
3654 return ExprError();
3655
3656 VarDecl *Var = cast<VarDecl>(Decl.get());
3657 if (!Var->getTemplateSpecializationKind())
3658 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
3659 NameInfo.getLoc());
3660
3661 // Build an ordinary singleton decl ref.
3662 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00003663 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003664}
3665
John McCalldadc5752010-08-24 06:29:42 +00003666ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003667 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00003668 LookupResult &R,
3669 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003670 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00003671 // FIXME: Can we do any checking at this point? I guess we could check the
3672 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00003673 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00003674 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00003675 // foo<int> could identify a single function unambiguously
3676 // This approach does NOT work, since f<int>(1);
3677 // gets resolved prior to resorting to overload resolution
3678 // i.e., template<class T> void f(double);
3679 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00003680
3681 // These should be filtered out by our callers.
3682 assert(!R.empty() && "empty lookup results when building templateid");
3683 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
3684
Larisse Voufo39a1e502013-08-06 01:03:05 +00003685 // In C++1y, check variable template ids.
Richard Smithd7d11ef2014-02-03 20:09:56 +00003686 bool InstantiationDependent;
3687 if (R.getAsSingle<VarTemplateDecl>() &&
3688 !TemplateSpecializationType::anyDependentTemplateArguments(
3689 *TemplateArgs, InstantiationDependent)) {
3690 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
3691 R.getAsSingle<VarTemplateDecl>(),
3692 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003693 }
3694
John McCall58cc69d2010-01-27 01:50:18 +00003695 // We don't want lookup warnings at this point.
3696 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003697
John McCalle66edc12009-11-24 19:00:30 +00003698 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00003699 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00003700 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003701 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003702 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003703 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00003704 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00003705
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003706 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00003707}
3708
John McCalle66edc12009-11-24 19:00:30 +00003709// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00003710ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003711Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003712 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003713 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003714 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003715
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003716 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00003717 DeclContext *DC;
3718 if (!(DC = computeDeclContext(SS, false)) ||
3719 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00003720 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00003721 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003722
Douglas Gregor786123d2010-05-21 23:18:07 +00003723 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003724 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Craig Topperc3ec1492014-05-26 06:22:03 +00003725 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
Douglas Gregor786123d2010-05-21 23:18:07 +00003726 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00003727
John McCalle66edc12009-11-24 19:00:30 +00003728 if (R.isAmbiguous())
3729 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003730
John McCalle66edc12009-11-24 19:00:30 +00003731 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003732 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
3733 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00003734 return ExprError();
3735 }
3736
3737 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003738 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00003739 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00003740 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00003741 Diag(Temp->getLocation(), diag::note_referenced_class_template);
3742 return ExprError();
3743 }
3744
Abramo Bagnara7945c982012-01-27 09:46:47 +00003745 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00003746}
3747
Douglas Gregorb67535d2009-03-31 00:43:58 +00003748/// \brief Form a dependent template name.
3749///
3750/// This action forms a dependent template name given the template
3751/// name and its (presumably dependent) scope specifier. For
3752/// example, given "MetaFun::template apply", the scope specifier \p
3753/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
3754/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003755TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00003756 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003757 SourceLocation TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00003758 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00003759 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00003760 bool EnteringContext,
Richard Smithfd3dae02017-01-20 00:20:39 +00003761 TemplateTy &Result,
3762 bool AllowInjectedClassName) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00003763 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
3764 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003765 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00003766 diag::warn_cxx98_compat_template_outside_of_template :
3767 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003768 << FixItHint::CreateRemoval(TemplateKWLoc);
3769
Craig Topperc3ec1492014-05-26 06:22:03 +00003770 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00003771 if (SS.isSet())
3772 LookupCtx = computeDeclContext(SS, EnteringContext);
3773 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00003774 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00003775 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00003776 // C++0x [temp.names]p5:
3777 // If a name prefixed by the keyword template is not the name of
3778 // a template, the program is ill-formed. [Note: the keyword
3779 // template may not be applied to non-template members of class
3780 // templates. -end note ] [ Note: as is the case with the
3781 // typename prefix, the template prefix is allowed in cases
3782 // where it is not strictly necessary; i.e., when the
3783 // nested-name-specifier or the expression on the left of the ->
3784 // or . is not dependent on a template-parameter, or the use
3785 // does not appear in the scope of a template. -end note]
3786 //
3787 // Note: C++03 was more strict here, because it banned the use of
3788 // the "template" keyword prior to a template-name that was not a
3789 // dependent name. C++ DR468 relaxed this requirement (the
3790 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00003791 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00003792 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00003793 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00003794 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00003795 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00003796 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
3797 isa<CXXRecordDecl>(LookupCtx) &&
Douglas Gregor5ecbb1b2011-03-11 23:27:41 +00003798 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
3799 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
Douglas Gregorbb119652010-06-16 23:00:59 +00003800 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00003801 } else if (TNK == TNK_Non_template) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003802 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003803 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003804 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003805 << Name.getSourceRange()
3806 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003807 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00003808 } else {
3809 // We found something; return it.
Richard Smithfd3dae02017-01-20 00:20:39 +00003810 auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
3811 if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
3812 Name.getKind() == UnqualifiedId::IK_Identifier && Name.Identifier &&
3813 LookupRD->getIdentifier() == Name.Identifier) {
3814 // C++14 [class.qual]p2:
3815 // In a lookup in which function names are not ignored and the
3816 // nested-name-specifier nominates a class C, if the name specified
3817 // [...] is the injected-class-name of C, [...] the name is instead
3818 // considered to name the constructor
3819 //
3820 // We don't get here if naming the constructor would be valid, so we
3821 // just reject immediately and recover by treating the
3822 // injected-class-name as naming the template.
3823 Diag(Name.getLocStart(),
3824 diag::ext_out_of_line_qualified_id_type_names_constructor)
3825 << Name.Identifier << 0 /*injected-class-name used as template name*/
3826 << 1 /*'template' keyword was used*/;
3827 }
Douglas Gregorbb119652010-06-16 23:00:59 +00003828 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003829 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00003830 }
3831
Aaron Ballman4a979672014-01-03 13:56:08 +00003832 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003833
Douglas Gregor3cf81312009-11-03 23:16:33 +00003834 switch (Name.getKind()) {
3835 case UnqualifiedId::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003836 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00003837 Name.Identifier));
3838 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003839
Douglas Gregor71395fa2009-11-04 00:56:37 +00003840 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00003841 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00003842 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00003843 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00003844
3845 case UnqualifiedId::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00003846 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00003847
Douglas Gregor3cf81312009-11-03 23:16:33 +00003848 default:
3849 break;
3850 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003851
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003852 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003853 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003854 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003855 << Name.getSourceRange()
3856 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003857 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003858}
3859
Mike Stump11289f42009-09-09 15:08:12 +00003860bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003861 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003862 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00003863 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00003864 QualType ArgType;
3865 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00003866
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003867 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003868 switch(Arg.getKind()) {
3869 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003870 // C++ [temp.arg.type]p1:
3871 // A template-argument for a template-parameter which is a
3872 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00003873 ArgType = Arg.getAsType();
3874 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003875 break;
3876 case TemplateArgument::Template: {
3877 // We have a template type parameter but the template argument
3878 // is a template without any arguments.
3879 SourceRange SR = AL.getSourceRange();
3880 TemplateName Name = Arg.getAsTemplate();
3881 Diag(SR.getBegin(), diag::err_template_missing_args)
Richard Smith0c062b42017-01-14 02:19:59 +00003882 << (int)getTemplateNameKindForDiagnostics(Name) << Name << SR;
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003883 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3884 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003885
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003886 return true;
3887 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003888 case TemplateArgument::Expression: {
3889 // We have a template type parameter but the template argument is an
3890 // expression; see if maybe it is missing the "typename" keyword.
3891 CXXScopeSpec SS;
3892 DeclarationNameInfo NameInfo;
3893
3894 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3895 SS.Adopt(ArgExpr->getQualifierLoc());
3896 NameInfo = ArgExpr->getNameInfo();
3897 } else if (DependentScopeDeclRefExpr *ArgExpr =
3898 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3899 SS.Adopt(ArgExpr->getQualifierLoc());
3900 NameInfo = ArgExpr->getNameInfo();
3901 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3902 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003903 if (ArgExpr->isImplicitAccess()) {
3904 SS.Adopt(ArgExpr->getQualifierLoc());
3905 NameInfo = ArgExpr->getMemberNameInfo();
3906 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003907 }
3908
Reid Kleckner377c1592014-06-10 23:29:48 +00003909 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003910 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3911 LookupParsedName(Result, CurScope, &SS);
3912
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003913 if (Result.getAsSingle<TypeDecl>() ||
3914 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00003915 LookupResult::NotFoundInCurrentInstantiation) {
3916 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003917 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00003918 Diag(Loc, getLangOpts().MSVCCompat
3919 ? diag::ext_ms_template_type_arg_missing_typename
3920 : diag::err_template_arg_must_be_type_suggest)
3921 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003922 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00003923
3924 // Recover by synthesizing a type using the location information that we
3925 // already have.
3926 ArgType =
3927 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3928 TypeLocBuilder TLB;
3929 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3930 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3931 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3932 TL.setNameLoc(NameInfo.getLoc());
3933 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3934
3935 // Overwrite our input TemplateArgumentLoc so that we can recover
3936 // properly.
3937 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3938 TemplateArgumentLocInfo(TSI));
3939
3940 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003941 }
3942 }
3943 // fallthrough
3944 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003945 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003946 // We have a template type parameter but the template argument
3947 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00003948 SourceRange SR = AL.getSourceRange();
3949 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003950 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003951
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003952 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003953 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003954 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003955
Reid Kleckner377c1592014-06-10 23:29:48 +00003956 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003957 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003958
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003959 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00003960 ArgType = Context.getCanonicalType(ArgType);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003961
Douglas Gregore46db902011-06-17 22:11:49 +00003962 // Objective-C ARC:
3963 // If an explicitly-specified template argument type is a lifetime type
3964 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003965 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00003966 ArgType->isObjCLifetimeType() &&
3967 !ArgType.getObjCLifetime()) {
3968 Qualifiers Qs;
3969 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3970 ArgType = Context.getQualifiedType(ArgType, Qs);
3971 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003972
Douglas Gregore46db902011-06-17 22:11:49 +00003973 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003974 return false;
3975}
3976
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003977/// \brief Substitute template arguments into the default template argument for
3978/// the given template type parameter.
3979///
3980/// \param SemaRef the semantic analysis object for which we are performing
3981/// the substitution.
3982///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003983/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003984/// for.
3985///
3986/// \param TemplateLoc the location of the template name that started the
3987/// template-id we are checking.
3988///
3989/// \param RAngleLoc the location of the right angle bracket ('>') that
3990/// terminates the template-id.
3991///
3992/// \param Param the template template parameter whose default we are
3993/// substituting into.
3994///
3995/// \param Converted the list of template arguments provided for template
3996/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003997/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00003998static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003999SubstDefaultTemplateArgument(Sema &SemaRef,
4000 TemplateDecl *Template,
4001 SourceLocation TemplateLoc,
4002 SourceLocation RAngleLoc,
4003 TemplateTypeParmDecl *Param,
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00004004 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00004005 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004006
4007 // If the argument type is dependent, instantiate it now based
4008 // on the previously-computed template arguments.
4009 if (ArgType->getType()->isDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004010 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00004011 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004012 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004013 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00004014 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004015
David Majnemer8b622692016-07-03 21:17:51 +00004016 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004017
4018 // Only substitute for the innermost template argument list.
4019 MultiLevelTemplateArgumentList TemplateArgLists;
4020 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4021 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4022 TemplateArgLists.addOuterTemplateArguments(None);
4023
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00004024 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00004025 ArgType =
4026 SemaRef.SubstType(ArgType, TemplateArgLists,
4027 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004028 }
4029
4030 return ArgType;
4031}
4032
4033/// \brief Substitute template arguments into the default template argument for
4034/// the given non-type template parameter.
4035///
4036/// \param SemaRef the semantic analysis object for which we are performing
4037/// the substitution.
4038///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004039/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004040/// for.
4041///
4042/// \param TemplateLoc the location of the template name that started the
4043/// template-id we are checking.
4044///
4045/// \param RAngleLoc the location of the right angle bracket ('>') that
4046/// terminates the template-id.
4047///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004048/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004049/// substituting into.
4050///
4051/// \param Converted the list of template arguments provided for template
4052/// parameters that precede \p Param in the template parameter list.
4053///
4054/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00004055static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004056SubstDefaultTemplateArgument(Sema &SemaRef,
4057 TemplateDecl *Template,
4058 SourceLocation TemplateLoc,
4059 SourceLocation RAngleLoc,
4060 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004061 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004062 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00004063 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004064 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004065 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004066 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004067
David Majnemer8b622692016-07-03 21:17:51 +00004068 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004069
4070 // Only substitute for the innermost template argument list.
4071 MultiLevelTemplateArgumentList TemplateArgLists;
4072 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4073 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4074 TemplateArgLists.addOuterTemplateArguments(None);
4075
Faisal Valid143a0c2017-04-01 21:30:49 +00004076 EnterExpressionEvaluationContext ConstantEvaluated(
4077 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00004078 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004079}
4080
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004081/// \brief Substitute template arguments into the default template argument for
4082/// the given template template parameter.
4083///
4084/// \param SemaRef the semantic analysis object for which we are performing
4085/// the substitution.
4086///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004087/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004088/// for.
4089///
4090/// \param TemplateLoc the location of the template name that started the
4091/// template-id we are checking.
4092///
4093/// \param RAngleLoc the location of the right angle bracket ('>') that
4094/// terminates the template-id.
4095///
4096/// \param Param the template template parameter whose default we are
4097/// substituting into.
4098///
4099/// \param Converted the list of template arguments provided for template
4100/// parameters that precede \p Param in the template parameter list.
4101///
Simon Pilgrim6905d222016-12-30 22:55:33 +00004102/// \param QualifierLoc Will be set to the nested-name-specifier (with
Douglas Gregordf846d12011-03-02 18:46:51 +00004103/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00004104///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004105/// \returns the substituted template argument, or NULL if an error occurred.
4106static TemplateName
4107SubstDefaultTemplateArgument(Sema &SemaRef,
4108 TemplateDecl *Template,
4109 SourceLocation TemplateLoc,
4110 SourceLocation RAngleLoc,
4111 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004112 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00004113 NestedNameSpecifierLoc &QualifierLoc) {
Richard Smith54f18e82016-08-31 02:15:21 +00004114 Sema::InstantiatingTemplate Inst(
4115 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
4116 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004117 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004118 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004119
David Majnemer8b622692016-07-03 21:17:51 +00004120 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004121
4122 // Only substitute for the innermost template argument list.
4123 MultiLevelTemplateArgumentList TemplateArgLists;
4124 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4125 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4126 TemplateArgLists.addOuterTemplateArguments(None);
4127
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00004128 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00004129 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00004130 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00004131 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00004132 QualifierLoc =
4133 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00004134 if (!QualifierLoc)
4135 return TemplateName();
4136 }
David Majnemer89189202013-08-28 23:48:32 +00004137
4138 return SemaRef.SubstTemplateName(
4139 QualifierLoc,
4140 Param->getDefaultArgument().getArgument().getAsTemplate(),
4141 Param->getDefaultArgument().getTemplateNameLoc(),
4142 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004143}
4144
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004145/// \brief If the given template parameter has a default template
4146/// argument, substitute into that default template argument and
4147/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004148TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004149Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
4150 SourceLocation TemplateLoc,
4151 SourceLocation RAngleLoc,
4152 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00004153 SmallVectorImpl<TemplateArgument>
4154 &Converted,
4155 bool &HasDefaultArg) {
4156 HasDefaultArg = false;
4157
4158 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004159 if (!hasVisibleDefaultArgument(TypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004160 return TemplateArgumentLoc();
4161
Richard Smithc87b9382013-07-04 01:01:24 +00004162 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00004163 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004164 TemplateLoc,
4165 RAngleLoc,
4166 TypeParm,
4167 Converted);
4168 if (DI)
4169 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4170
4171 return TemplateArgumentLoc();
4172 }
4173
4174 if (NonTypeTemplateParmDecl *NonTypeParm
4175 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004176 if (!hasVisibleDefaultArgument(NonTypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004177 return TemplateArgumentLoc();
4178
Richard Smithc87b9382013-07-04 01:01:24 +00004179 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00004180 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00004181 TemplateLoc,
4182 RAngleLoc,
4183 NonTypeParm,
4184 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004185 if (Arg.isInvalid())
4186 return TemplateArgumentLoc();
4187
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004188 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004189 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
4190 }
4191
4192 TemplateTemplateParmDecl *TempTempParm
4193 = cast<TemplateTemplateParmDecl>(Param);
Richard Smith95d83952015-06-10 20:36:34 +00004194 if (!hasVisibleDefaultArgument(TempTempParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004195 return TemplateArgumentLoc();
4196
Richard Smithc87b9382013-07-04 01:01:24 +00004197 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00004198 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004199 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004200 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004201 RAngleLoc,
4202 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00004203 Converted,
4204 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004205 if (TName.isNull())
4206 return TemplateArgumentLoc();
4207
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004208 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00004209 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004210 TempTempParm->getDefaultArgument().getTemplateNameLoc());
4211}
4212
Richard Smith11255ec2017-01-18 19:19:22 +00004213/// Convert a template-argument that we parsed as a type into a template, if
4214/// possible. C++ permits injected-class-names to perform dual service as
4215/// template template arguments and as template type arguments.
4216static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
4217 // Extract and step over any surrounding nested-name-specifier.
4218 NestedNameSpecifierLoc QualLoc;
4219 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4220 if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
4221 return TemplateArgumentLoc();
4222
4223 QualLoc = ETLoc.getQualifierLoc();
4224 TLoc = ETLoc.getNamedTypeLoc();
4225 }
4226
4227 // If this type was written as an injected-class-name, it can be used as a
4228 // template template argument.
4229 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4230 return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
4231 QualLoc, InjLoc.getNameLoc());
4232
4233 // If this type was written as an injected-class-name, it may have been
4234 // converted to a RecordType during instantiation. If the RecordType is
4235 // *not* wrapped in a TemplateSpecializationType and denotes a class
4236 // template specialization, it must have come from an injected-class-name.
4237 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
4238 if (auto *CTSD =
4239 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
4240 return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
4241 QualLoc, RecLoc.getNameLoc());
4242
4243 return TemplateArgumentLoc();
4244}
4245
Douglas Gregorda0fb532009-11-11 19:31:23 +00004246/// \brief Check that the given template argument corresponds to the given
4247/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004248///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004249/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004250/// checked.
4251///
Richard Trieu15b66532015-01-24 02:48:32 +00004252/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004253///
4254/// \param Template The template in which the template argument resides.
4255///
4256/// \param TemplateLoc The location of the template name for the template
4257/// whose argument list we're matching.
4258///
4259/// \param RAngleLoc The location of the right angle bracket ('>') that closes
4260/// the template argument list.
4261///
4262/// \param ArgumentPackIndex The index into the argument pack where this
4263/// argument will be placed. Only valid if the parameter is a parameter pack.
4264///
4265/// \param Converted The checked, converted argument will be added to the
4266/// end of this small vector.
4267///
4268/// \param CTAK Describes how we arrived at this particular template argument:
4269/// explicitly written, deduced, etc.
4270///
4271/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004272bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00004273 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00004274 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004275 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004276 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004277 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004278 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00004279 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00004280 // Check template type parameters.
4281 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004282 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004283
Douglas Gregoreebed722009-11-11 19:41:09 +00004284 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004285 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004286 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00004287 // with the template arguments we've seen thus far. But if the
4288 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004289 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004290 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
4291 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004292
Peter Collingbourne01687632010-12-10 17:08:53 +00004293 if (NTTPType->isDependentType() &&
4294 !isa<TemplateTemplateParmDecl>(Template) &&
4295 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004296 // Do substitution on the type of the non-type template parameter.
4297 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00004298 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004299 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004300 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004301 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004302
4303 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00004304 Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004305 NTTPType = SubstType(NTTPType,
4306 MultiLevelTemplateArgumentList(TemplateArgs),
4307 NTTP->getLocation(),
4308 NTTP->getDeclName());
4309 // If that worked, check the non-type template parameter type
4310 // for validity.
4311 if (!NTTPType.isNull())
4312 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
4313 NTTP->getLocation());
4314 if (NTTPType.isNull())
4315 return true;
4316 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004317
Douglas Gregorda0fb532009-11-11 19:31:23 +00004318 switch (Arg.getArgument().getKind()) {
4319 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00004320 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004321
Douglas Gregorda0fb532009-11-11 19:31:23 +00004322 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004323 TemplateArgument Result;
John Wiegley01296292011-04-08 18:41:53 +00004324 ExprResult Res =
4325 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
4326 Result, CTAK);
4327 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00004328 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004329
Richard Trieu15b66532015-01-24 02:48:32 +00004330 // If the resulting expression is new, then use it in place of the
4331 // old expression in the template argument.
4332 if (Res.get() != Arg.getArgument().getAsExpr()) {
4333 TemplateArgument TA(Res.get());
4334 Arg = TemplateArgumentLoc(TA, Res.get());
4335 }
4336
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004337 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004338 break;
4339 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004340
Douglas Gregorda0fb532009-11-11 19:31:23 +00004341 case TemplateArgument::Declaration:
4342 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00004343 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00004344 // We've already checked this template argument, so just copy
4345 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004346 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00004347 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004348
Douglas Gregorda0fb532009-11-11 19:31:23 +00004349 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004350 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00004351 // We were given a template template argument. It may not be ill-formed;
4352 // see below.
4353 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004354 = Arg.getArgument().getAsTemplateOrTemplatePattern()
4355 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004356 // We have a template argument such as \c T::template X, which we
4357 // parsed as a template template argument. However, since we now
4358 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004359 // template name into an expression.
4360
4361 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
4362 Arg.getTemplateNameLoc());
4363
Douglas Gregor3a43fd62011-02-25 20:49:16 +00004364 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00004365 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00004366 // FIXME: the template-template arg was a DependentTemplateName,
4367 // so it was provided with a template keyword. However, its source
4368 // location is not stored in the template argument structure.
4369 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004370 ExprResult E = DependentScopeDeclRefExpr::Create(
4371 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
4372 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004373
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004374 // If we parsed the template argument as a pack expansion, create a
4375 // pack expansion expression.
4376 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004377 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00004378 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004379 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004380 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004381
Douglas Gregorda0fb532009-11-11 19:31:23 +00004382 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004383 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00004384 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00004385 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004386
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004387 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004388 break;
4389 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004390
Douglas Gregorda0fb532009-11-11 19:31:23 +00004391 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00004392 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00004393 // therefore cannot be a non-type template argument.
4394 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
4395 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004396
Douglas Gregorda0fb532009-11-11 19:31:23 +00004397 Diag(Param->getLocation(), diag::note_template_param_here);
4398 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004399
Douglas Gregorda0fb532009-11-11 19:31:23 +00004400 case TemplateArgument::Type: {
4401 // We have a non-type template parameter but the template
4402 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004403
Douglas Gregorda0fb532009-11-11 19:31:23 +00004404 // C++ [temp.arg]p2:
4405 // In a template-argument, an ambiguity between a type-id and
4406 // an expression is resolved to a type-id, regardless of the
4407 // form of the corresponding template-parameter.
4408 //
4409 // We warn specifically about this case, since it can be rather
4410 // confusing for users.
4411 QualType T = Arg.getArgument().getAsType();
4412 SourceRange SR = Arg.getSourceRange();
4413 if (T->isFunctionType())
4414 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
4415 else
4416 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
4417 Diag(Param->getLocation(), diag::note_template_param_here);
4418 return true;
4419 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004420
Douglas Gregorda0fb532009-11-11 19:31:23 +00004421 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004422 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004423 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004424
Douglas Gregorda0fb532009-11-11 19:31:23 +00004425 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004426 }
4427
4428
Douglas Gregorda0fb532009-11-11 19:31:23 +00004429 // Check template template parameters.
4430 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004431
Douglas Gregorda0fb532009-11-11 19:31:23 +00004432 // Substitute into the template parameter list of the template
4433 // template parameter, since previously-supplied template arguments
4434 // may appear within the template template parameter.
4435 {
4436 // Set up a template instantiation context.
4437 LocalInstantiationScope Scope(*this);
4438 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00004439 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004440 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004441 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004442 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004443
David Majnemer8b622692016-07-03 21:17:51 +00004444 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004445 TempParm = cast_or_null<TemplateTemplateParmDecl>(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004446 SubstDecl(TempParm, CurContext,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004447 MultiLevelTemplateArgumentList(TemplateArgs)));
4448 if (!TempParm)
4449 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00004450 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004451
Richard Smith11255ec2017-01-18 19:19:22 +00004452 // C++1z [temp.local]p1: (DR1004)
4453 // When [the injected-class-name] is used [...] as a template-argument for
4454 // a template template-parameter [...] it refers to the class template
4455 // itself.
4456 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
4457 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
4458 Arg.getTypeSourceInfo()->getTypeLoc());
4459 if (!ConvertedArg.getArgument().isNull())
4460 Arg = ConvertedArg;
4461 }
4462
Douglas Gregorda0fb532009-11-11 19:31:23 +00004463 switch (Arg.getArgument().getKind()) {
4464 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00004465 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004466
Douglas Gregorda0fb532009-11-11 19:31:23 +00004467 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004468 case TemplateArgument::TemplateExpansion:
Richard Smith1fde8ec2012-09-07 02:06:42 +00004469 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004470 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004471
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004472 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00004473 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004474
Douglas Gregorda0fb532009-11-11 19:31:23 +00004475 case TemplateArgument::Expression:
4476 case TemplateArgument::Type:
4477 // We have a template template parameter but the template
4478 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004479 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004480 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00004481 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004482
Douglas Gregorda0fb532009-11-11 19:31:23 +00004483 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00004484 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004485 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00004486 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00004487 case TemplateArgument::NullPtr:
4488 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004489
Douglas Gregorda0fb532009-11-11 19:31:23 +00004490 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004491 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004492 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004493
Douglas Gregorda0fb532009-11-11 19:31:23 +00004494 return false;
4495}
4496
Simon Pilgrim6905d222016-12-30 22:55:33 +00004497/// \brief Diagnose an arity mismatch in the
Douglas Gregor8e072612012-02-03 07:34:46 +00004498static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
4499 SourceLocation TemplateLoc,
4500 TemplateArgumentListInfo &TemplateArgs) {
4501 TemplateParameterList *Params = Template->getTemplateParameters();
4502 unsigned NumParams = Params->size();
4503 unsigned NumArgs = TemplateArgs.size();
4504
4505 SourceRange Range;
4506 if (NumArgs > NumParams)
Simon Pilgrim6905d222016-12-30 22:55:33 +00004507 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
Douglas Gregor8e072612012-02-03 07:34:46 +00004508 TemplateArgs.getRAngleLoc());
4509 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4510 << (NumArgs > NumParams)
Richard Smith0c062b42017-01-14 02:19:59 +00004511 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(Template))
Douglas Gregor8e072612012-02-03 07:34:46 +00004512 << Template << Range;
4513 S.Diag(Template->getLocation(), diag::note_template_decl_here)
4514 << Params->getSourceRange();
4515 return true;
4516}
4517
Richard Smith1fde8ec2012-09-07 02:06:42 +00004518/// \brief Check whether the template parameter is a pack expansion, and if so,
4519/// determine the number of parameters produced by that expansion. For instance:
4520///
4521/// \code
4522/// template<typename ...Ts> struct A {
4523/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
4524/// };
4525/// \endcode
4526///
4527/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
4528/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00004529static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00004530 if (NonTypeTemplateParmDecl *NTTP
4531 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4532 if (NTTP->isExpandedParameterPack())
4533 return NTTP->getNumExpansionTypes();
4534 }
4535
4536 if (TemplateTemplateParmDecl *TTP
4537 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
4538 if (TTP->isExpandedParameterPack())
4539 return TTP->getNumExpansionTemplateParameters();
4540 }
4541
David Blaikie7a30dc52013-02-21 01:47:18 +00004542 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00004543}
4544
Richard Smith35c1df52015-06-17 20:16:32 +00004545/// Diagnose a missing template argument.
4546template<typename TemplateParmDecl>
4547static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
4548 TemplateDecl *TD,
4549 const TemplateParmDecl *D,
4550 TemplateArgumentListInfo &Args) {
4551 // Dig out the most recent declaration of the template parameter; there may be
4552 // declarations of the template that are more recent than TD.
4553 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
4554 ->getTemplateParameters()
4555 ->getParam(D->getIndex()));
4556
4557 // If there's a default argument that's not visible, diagnose that we're
4558 // missing a module import.
4559 llvm::SmallVector<Module*, 8> Modules;
4560 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
4561 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
4562 D->getDefaultArgumentLoc(), Modules,
4563 Sema::MissingImportKind::DefaultArgument,
Richard Smith6739a102016-05-05 00:56:12 +00004564 /*Recover*/true);
Richard Smith35c1df52015-06-17 20:16:32 +00004565 return true;
4566 }
4567
4568 // FIXME: If there's a more recent default argument that *is* visible,
4569 // diagnose that it was declared too late.
4570
4571 return diagnoseArityMismatch(S, TD, Loc, Args);
4572}
4573
Douglas Gregord32e0282009-02-09 23:23:08 +00004574/// \brief Check that the given template argument list is well-formed
4575/// for specializing the given template.
Richard Smith11255ec2017-01-18 19:19:22 +00004576bool Sema::CheckTemplateArgumentList(
4577 TemplateDecl *Template, SourceLocation TemplateLoc,
4578 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
4579 SmallVectorImpl<TemplateArgument> &Converted,
4580 bool UpdateArgsWithConversions) {
Richard Trieu15b66532015-01-24 02:48:32 +00004581 // Make a copy of the template arguments for processing. Only make the
4582 // changes at the end when successful in matching the arguments to the
4583 // template.
4584 TemplateArgumentListInfo NewArgs = TemplateArgs;
4585
Douglas Gregord32e0282009-02-09 23:23:08 +00004586 TemplateParameterList *Params = Template->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00004587
Richard Trieu15b66532015-01-24 02:48:32 +00004588 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00004589
Mike Stump11289f42009-09-09 15:08:12 +00004590 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00004591 // [...] The type and form of each template-argument specified in
4592 // a template-id shall match the type and form specified for the
4593 // corresponding parameter declared by the template in its
4594 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00004595 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004596 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00004597 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00004598 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00004599 for (TemplateParameterList::iterator Param = Params->begin(),
4600 ParamEnd = Params->end();
4601 Param != ParamEnd; /* increment in loop */) {
4602 // If we have an expanded parameter pack, make sure we don't have too
4603 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00004604 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00004605 if (*Expansions == ArgumentPack.size()) {
4606 // We're done with this parameter pack. Pack up its arguments and add
4607 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00004608 Converted.push_back(
Benjamin Kramercce63472015-08-05 09:40:22 +00004609 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00004610 ArgumentPack.clear();
4611
Richard Smith1fde8ec2012-09-07 02:06:42 +00004612 // This argument is assigned to the next parameter.
4613 ++Param;
4614 continue;
4615 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
4616 // Not enough arguments for this parameter pack.
4617 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4618 << false
Richard Smith0c062b42017-01-14 02:19:59 +00004619 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
Richard Smith1fde8ec2012-09-07 02:06:42 +00004620 << Template;
4621 Diag(Template->getLocation(), diag::note_template_decl_here)
4622 << Params->getSourceRange();
4623 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004624 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00004625 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004626
Richard Smith1fde8ec2012-09-07 02:06:42 +00004627 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00004628 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00004629 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004630 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004631 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00004632 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004633
Richard Smith96d71c32014-11-12 23:38:38 +00004634 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00004635 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00004636 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
4637 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00004638 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00004639 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00004640 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00004641 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00004642 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00004643 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00004644 Diag((*Param)->getLocation(), diag::note_template_param_here);
4645 return true;
4646 }
4647
Richard Smith1fde8ec2012-09-07 02:06:42 +00004648 // We're now done with this argument.
4649 ++ArgIdx;
4650
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004651 if ((*Param)->isTemplateParameterPack()) {
4652 // The template parameter was a template parameter pack, so take the
4653 // deduced argument and place it on the argument pack. Note that we
4654 // stay on the same template parameter so that we can deduce more
4655 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00004656 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004657 } else {
4658 // Move to the next template parameter.
4659 ++Param;
4660 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00004661
Richard Smith96d71c32014-11-12 23:38:38 +00004662 // If we just saw a pack expansion into a non-pack, then directly convert
4663 // the remaining arguments, because we don't know what parameters they'll
4664 // match up with.
4665 if (PackExpansionIntoNonPack) {
4666 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00004667 // If we were part way through filling in an expanded parameter pack,
4668 // fall back to just producing individual arguments.
4669 Converted.insert(Converted.end(),
4670 ArgumentPack.begin(), ArgumentPack.end());
4671 ArgumentPack.clear();
4672 }
4673
4674 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00004675 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00004676 ++ArgIdx;
4677 }
4678
Richard Smith1fde8ec2012-09-07 02:06:42 +00004679 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00004680 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00004681
Douglas Gregor84d49a22009-11-11 21:54:23 +00004682 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00004683 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004684
Douglas Gregor2f157c92011-06-03 02:59:40 +00004685 // If we're checking a partial template argument list, we're done.
4686 if (PartialTemplateArgs) {
4687 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
Benjamin Kramercce63472015-08-05 09:40:22 +00004688 Converted.push_back(
4689 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4690
Richard Smith1fde8ec2012-09-07 02:06:42 +00004691 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00004692 }
4693
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004694 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004695 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00004696 if ((*Param)->isTemplateParameterPack()) {
4697 assert(!getExpandedPackSize(*Param) &&
4698 "Should have dealt with this already");
4699
4700 // A non-expanded parameter pack before the end of the parameter list
4701 // only occurs for an ill-formed template parameter list, unless we've
4702 // got a partial argument list for a function template, so just bail out.
4703 if (Param + 1 != ParamEnd)
4704 return true;
4705
Benjamin Kramercce63472015-08-05 09:40:22 +00004706 Converted.push_back(
4707 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00004708 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00004709
4710 ++Param;
4711 continue;
4712 }
4713
Douglas Gregor8e072612012-02-03 07:34:46 +00004714 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00004715 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004716
Douglas Gregor84d49a22009-11-11 21:54:23 +00004717 // Retrieve the default template argument from the template
4718 // parameter. For each kind of template parameter, we substitute the
4719 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004720 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00004721 // the default argument.
4722 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004723 if (!hasVisibleDefaultArgument(TTP))
Richard Smith35c1df52015-06-17 20:16:32 +00004724 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
4725 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004726
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004727 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004728 Template,
4729 TemplateLoc,
4730 RAngleLoc,
4731 TTP,
4732 Converted);
4733 if (!ArgType)
4734 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004735
Douglas Gregor84d49a22009-11-11 21:54:23 +00004736 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
4737 ArgType);
4738 } else if (NonTypeTemplateParmDecl *NTTP
4739 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004740 if (!hasVisibleDefaultArgument(NTTP))
Richard Smith35c1df52015-06-17 20:16:32 +00004741 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
4742 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004743
John McCalldadc5752010-08-24 06:29:42 +00004744 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004745 TemplateLoc,
4746 RAngleLoc,
4747 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004748 Converted);
4749 if (E.isInvalid())
4750 return true;
4751
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004752 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00004753 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
4754 } else {
4755 TemplateTemplateParmDecl *TempParm
4756 = cast<TemplateTemplateParmDecl>(*Param);
4757
Richard Smith95d83952015-06-10 20:36:34 +00004758 if (!hasVisibleDefaultArgument(TempParm))
Richard Smith35c1df52015-06-17 20:16:32 +00004759 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
4760 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004761
Douglas Gregordf846d12011-03-02 18:46:51 +00004762 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00004763 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004764 TemplateLoc,
4765 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004766 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00004767 Converted,
4768 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004769 if (Name.isNull())
4770 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004771
Douglas Gregor9d802122011-03-02 17:09:35 +00004772 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
4773 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00004774 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004775
Douglas Gregor84d49a22009-11-11 21:54:23 +00004776 // Introduce an instantiation record that describes where we are using
Richard Smith54f18e82016-08-31 02:15:21 +00004777 // the default template argument. We're not actually instantiating a
4778 // template here, we just create this object to put a note into the
4779 // context stack.
Alp Tokerd4a72d52013-10-08 08:09:04 +00004780 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
4781 SourceRange(TemplateLoc, RAngleLoc));
4782 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004783 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004784
Douglas Gregor84d49a22009-11-11 21:54:23 +00004785 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00004786 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004787 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004788 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004789
Richard Trieu15b66532015-01-24 02:48:32 +00004790 // Core issue 150 (assumed resolution): if this is a template template
4791 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00004792 // template definition.
4793 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00004794 NewArgs.addArgument(Arg);
4795
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004796 // Move to the next template parameter and argument.
4797 ++Param;
4798 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00004799 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004800
Richard Smith07f79912014-06-06 16:00:50 +00004801 // If we're performing a partial argument substitution, allow any trailing
4802 // pack expansions; they might be empty. This can happen even if
4803 // PartialTemplateArgs is false (the list of arguments is complete but
4804 // still dependent).
4805 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
4806 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00004807 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
4808 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00004809 }
4810
Douglas Gregor8e072612012-02-03 07:34:46 +00004811 // If we have any leftover arguments, then there were too many arguments.
4812 // Complain and fail.
4813 if (ArgIdx < NumArgs)
Richard Trieu15b66532015-01-24 02:48:32 +00004814 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
4815
4816 // No problems found with the new argument list, propagate changes back
4817 // to caller.
Richard Smith11255ec2017-01-18 19:19:22 +00004818 if (UpdateArgsWithConversions)
4819 TemplateArgs = std::move(NewArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004820
Richard Smith1fde8ec2012-09-07 02:06:42 +00004821 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00004822}
4823
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004824namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004825 class UnnamedLocalNoLinkageFinder
4826 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004827 {
4828 Sema &S;
4829 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004830
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004831 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004832
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004833 public:
4834 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
4835
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004836 bool Visit(QualType T) {
Daniel Jasper5cad6852017-01-02 22:55:45 +00004837 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004838 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004839
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004840#define TYPE(Class, Parent) \
4841 bool Visit##Class##Type(const Class##Type *);
4842#define ABSTRACT_TYPE(Class, Parent) \
4843 bool Visit##Class##Type(const Class##Type *) { return false; }
4844#define NON_CANONICAL_TYPE(Class, Parent) \
4845 bool Visit##Class##Type(const Class##Type *) { return false; }
4846#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004847
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004848 bool VisitTagDecl(const TagDecl *Tag);
4849 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
4850 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004851} // end anonymous namespace
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004852
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004853bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004854 return false;
4855}
4856
4857bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
4858 return Visit(T->getElementType());
4859}
4860
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004861bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004862 return Visit(T->getPointeeType());
4863}
4864
4865bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004866 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004867 return Visit(T->getPointeeType());
4868}
4869
4870bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004871 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004872 return Visit(T->getPointeeType());
4873}
4874
4875bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004876 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004877 return Visit(T->getPointeeType());
4878}
4879
4880bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004881 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004882 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
4883}
4884
4885bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004886 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004887 return Visit(T->getElementType());
4888}
4889
4890bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004891 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004892 return Visit(T->getElementType());
4893}
4894
4895bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004896 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004897 return Visit(T->getElementType());
4898}
4899
4900bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004901 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004902 return Visit(T->getElementType());
4903}
4904
4905bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004906 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004907 return Visit(T->getElementType());
4908}
4909
4910bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
4911 return Visit(T->getElementType());
4912}
4913
4914bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
4915 return Visit(T->getElementType());
4916}
4917
4918bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
4919 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004920 for (const auto &A : T->param_types()) {
4921 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004922 return true;
4923 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004924
Alp Toker314cc812014-01-25 16:55:45 +00004925 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004926}
4927
4928bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
4929 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00004930 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004931}
4932
4933bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
4934 const UnresolvedUsingType*) {
4935 return false;
4936}
4937
4938bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
4939 return false;
4940}
4941
4942bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4943 return Visit(T->getUnderlyingType());
4944}
4945
4946bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4947 return false;
4948}
4949
Alexis Hunte852b102011-05-24 22:41:36 +00004950bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4951 const UnaryTransformType*) {
4952 return false;
4953}
4954
Richard Smith30482bc2011-02-20 03:19:35 +00004955bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4956 return Visit(T->getDeducedType());
4957}
4958
Richard Smith600b5262017-01-26 20:40:47 +00004959bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
4960 const DeducedTemplateSpecializationType *T) {
4961 return Visit(T->getDeducedType());
4962}
4963
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004964bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4965 return VisitTagDecl(T->getDecl());
4966}
4967
4968bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4969 return VisitTagDecl(T->getDecl());
4970}
4971
4972bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4973 const TemplateTypeParmType*) {
4974 return false;
4975}
4976
Douglas Gregorada4b792011-01-14 02:55:32 +00004977bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4978 const SubstTemplateTypeParmPackType *) {
4979 return false;
4980}
4981
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004982bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4983 const TemplateSpecializationType*) {
4984 return false;
4985}
4986
4987bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4988 const InjectedClassNameType* T) {
4989 return VisitTagDecl(T->getDecl());
4990}
4991
4992bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4993 const DependentNameType* T) {
4994 return VisitNestedNameSpecifier(T->getQualifier());
4995}
4996
4997bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4998 const DependentTemplateSpecializationType* T) {
4999 return VisitNestedNameSpecifier(T->getQualifier());
5000}
5001
Douglas Gregord2fa7662010-12-20 02:24:11 +00005002bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
5003 const PackExpansionType* T) {
5004 return Visit(T->getPattern());
5005}
5006
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005007bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5008 return false;
5009}
5010
5011bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
5012 const ObjCInterfaceType *) {
5013 return false;
5014}
5015
5016bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
5017 const ObjCObjectPointerType *) {
5018 return false;
5019}
5020
Eli Friedman0dfb8892011-10-06 23:00:33 +00005021bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
5022 return Visit(T->getValueType());
5023}
5024
Xiuli Pan9c14e282016-01-09 12:53:17 +00005025bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
5026 return false;
5027}
5028
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005029bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
5030 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005031 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005032 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00005033 diag::warn_cxx98_compat_template_arg_local_type :
5034 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005035 << S.Context.getTypeDeclType(Tag) << SR;
5036 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005037 }
5038
John McCall5ea95772013-03-09 00:54:27 +00005039 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005040 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005041 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00005042 diag::warn_cxx98_compat_template_arg_unnamed_type :
5043 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005044 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
5045 return true;
5046 }
5047
5048 return false;
5049}
5050
5051bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5052 NestedNameSpecifier *NNS) {
5053 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5054 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005055
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005056 switch (NNS->getKind()) {
5057 case NestedNameSpecifier::Identifier:
5058 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005059 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005060 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00005061 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005062 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005063
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005064 case NestedNameSpecifier::TypeSpec:
5065 case NestedNameSpecifier::TypeSpecWithTemplate:
5066 return Visit(QualType(NNS->getAsType(), 0));
5067 }
David Blaikie8a40f702012-01-17 06:56:22 +00005068 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005069}
5070
Douglas Gregord32e0282009-02-09 23:23:08 +00005071/// \brief Check a template argument against its corresponding
5072/// template type parameter.
5073///
5074/// This routine implements the semantics of C++ [temp.arg.type]. It
5075/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005076bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00005077 TypeSourceInfo *ArgInfo) {
5078 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00005079 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00005080 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00005081
5082 if (Arg->isVariablyModifiedType()) {
5083 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005084 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005085 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00005086 }
5087
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005088 // C++03 [temp.arg.type]p2:
5089 // A local type, a type with no linkage, an unnamed type or a type
5090 // compounded from any of these types shall not be used as a
5091 // template-argument for a template type-parameter.
5092 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00005093 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005094 // a warning.
Daniel Jasper5cad6852017-01-02 22:55:45 +00005095 if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005096 UnnamedLocalNoLinkageFinder Finder(*this, SR);
5097 (void)Finder.Visit(Context.getCanonicalType(Arg));
5098 }
5099
Douglas Gregord32e0282009-02-09 23:23:08 +00005100 return false;
5101}
5102
Douglas Gregor20fdef32012-04-10 17:08:25 +00005103enum NullPointerValueKind {
5104 NPV_NotNullPointer,
5105 NPV_NullPointer,
5106 NPV_Error
5107};
5108
5109/// \brief Determine whether the given template argument is a null pointer
5110/// value of the appropriate type.
5111static NullPointerValueKind
5112isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
5113 QualType ParamType, Expr *Arg) {
5114 if (Arg->isValueDependent() || Arg->isTypeDependent())
5115 return NPV_NotNullPointer;
David Majnemer69c3ddc2015-09-11 20:18:09 +00005116
Richard Smithdb0ac552015-12-18 22:40:25 +00005117 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
David Majnemerb54368c2015-09-11 20:55:29 +00005118 llvm_unreachable(
5119 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
David Majnemer69c3ddc2015-09-11 20:18:09 +00005120
David Majnemer5c734ad2014-08-14 00:49:23 +00005121 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00005122 return NPV_NotNullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005123
Douglas Gregor20fdef32012-04-10 17:08:25 +00005124 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00005125 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
5126 if (ArgRV.isInvalid())
5127 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005128 Arg = ArgRV.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005129
Douglas Gregor20fdef32012-04-10 17:08:25 +00005130 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005131 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00005132 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005133 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00005134 EvalResult.HasSideEffects) {
5135 SourceLocation DiagLoc = Arg->getExprLoc();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005136
Douglas Gregor350880c2012-04-10 19:03:30 +00005137 // If our only note is the usual "invalid subexpression" note, just point
5138 // the caret at its location rather than producing an essentially
5139 // redundant note.
5140 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5141 diag::note_invalid_subexpr_in_const_expr) {
5142 DiagLoc = Notes[0].first;
5143 Notes.clear();
5144 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005145
Douglas Gregor350880c2012-04-10 19:03:30 +00005146 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5147 << Arg->getType() << Arg->getSourceRange();
5148 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5149 S.Diag(Notes[I].first, Notes[I].second);
Simon Pilgrim6905d222016-12-30 22:55:33 +00005150
Douglas Gregor350880c2012-04-10 19:03:30 +00005151 S.Diag(Param->getLocation(), diag::note_template_param_here);
5152 return NPV_Error;
5153 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005154
Douglas Gregor20fdef32012-04-10 17:08:25 +00005155 // C++11 [temp.arg.nontype]p1:
5156 // - an address constant expression of type std::nullptr_t
5157 if (Arg->getType()->isNullPtrType())
5158 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005159
Douglas Gregor20fdef32012-04-10 17:08:25 +00005160 // - a constant expression that evaluates to a null pointer value (4.10); or
5161 // - a constant expression that evaluates to a null member pointer value
5162 // (4.11); or
5163 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
5164 (EvalResult.Val.isMemberPointer() &&
5165 !EvalResult.Val.getMemberPointerDecl())) {
5166 // If our expression has an appropriate type, we've succeeded.
5167 bool ObjCLifetimeConversion;
5168 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5169 S.IsQualificationConversion(Arg->getType(), ParamType, false,
5170 ObjCLifetimeConversion))
5171 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005172
Douglas Gregor20fdef32012-04-10 17:08:25 +00005173 // The types didn't match, but we know we got a null pointer; complain,
5174 // then recover as if the types were correct.
5175 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
5176 << Arg->getType() << ParamType << Arg->getSourceRange();
5177 S.Diag(Param->getLocation(), diag::note_template_param_here);
5178 return NPV_NullPointer;
5179 }
5180
5181 // If we don't have a null pointer value, but we do have a NULL pointer
5182 // constant, suggest a cast to the appropriate type.
5183 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
5184 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
5185 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Alp Tokerb6cc5922014-05-03 03:45:55 +00005186 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
5187 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
5188 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00005189 S.Diag(Param->getLocation(), diag::note_template_param_here);
5190 return NPV_NullPointer;
5191 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005192
Douglas Gregor20fdef32012-04-10 17:08:25 +00005193 // FIXME: If we ever want to support general, address-constant expressions
5194 // as non-type template arguments, we should return the ExprResult here to
5195 // be interpreted by the caller.
5196 return NPV_NotNullPointer;
5197}
5198
David Majnemer61c39a12013-08-23 05:39:39 +00005199/// \brief Checks whether the given template argument is compatible with its
5200/// template parameter.
5201static bool CheckTemplateArgumentIsCompatibleWithParameter(
5202 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
5203 Expr *Arg, QualType ArgType) {
5204 bool ObjCLifetimeConversion;
5205 if (ParamType->isPointerType() &&
5206 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
5207 S.IsQualificationConversion(ArgType, ParamType, false,
5208 ObjCLifetimeConversion)) {
5209 // For pointer-to-object types, qualification conversions are
5210 // permitted.
5211 } else {
5212 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
5213 if (!ParamRef->getPointeeType()->isFunctionType()) {
5214 // C++ [temp.arg.nontype]p5b3:
5215 // For a non-type template-parameter of type reference to
5216 // object, no conversions apply. The type referred to by the
5217 // reference may be more cv-qualified than the (otherwise
5218 // identical) type of the template- argument. The
5219 // template-parameter is bound directly to the
5220 // template-argument, which shall be an lvalue.
5221
5222 // FIXME: Other qualifiers?
5223 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
5224 unsigned ArgQuals = ArgType.getCVRQualifiers();
5225
5226 if ((ParamQuals | ArgQuals) != ParamQuals) {
5227 S.Diag(Arg->getLocStart(),
5228 diag::err_template_arg_ref_bind_ignores_quals)
5229 << ParamType << Arg->getType() << Arg->getSourceRange();
5230 S.Diag(Param->getLocation(), diag::note_template_param_here);
5231 return true;
5232 }
5233 }
5234 }
5235
5236 // At this point, the template argument refers to an object or
5237 // function with external linkage. We now need to check whether the
5238 // argument and parameter types are compatible.
5239 if (!S.Context.hasSameUnqualifiedType(ArgType,
5240 ParamType.getNonReferenceType())) {
5241 // We can't perform this conversion or binding.
5242 if (ParamType->isReferenceType())
5243 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
5244 << ParamType << ArgIn->getType() << Arg->getSourceRange();
5245 else
5246 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
5247 << ArgIn->getType() << ParamType << Arg->getSourceRange();
5248 S.Diag(Param->getLocation(), diag::note_template_param_here);
5249 return true;
5250 }
5251 }
5252
5253 return false;
5254}
5255
Douglas Gregorccb07762009-02-11 19:52:55 +00005256/// \brief Checks whether the given template argument is the address
5257/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005258static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00005259CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
5260 NonTypeTemplateParmDecl *Param,
5261 QualType ParamType,
5262 Expr *ArgIn,
5263 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005264 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005265 Expr *Arg = ArgIn;
5266 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00005267
Douglas Gregorb242683d2010-04-01 18:32:35 +00005268 bool AddressTaken = false;
5269 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00005270 if (S.getLangOpts().MicrosoftExt) {
5271 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
5272 // dereference and address-of operators.
5273 Arg = Arg->IgnoreParenCasts();
5274
5275 bool ExtWarnMSTemplateArg = false;
5276 UnaryOperatorKind FirstOpKind;
5277 SourceLocation FirstOpLoc;
5278 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5279 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
5280 if (UnOpKind == UO_Deref)
5281 ExtWarnMSTemplateArg = true;
5282 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
5283 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
5284 if (!AddrOpLoc.isValid()) {
5285 FirstOpKind = UnOpKind;
5286 FirstOpLoc = UnOp->getOperatorLoc();
5287 }
5288 } else
5289 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005290 }
David Majnemer61c39a12013-08-23 05:39:39 +00005291 if (FirstOpLoc.isValid()) {
5292 if (ExtWarnMSTemplateArg)
5293 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
5294 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00005295
David Majnemer61c39a12013-08-23 05:39:39 +00005296 if (FirstOpKind == UO_AddrOf)
5297 AddressTaken = true;
5298 else if (Arg->getType()->isPointerType()) {
5299 // We cannot let pointers get dereferenced here, that is obviously not a
5300 // constant expression.
5301 assert(FirstOpKind == UO_Deref);
5302 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5303 << Arg->getSourceRange();
5304 }
5305 }
5306 } else {
5307 // See through any implicit casts we added to fix the type.
5308 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00005309
David Majnemer61c39a12013-08-23 05:39:39 +00005310 // C++ [temp.arg.nontype]p1:
5311 //
5312 // A template-argument for a non-type, non-template
5313 // template-parameter shall be one of: [...]
5314 //
5315 // -- the address of an object or function with external
5316 // linkage, including function templates and function
5317 // template-ids but excluding non-static class members,
5318 // expressed as & id-expression where the & is optional if
5319 // the name refers to a function or array, or if the
5320 // corresponding template-parameter is a reference; or
5321
5322 // In C++98/03 mode, give an extension warning on any extra parentheses.
5323 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5324 bool ExtraParens = false;
5325 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5326 if (!Invalid && !ExtraParens) {
5327 S.Diag(Arg->getLocStart(),
5328 S.getLangOpts().CPlusPlus11
5329 ? diag::warn_cxx98_compat_template_arg_extra_parens
5330 : diag::ext_template_arg_extra_parens)
5331 << Arg->getSourceRange();
5332 ExtraParens = true;
5333 }
5334
5335 Arg = Parens->getSubExpr();
5336 }
5337
5338 while (SubstNonTypeTemplateParmExpr *subst =
5339 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5340 Arg = subst->getReplacement()->IgnoreImpCasts();
5341
5342 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5343 if (UnOp->getOpcode() == UO_AddrOf) {
5344 Arg = UnOp->getSubExpr();
5345 AddressTaken = true;
5346 AddrOpLoc = UnOp->getOperatorLoc();
5347 }
5348 }
5349
5350 while (SubstNonTypeTemplateParmExpr *subst =
5351 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5352 Arg = subst->getReplacement()->IgnoreImpCasts();
5353 }
John McCall7c454bb2011-07-15 05:09:51 +00005354
David Majnemer07910d62014-06-26 07:48:46 +00005355 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
5356 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5357
5358 // If our parameter has pointer type, check for a null template value.
5359 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
5360 NullPointerValueKind NPV;
5361 // dllimport'd entities aren't constant but are available inside of template
5362 // arguments.
5363 if (Entity && Entity->hasAttr<DLLImportAttr>())
5364 NPV = NPV_NotNullPointer;
5365 else
5366 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
5367 switch (NPV) {
5368 case NPV_NullPointer:
5369 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005370 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5371 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00005372 return false;
5373
5374 case NPV_Error:
5375 return true;
5376
5377 case NPV_NotNullPointer:
5378 break;
5379 }
5380 }
5381
Chandler Carruth724a8a12010-01-31 10:01:20 +00005382 // Stop checking the precise nature of the argument if it is value dependent,
5383 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00005384 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005385 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00005386 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005387 }
David Majnemer61c39a12013-08-23 05:39:39 +00005388
5389 if (isa<CXXUuidofExpr>(Arg)) {
5390 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
5391 ArgIn, Arg, ArgType))
5392 return true;
5393
5394 Converted = TemplateArgument(ArgIn);
5395 return false;
5396 }
5397
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005398 if (!DRE) {
5399 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5400 << Arg->getSourceRange();
5401 S.Diag(Param->getLocation(), diag::note_template_param_here);
5402 return true;
5403 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00005404
Douglas Gregorccb07762009-02-11 19:52:55 +00005405 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00005406 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005407 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
David Majnemer6bedcfa2013-10-26 06:12:44 +00005408 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005409 S.Diag(Param->getLocation(), diag::note_template_param_here);
5410 return true;
5411 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005412
5413 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00005414 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005415 if (!Method->isStatic()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005416 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00005417 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005418 S.Diag(Param->getLocation(), diag::note_template_param_here);
5419 return true;
5420 }
Richard Smith9380e0e2012-04-04 21:11:30 +00005421 }
Mike Stump11289f42009-09-09 15:08:12 +00005422
Richard Smith9380e0e2012-04-04 21:11:30 +00005423 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
5424 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00005425
Richard Smith9380e0e2012-04-04 21:11:30 +00005426 // A non-type template argument must refer to an object or function.
5427 if (!Func && !Var) {
5428 // We found something, but we don't know specifically what it is.
5429 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
5430 << Arg->getSourceRange();
5431 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
5432 return true;
5433 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005434
Richard Smith9380e0e2012-04-04 21:11:30 +00005435 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00005436 if (Entity->getFormalLinkage() == InternalLinkage) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005437 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
Richard Smith9380e0e2012-04-04 21:11:30 +00005438 diag::warn_cxx98_compat_template_arg_object_internal :
5439 diag::ext_template_arg_object_internal)
5440 << !Func << Entity << Arg->getSourceRange();
5441 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5442 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00005443 } else if (!Entity->hasLinkage()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00005444 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
5445 << !Func << Entity << Arg->getSourceRange();
5446 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5447 << !Func;
5448 return true;
5449 }
5450
5451 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005452 // If the template parameter has pointer type, the function decays.
5453 if (ParamType->isPointerType() && !AddressTaken)
5454 ArgType = S.Context.getPointerType(Func->getType());
5455 else if (AddressTaken && ParamType->isReferenceType()) {
5456 // If we originally had an address-of operator, but the
5457 // parameter has reference type, complain and (if things look
5458 // like they will work) drop the address-of operator.
5459 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
5460 ParamType.getNonReferenceType())) {
5461 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5462 << ParamType;
5463 S.Diag(Param->getLocation(), diag::note_template_param_here);
5464 return true;
5465 }
5466
5467 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5468 << ParamType
5469 << FixItHint::CreateRemoval(AddrOpLoc);
5470 S.Diag(Param->getLocation(), diag::note_template_param_here);
5471
5472 ArgType = Func->getType();
5473 }
Richard Smith9380e0e2012-04-04 21:11:30 +00005474 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005475 // A value of reference type is not an object.
5476 if (Var->getType()->isReferenceType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005477 S.Diag(Arg->getLocStart(),
Douglas Gregorb242683d2010-04-01 18:32:35 +00005478 diag::err_template_arg_reference_var)
5479 << Var->getType() << Arg->getSourceRange();
5480 S.Diag(Param->getLocation(), diag::note_template_param_here);
5481 return true;
5482 }
5483
Richard Smith9380e0e2012-04-04 21:11:30 +00005484 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00005485 if (Var->getTLSKind()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00005486 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
5487 << Arg->getSourceRange();
5488 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
5489 return true;
5490 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00005491
5492 // If the template parameter has pointer type, we must have taken
5493 // the address of this object.
5494 if (ParamType->isReferenceType()) {
5495 if (AddressTaken) {
5496 // If we originally had an address-of operator, but the
5497 // parameter has reference type, complain and (if things look
5498 // like they will work) drop the address-of operator.
5499 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
5500 ParamType.getNonReferenceType())) {
5501 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5502 << ParamType;
5503 S.Diag(Param->getLocation(), diag::note_template_param_here);
5504 return true;
5505 }
5506
5507 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5508 << ParamType
5509 << FixItHint::CreateRemoval(AddrOpLoc);
5510 S.Diag(Param->getLocation(), diag::note_template_param_here);
5511
5512 ArgType = Var->getType();
5513 }
5514 } else if (!AddressTaken && ParamType->isPointerType()) {
5515 if (Var->getType()->isArrayType()) {
5516 // Array-to-pointer decay.
5517 ArgType = S.Context.getArrayDecayedType(Var->getType());
5518 } else {
5519 // If the template parameter has pointer type but the address of
5520 // this object was not taken, complain and (possibly) recover by
5521 // taking the address of the entity.
5522 ArgType = S.Context.getPointerType(Var->getType());
5523 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
5524 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5525 << ParamType;
5526 S.Diag(Param->getLocation(), diag::note_template_param_here);
5527 return true;
5528 }
5529
5530 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5531 << ParamType
5532 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
5533
5534 S.Diag(Param->getLocation(), diag::note_template_param_here);
5535 }
5536 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005537 }
Mike Stump11289f42009-09-09 15:08:12 +00005538
David Majnemer61c39a12013-08-23 05:39:39 +00005539 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
5540 Arg, ArgType))
5541 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005542
5543 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00005544 Converted =
5545 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Nick Lewycky45b50522013-02-02 00:25:55 +00005546 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00005547 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00005548}
5549
5550/// \brief Checks whether the given template argument is a pointer to
5551/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00005552static bool CheckTemplateArgumentPointerToMember(Sema &S,
5553 NonTypeTemplateParmDecl *Param,
5554 QualType ParamType,
5555 Expr *&ResultArg,
5556 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005557 bool Invalid = false;
5558
Douglas Gregor20fdef32012-04-10 17:08:25 +00005559 // Check for a null pointer value.
5560 Expr *Arg = ResultArg;
5561 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
5562 case NPV_Error:
5563 return true;
5564 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00005565 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005566 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5567 /*isNullPtr*/true);
Douglas Gregor20fdef32012-04-10 17:08:25 +00005568 return false;
5569 case NPV_NotNullPointer:
5570 break;
5571 }
5572
5573 bool ObjCLifetimeConversion;
5574 if (S.IsQualificationConversion(Arg->getType(),
5575 ParamType.getNonReferenceType(),
5576 false, ObjCLifetimeConversion)) {
5577 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005578 Arg->getValueKind()).get();
Douglas Gregor20fdef32012-04-10 17:08:25 +00005579 ResultArg = Arg;
5580 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
5581 ParamType.getNonReferenceType())) {
5582 // We can't perform this conversion.
5583 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
5584 << Arg->getType() << ParamType << Arg->getSourceRange();
5585 S.Diag(Param->getLocation(), diag::note_template_param_here);
5586 return true;
5587 }
5588
Douglas Gregorccb07762009-02-11 19:52:55 +00005589 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00005590 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00005591 Arg = Cast->getSubExpr();
5592
5593 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00005594 //
Douglas Gregorccb07762009-02-11 19:52:55 +00005595 // A template-argument for a non-type, non-template
5596 // template-parameter shall be one of: [...]
5597 //
5598 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00005599 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00005600
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00005601 // In C++98/03 mode, give an extension warning on any extra parentheses.
5602 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5603 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00005604 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005605 if (!Invalid && !ExtraParens) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00005606 S.Diag(Arg->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005607 S.getLangOpts().CPlusPlus11 ?
Douglas Gregor20fdef32012-04-10 17:08:25 +00005608 diag::warn_cxx98_compat_template_arg_extra_parens :
5609 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00005610 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00005611 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00005612 }
5613
5614 Arg = Parens->getSubExpr();
5615 }
5616
John McCall7c454bb2011-07-15 05:09:51 +00005617 while (SubstNonTypeTemplateParmExpr *subst =
5618 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5619 Arg = subst->getReplacement()->IgnoreImpCasts();
5620
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005621 // A pointer-to-member constant written &Class::member.
5622 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00005623 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005624 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
5625 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00005626 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005627 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005628 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005629 // A constant of pointer-to-member type.
5630 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
5631 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
5632 if (VD->getType()->isMemberPointerType()) {
David Majnemercd053cd2013-12-10 00:40:58 +00005633 if (isa<NonTypeTemplateParmDecl>(VD)) {
Eli Friedmanb826a002012-09-26 02:36:12 +00005634 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005635 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00005636 } else {
5637 VD = cast<ValueDecl>(VD->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00005638 Converted = TemplateArgument(VD, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00005639 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005640 return Invalid;
5641 }
5642 }
5643 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005644
Craig Topperc3ec1492014-05-26 06:22:03 +00005645 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005646 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005647
Douglas Gregorccb07762009-02-11 19:52:55 +00005648 if (!DRE)
Douglas Gregor20fdef32012-04-10 17:08:25 +00005649 return S.Diag(Arg->getLocStart(),
5650 diag::err_template_arg_not_pointer_to_member_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00005651 << Arg->getSourceRange();
5652
David Majnemer3ac84e62013-10-22 21:56:38 +00005653 if (isa<FieldDecl>(DRE->getDecl()) ||
5654 isa<IndirectFieldDecl>(DRE->getDecl()) ||
5655 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005656 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00005657 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00005658 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
5659 "Only non-static member pointers can make it here");
5660
5661 // Okay: this is the address of a non-static member, and therefore
5662 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00005663 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005664 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00005665 } else {
5666 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00005667 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00005668 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005669 return Invalid;
5670 }
5671
5672 // We found something else, but we don't know specifically what it is.
Douglas Gregor20fdef32012-04-10 17:08:25 +00005673 S.Diag(Arg->getLocStart(),
5674 diag::err_template_arg_not_pointer_to_member_form)
5675 << Arg->getSourceRange();
5676 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00005677 return true;
5678}
5679
Douglas Gregord32e0282009-02-09 23:23:08 +00005680/// \brief Check a template argument against its corresponding
5681/// non-type template parameter.
5682///
Douglas Gregor463421d2009-03-03 04:44:36 +00005683/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00005684/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00005685/// returns the converted template argument. \p ParamType is the
5686/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00005687ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00005688 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00005689 TemplateArgument &Converted,
5690 CheckTemplateArgumentKind CTAK) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005691 SourceLocation StartLoc = Arg->getLocStart();
Douglas Gregorc40290e2009-03-09 23:48:35 +00005692
Richard Smith5f274382016-09-28 23:55:27 +00005693 // If the parameter type somehow involves auto, deduce the type now.
5694 if (getLangOpts().CPlusPlus1z && ParamType->isUndeducedType()) {
Richard Smith4ae5ec82017-02-22 20:01:55 +00005695 // During template argument deduction, we allow 'decltype(auto)' to
5696 // match an arbitrary dependent argument.
5697 // FIXME: The language rules don't say what happens in this case.
5698 // FIXME: We get an opaque dependent type out of decltype(auto) if the
5699 // expression is merely instantiation-dependent; is this enough?
5700 if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
5701 auto *AT = dyn_cast<AutoType>(ParamType);
5702 if (AT && AT->isDecltypeAuto()) {
5703 Converted = TemplateArgument(Arg);
5704 return Arg;
5705 }
5706 }
5707
Richard Smith87d263e2016-12-25 08:05:23 +00005708 // When checking a deduced template argument, deduce from its type even if
5709 // the type is dependent, in order to check the types of non-type template
5710 // arguments line up properly in partial ordering.
5711 Optional<unsigned> Depth;
5712 if (CTAK != CTAK_Specified)
5713 Depth = Param->getDepth() + 1;
Richard Smith5f274382016-09-28 23:55:27 +00005714 if (DeduceAutoType(
5715 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
Richard Smith87d263e2016-12-25 08:05:23 +00005716 Arg, ParamType, Depth) == DAR_Failed) {
Richard Smith5f274382016-09-28 23:55:27 +00005717 Diag(Arg->getExprLoc(),
5718 diag::err_non_type_template_parm_type_deduction_failure)
5719 << Param->getDeclName() << Param->getType() << Arg->getType()
5720 << Arg->getSourceRange();
5721 Diag(Param->getLocation(), diag::note_template_param_here);
5722 return ExprError();
5723 }
5724 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
5725 // an error. The error message normally references the parameter
5726 // declaration, but here we'll pass the argument location because that's
5727 // where the parameter type is deduced.
5728 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
5729 if (ParamType.isNull()) {
5730 Diag(Param->getLocation(), diag::note_template_param_here);
5731 return ExprError();
5732 }
5733 }
5734
Richard Smithd663fdd2014-12-17 20:42:37 +00005735 // We should have already dropped all cv-qualifiers by now.
5736 assert(!ParamType.hasQualifiers() &&
5737 "non-type template parameter type cannot be qualified");
5738
5739 if (CTAK == CTAK_Deduced &&
Richard Smithd92eddf2016-12-27 06:14:37 +00005740 !Context.hasSameType(ParamType.getNonLValueExprType(Context),
Richard Smith0e617ec2016-12-27 07:56:27 +00005741 Arg->getType())) {
Richard Smith957fbf12017-01-17 02:14:37 +00005742 // FIXME: If either type is dependent, we skip the check. This isn't
5743 // correct, since during deduction we're supposed to have replaced each
5744 // template parameter with some unique (non-dependent) placeholder.
5745 // FIXME: If the argument type contains 'auto', we carry on and fail the
5746 // type check in order to force specific types to be more specialized than
5747 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
5748 // work.
5749 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
5750 !Arg->getType()->getContainedAutoType()) {
5751 Converted = TemplateArgument(Arg);
5752 return Arg;
5753 }
5754 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
5755 // we should actually be checking the type of the template argument in P,
5756 // not the type of the template argument deduced from A, against the
5757 // template parameter type.
Richard Smithd663fdd2014-12-17 20:42:37 +00005758 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
Richard Smith0e617ec2016-12-27 07:56:27 +00005759 << Arg->getType()
Richard Smithd663fdd2014-12-17 20:42:37 +00005760 << ParamType.getUnqualifiedType();
5761 Diag(Param->getLocation(), diag::note_template_param_here);
5762 return ExprError();
5763 }
5764
Richard Smith87d263e2016-12-25 08:05:23 +00005765 // If either the parameter has a dependent type or the argument is
5766 // type-dependent, there's nothing we can check now.
5767 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
5768 // FIXME: Produce a cloned, canonical expression?
5769 Converted = TemplateArgument(Arg);
5770 return Arg;
5771 }
5772
Richard Smithe5945872017-01-06 22:52:53 +00005773 // The initialization of the parameter from the argument is
5774 // a constant-evaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00005775 EnterExpressionEvaluationContext ConstantEvaluated(
5776 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Richard Smithe5945872017-01-06 22:52:53 +00005777
Richard Smith410cc892014-11-26 03:26:53 +00005778 if (getLangOpts().CPlusPlus1z) {
Richard Smith410cc892014-11-26 03:26:53 +00005779 // C++1z [temp.arg.nontype]p1:
5780 // A template-argument for a non-type template parameter shall be
5781 // a converted constant expression of the type of the template-parameter.
5782 APValue Value;
5783 ExprResult ArgResult = CheckConvertedConstantExpression(
5784 Arg, ParamType, Value, CCEK_TemplateArg);
5785 if (ArgResult.isInvalid())
5786 return ExprError();
5787
Richard Smith52e624f2016-12-21 21:42:57 +00005788 // For a value-dependent argument, CheckConvertedConstantExpression is
5789 // permitted (and expected) to be unable to determine a value.
5790 if (ArgResult.get()->isValueDependent()) {
Richard Smith01bfa682016-12-27 02:02:09 +00005791 Converted = TemplateArgument(ArgResult.get());
5792 return ArgResult;
Richard Smith52e624f2016-12-21 21:42:57 +00005793 }
5794
Richard Smithd663fdd2014-12-17 20:42:37 +00005795 QualType CanonParamType = Context.getCanonicalType(ParamType);
5796
Richard Smith410cc892014-11-26 03:26:53 +00005797 // Convert the APValue to a TemplateArgument.
5798 switch (Value.getKind()) {
5799 case APValue::Uninitialized:
5800 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00005801 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005802 break;
5803 case APValue::Int:
5804 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00005805 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00005806 break;
5807 case APValue::MemberPointer: {
5808 assert(ParamType->isMemberPointerType());
5809
5810 // FIXME: We need TemplateArgument representation and mangling for these.
5811 if (!Value.getMemberPointerPath().empty()) {
5812 Diag(Arg->getLocStart(),
5813 diag::err_template_arg_member_ptr_base_derived_not_supported)
5814 << Value.getMemberPointerDecl() << ParamType
5815 << Arg->getSourceRange();
5816 return ExprError();
5817 }
5818
5819 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00005820 Converted = VD ? TemplateArgument(VD, CanonParamType)
5821 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005822 break;
5823 }
5824 case APValue::LValue: {
5825 // For a non-type template-parameter of pointer or reference type,
5826 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00005827 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
5828 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00005829 // -- a temporary object
5830 // -- a string literal
5831 // -- the result of a typeid expression, or
Eric Christopher0d2c56a2017-03-31 01:45:39 +00005832 // -- a predefined __func__ variable
Richard Smith410cc892014-11-26 03:26:53 +00005833 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
5834 if (isa<CXXUuidofExpr>(E)) {
5835 Converted = TemplateArgument(const_cast<Expr*>(E));
5836 break;
5837 }
5838 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5839 << Arg->getSourceRange();
5840 return ExprError();
5841 }
5842 auto *VD = const_cast<ValueDecl *>(
5843 Value.getLValueBase().dyn_cast<const ValueDecl *>());
5844 // -- a subobject
5845 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
5846 VD && VD->getType()->isArrayType() &&
5847 Value.getLValuePath()[0].ArrayIndex == 0 &&
5848 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
5849 // Per defect report (no number yet):
5850 // ... other than a pointer to the first element of a complete array
5851 // object.
5852 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
5853 Value.isLValueOnePastTheEnd()) {
5854 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
5855 << Value.getAsString(Context, ParamType);
5856 return ExprError();
5857 }
Richard Smithd663fdd2014-12-17 20:42:37 +00005858 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00005859 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00005860 assert((!VD || !ParamType->isNullPtrType()) &&
5861 "non-null value of type nullptr_t?");
5862 Converted = VD ? TemplateArgument(VD, CanonParamType)
5863 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005864 break;
5865 }
5866 case APValue::AddrLabelDiff:
5867 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
5868 case APValue::Float:
5869 case APValue::ComplexInt:
5870 case APValue::ComplexFloat:
5871 case APValue::Vector:
5872 case APValue::Array:
5873 case APValue::Struct:
5874 case APValue::Union:
5875 llvm_unreachable("invalid kind for template argument");
5876 }
5877
5878 return ArgResult.get();
5879 }
5880
Douglas Gregor86560402009-02-10 23:36:10 +00005881 // C++ [temp.arg.nontype]p5:
5882 // The following conversions are performed on each expression used
5883 // as a non-type template-argument. If a non-type
5884 // template-argument cannot be converted to the type of the
5885 // corresponding template-parameter then the program is
5886 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00005887 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00005888 // C++11:
5889 // -- for a non-type template-parameter of integral or
5890 // enumeration type, conversions permitted in a converted
5891 // constant expression are applied.
5892 //
5893 // C++98:
5894 // -- for a non-type template-parameter of integral or
5895 // enumeration type, integral promotions (4.5) and integral
5896 // conversions (4.7) are applied.
5897
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005898 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00005899 // C++ [temp.arg.nontype]p1:
5900 // A template-argument for a non-type, non-template template-parameter
5901 // shall be one of:
5902 //
5903 // -- for a non-type template-parameter of integral or enumeration
5904 // type, a converted constant expression of the type of the
5905 // template-parameter; or
5906 llvm::APSInt Value;
5907 ExprResult ArgResult =
5908 CheckConvertedConstantExpression(Arg, ParamType, Value,
5909 CCEK_TemplateArg);
5910 if (ArgResult.isInvalid())
5911 return ExprError();
5912
Richard Smith01bfa682016-12-27 02:02:09 +00005913 // We can't check arbitrary value-dependent arguments.
5914 if (ArgResult.get()->isValueDependent()) {
5915 Converted = TemplateArgument(ArgResult.get());
5916 return ArgResult;
5917 }
5918
Richard Smithf8379a02012-01-18 23:55:52 +00005919 // Widen the argument value to sizeof(parameter type). This is almost
5920 // always a no-op, except when the parameter type is bool. In
5921 // that case, this may extend the argument from 1 bit to 8 bits.
5922 QualType IntegerType = ParamType;
5923 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5924 IntegerType = Enum->getDecl()->getIntegerType();
5925 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
5926
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005927 Converted = TemplateArgument(Context, Value,
5928 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00005929 return ArgResult;
5930 }
5931
Richard Smith08b12f12011-10-27 22:11:44 +00005932 ExprResult ArgResult = DefaultLvalueConversion(Arg);
5933 if (ArgResult.isInvalid())
5934 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005935 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00005936
5937 QualType ArgType = Arg->getType();
5938
Douglas Gregor86560402009-02-10 23:36:10 +00005939 // C++ [temp.arg.nontype]p1:
5940 // A template-argument for a non-type, non-template
5941 // template-parameter shall be one of:
5942 //
5943 // -- an integral constant-expression of integral or enumeration
5944 // type; or
5945 // -- the name of a non-type template-parameter; or
5946 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005947 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00005948 if (!ArgType->isIntegralOrEnumerationType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005949 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005950 diag::err_template_arg_not_integral_or_enumeral)
5951 << ArgType << Arg->getSourceRange();
5952 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005953 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00005954 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005955 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
5956 QualType T;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005957
Douglas Gregore2b37442012-05-04 22:38:52 +00005958 public:
5959 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00005960
5961 void diagnoseNotICE(Sema &S, SourceLocation Loc,
5962 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00005963 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
5964 }
5965 } Diagnoser(ArgType);
5966
5967 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005968 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00005969 if (!Arg)
5970 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005971 }
5972
Richard Smithd663fdd2014-12-17 20:42:37 +00005973 // From here on out, all we care about is the unqualified form
5974 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005975 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00005976
5977 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00005978 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00005979 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00005980 } else if (ParamType->isBooleanType()) {
5981 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005982 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005983 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
5984 !ParamType->isEnumeralType()) {
5985 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005986 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005987 } else {
5988 // We can't perform this conversion.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005989 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005990 diag::err_template_arg_not_convertible)
Richard Smithd663fdd2014-12-17 20:42:37 +00005991 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00005992 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005993 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005994 }
5995
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005996 // Add the value of this argument to the list of converted
5997 // arguments. We use the bitwidth and signedness of the template
5998 // parameter.
5999 if (Arg->isValueDependent()) {
6000 // The argument is value-dependent. Create a new
6001 // TemplateArgument with the converted expression.
6002 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006003 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006004 }
6005
Douglas Gregor52aba872009-03-14 00:20:21 +00006006 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00006007 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00006008 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00006009
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006010 if (ParamType->isBooleanType()) {
6011 // Value must be zero or one.
6012 Value = Value != 0;
6013 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6014 if (Value.getBitWidth() != AllowedBits)
6015 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006016 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006017 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006018 llvm::APSInt OldValue = Value;
Simon Pilgrim6905d222016-12-30 22:55:33 +00006019
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006020 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006021 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00006022 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00006023 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006024 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006025 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Simon Pilgrim6905d222016-12-30 22:55:33 +00006026
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006027 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006028 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006029 && (OldValue.isSigned() && OldValue.isNegative())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006030 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006031 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6032 << Arg->getSourceRange();
6033 Diag(Param->getLocation(), diag::note_template_param_here);
6034 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006035
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006036 // Complain if we overflowed the template parameter's type.
6037 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006038 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006039 RequiredBits = OldValue.getActiveBits();
6040 else if (OldValue.isUnsigned())
6041 RequiredBits = OldValue.getActiveBits() + 1;
6042 else
6043 RequiredBits = OldValue.getMinSignedBits();
6044 if (RequiredBits > AllowedBits) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006045 Diag(Arg->getLocStart(),
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006046 diag::warn_template_arg_too_large)
6047 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6048 << Arg->getSourceRange();
6049 Diag(Param->getLocation(), diag::note_template_param_here);
6050 }
Douglas Gregor52aba872009-03-14 00:20:21 +00006051 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00006052
Benjamin Kramer6003ad52012-06-07 15:09:51 +00006053 Converted = TemplateArgument(Context, Value,
Simon Pilgrim6905d222016-12-30 22:55:33 +00006054 ParamType->isEnumeralType()
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00006055 ? Context.getCanonicalType(ParamType)
6056 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006057 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00006058 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006059
Richard Smith08b12f12011-10-27 22:11:44 +00006060 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00006061 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
6062
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006063 // Handle pointer-to-function, reference-to-function, and
6064 // pointer-to-member-function all in (roughly) the same way.
6065 if (// -- For a non-type template-parameter of type pointer to
6066 // function, only the function-to-pointer conversion (4.3) is
6067 // applied. If the template-argument represents a set of
6068 // overloaded functions (or a pointer to such), the matching
6069 // function is selected from the set (13.4).
6070 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006071 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006072 // -- For a non-type template-parameter of type reference to
6073 // function, no conversions apply. If the template-argument
6074 // represents a set of overloaded functions, the matching
6075 // function is selected from the set (13.4).
6076 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006077 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006078 // -- For a non-type template-parameter of type pointer to
6079 // member function, no conversions apply. If the
6080 // template-argument represents a set of overloaded member
6081 // functions, the matching member function is selected from
6082 // the set (13.4).
6083 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006084 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006085 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006086
Douglas Gregor064fdb22010-04-14 23:11:21 +00006087 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006088 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00006089 true,
6090 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006091 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00006092 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00006093
6094 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6095 ArgType = Arg->getType();
6096 } else
John Wiegley01296292011-04-08 18:41:53 +00006097 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006098 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006099
John Wiegley01296292011-04-08 18:41:53 +00006100 if (!ParamType->isMemberPointerType()) {
6101 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6102 ParamType,
6103 Arg, Converted))
6104 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006105 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00006106 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00006107
Douglas Gregor20fdef32012-04-10 17:08:25 +00006108 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6109 Converted))
John Wiegley01296292011-04-08 18:41:53 +00006110 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006111 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006112 }
6113
Chris Lattner696197c2009-02-20 21:37:53 +00006114 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006115 // -- for a non-type template-parameter of type pointer to
6116 // object, qualification conversions (4.4) and the
6117 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00006118 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00006119 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006120 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00006121
John Wiegley01296292011-04-08 18:41:53 +00006122 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6123 ParamType,
6124 Arg, Converted))
6125 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006126 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00006127 }
Mike Stump11289f42009-09-09 15:08:12 +00006128
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006129 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006130 // -- For a non-type template-parameter of type reference to
6131 // object, no conversions apply. The type referred to by the
6132 // reference may be more cv-qualified than the (otherwise
6133 // identical) type of the template-argument. The
6134 // template-parameter is bound directly to the
6135 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00006136 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006137 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00006138
Douglas Gregor064fdb22010-04-14 23:11:21 +00006139 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006140 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
6141 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00006142 true,
6143 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006144 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00006145 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00006146
6147 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6148 ArgType = Arg->getType();
6149 } else
John Wiegley01296292011-04-08 18:41:53 +00006150 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006151 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006152
John Wiegley01296292011-04-08 18:41:53 +00006153 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6154 ParamType,
6155 Arg, Converted))
6156 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006157 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006158 }
Douglas Gregor0e558532009-02-11 16:16:59 +00006159
Douglas Gregor20fdef32012-04-10 17:08:25 +00006160 // Deal with parameters of type std::nullptr_t.
6161 if (ParamType->isNullPtrType()) {
6162 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6163 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006164 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006165 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006166
Douglas Gregor20fdef32012-04-10 17:08:25 +00006167 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
6168 case NPV_NotNullPointer:
6169 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
6170 << Arg->getType() << ParamType;
6171 Diag(Param->getLocation(), diag::note_template_param_here);
6172 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00006173
Douglas Gregor20fdef32012-04-10 17:08:25 +00006174 case NPV_Error:
6175 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00006176
Douglas Gregor20fdef32012-04-10 17:08:25 +00006177 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00006178 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00006179 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
6180 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006181 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006182 }
6183 }
6184
Douglas Gregor0e558532009-02-11 16:16:59 +00006185 // -- For a non-type template-parameter of type pointer to data
6186 // member, qualification conversions (4.4) are applied.
6187 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
6188
Douglas Gregor20fdef32012-04-10 17:08:25 +00006189 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6190 Converted))
John Wiegley01296292011-04-08 18:41:53 +00006191 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006192 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00006193}
6194
Richard Smith26b86ea2016-12-31 21:41:23 +00006195static void DiagnoseTemplateParameterListArityMismatch(
6196 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
6197 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
6198
Douglas Gregord32e0282009-02-09 23:23:08 +00006199/// \brief Check a template argument against its corresponding
6200/// template template parameter.
6201///
6202/// This routine implements the semantics of C++ [temp.arg.template].
6203/// It returns true if an error occurred, and false otherwise.
6204bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00006205 TemplateArgumentLoc &Arg,
Richard Smith1fde8ec2012-09-07 02:06:42 +00006206 unsigned ArgumentPackIndex) {
Eli Friedmanb826a002012-09-26 02:36:12 +00006207 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006208 TemplateDecl *Template = Name.getAsTemplateDecl();
6209 if (!Template) {
6210 // Any dependent template name is fine.
6211 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
6212 return false;
6213 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00006214
Richard Smith26b86ea2016-12-31 21:41:23 +00006215 if (Template->isInvalidDecl())
6216 return true;
6217
Richard Smith3f1b5d02011-05-05 21:57:07 +00006218 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00006219 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00006220 // the name of a class template or an alias template, expressed as an
6221 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00006222 // primary class templates are considered when matching the
6223 // template template argument with the corresponding parameter;
6224 // partial specializations are not considered even if their
6225 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00006226 //
6227 // Note that we also allow template template parameters here, which
6228 // will happen when we are dealing with, e.g., class template
6229 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00006230 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00006231 !isa<TemplateTemplateParmDecl>(Template) &&
David Majnemerc2406d42016-07-11 17:09:56 +00006232 !isa<TypeAliasTemplateDecl>(Template) &&
6233 !isa<BuiltinTemplateDecl>(Template)) {
6234 assert(isa<FunctionTemplateDecl>(Template) &&
6235 "Only function templates are possible here");
Faisal Valib8b04f82016-03-26 20:46:45 +00006236 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
David Majnemerc2406d42016-07-11 17:09:56 +00006237 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
6238 << Template;
Douglas Gregor85e0f662009-02-10 00:24:35 +00006239 }
6240
Richard Smith1fde8ec2012-09-07 02:06:42 +00006241 TemplateParameterList *Params = Param->getTemplateParameters();
6242 if (Param->isExpandedParameterPack())
6243 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
6244
Richard Smith26b86ea2016-12-31 21:41:23 +00006245 // C++1z [temp.arg.template]p3: (DR 150)
6246 // A template-argument matches a template template-parameter P when P
6247 // is at least as specialized as the template-argument A.
6248 if (getLangOpts().RelaxedTemplateTemplateArgs) {
6249 // Quick check for the common case:
6250 // If P contains a parameter pack, then A [...] matches P if each of A's
6251 // template parameters matches the corresponding template parameter in
6252 // the template-parameter-list of P.
6253 if (TemplateParameterListsAreEqual(
6254 Template->getTemplateParameters(), Params, false,
6255 TPL_TemplateTemplateArgumentMatch, Arg.getLocation()))
6256 return false;
6257
6258 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
6259 Arg.getLocation()))
6260 return false;
6261 // FIXME: Produce better diagnostics for deduction failures.
6262 }
6263
Douglas Gregor85e0f662009-02-10 00:24:35 +00006264 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00006265 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006266 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006267 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006268 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00006269}
6270
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006271/// \brief Given a non-type template argument that refers to a
6272/// declaration and the type of its corresponding non-type template
6273/// parameter, produce an expression that properly refers to that
6274/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006275ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006276Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6277 QualType ParamType,
6278 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00006279 // C++ [temp.param]p8:
6280 //
6281 // A non-type template-parameter of type "array of T" or
6282 // "function returning T" is adjusted to be of type "pointer to
6283 // T" or "pointer to function returning T", respectively.
6284 if (ParamType->isArrayType())
6285 ParamType = Context.getArrayDecayedType(ParamType);
6286 else if (ParamType->isFunctionType())
6287 ParamType = Context.getPointerType(ParamType);
6288
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006289 // For a NULL non-type template argument, return nullptr casted to the
6290 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00006291 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006292 return ImpCastExprToType(
6293 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
6294 ParamType,
6295 ParamType->getAs<MemberPointerType>()
6296 ? CK_NullToMemberPointer
6297 : CK_NullToPointer);
6298 }
Eli Friedmanb826a002012-09-26 02:36:12 +00006299 assert(Arg.getKind() == TemplateArgument::Declaration &&
6300 "Only declaration template arguments permitted here");
6301
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006302 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
6303
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006304 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00006305 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
6306 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006307 // If the value is a class member, we might have a pointer-to-member.
6308 // Determine whether the non-type template template parameter is of
6309 // pointer-to-member type. If so, we need to build an appropriate
6310 // expression for a pointer-to-member, since a "normal" DeclRefExpr
6311 // would refer to the member itself.
6312 if (ParamType->isMemberPointerType()) {
6313 QualType ClassType
6314 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
6315 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00006316 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00006317 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006318 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00006319 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00006320
6321 // The actual value-ness of this is unimportant, but for
6322 // internal consistency's sake, references to instance methods
6323 // are r-values.
6324 ExprValueKind VK = VK_LValue;
6325 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
6326 VK = VK_RValue;
6327
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006328 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00006329 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00006330 VK,
John McCall7decc9e2010-11-18 06:31:45 +00006331 Loc,
6332 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006333 if (RefExpr.isInvalid())
6334 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006335
John McCalle3027922010-08-25 11:45:40 +00006336 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006337
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006338 // We might need to perform a trailing qualification conversion, since
6339 // the element type on the parameter could be more qualified than the
6340 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00006341 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006342 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00006343 ParamType.getUnqualifiedType(), false,
6344 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006345 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006346
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006347 assert(!RefExpr.isInvalid() &&
6348 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006349 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006350 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006351 }
6352 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006353
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006354 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00006355
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006356 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006357 // When the non-type template parameter is a pointer, take the
6358 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00006359 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006360 if (RefExpr.isInvalid())
6361 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006362
Richard Smithfc6fca12017-01-28 00:38:35 +00006363 if (!Context.hasSameUnqualifiedType(ParamType->getPointeeType(), T) &&
6364 (T->isFunctionType() || T->isArrayType())) {
6365 // Decay functions and arrays unless we're forming a pointer to array.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006366 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00006367 if (RefExpr.isInvalid())
6368 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006369
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006370 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006371 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006372
Douglas Gregorb242683d2010-04-01 18:32:35 +00006373 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00006374 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006375 }
6376
John McCall7decc9e2010-11-18 06:31:45 +00006377 ExprValueKind VK = VK_RValue;
6378
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006379 // If the non-type template parameter has reference type, qualify the
6380 // resulting declaration reference with the extra qualifiers on the
6381 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00006382 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
6383 VK = VK_LValue;
6384 T = Context.getQualifiedType(T,
6385 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00006386 } else if (isa<FunctionDecl>(VD)) {
6387 // References to functions are always lvalues.
6388 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00006389 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006390
John McCall7decc9e2010-11-18 06:31:45 +00006391 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006392}
6393
6394/// \brief Construct a new expression that refers to the given
6395/// integral template argument with the given source-location
6396/// information.
6397///
6398/// This routine takes care of the mapping from an integral template
6399/// argument (which may have any integral type) to the appropriate
6400/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006401ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006402Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6403 SourceLocation Loc) {
6404 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00006405 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006406 QualType OrigT = Arg.getIntegralType();
6407
6408 // If this is an enum type that we're instantiating, we need to use an integer
6409 // type the same size as the enumerator. We don't want to build an
6410 // IntegerLiteral with enum type. The integer type of an enum type can be of
6411 // any integral type with C++11 enum classes, make sure we create the right
6412 // type of literal for it.
6413 QualType T = OrigT;
6414 if (const EnumType *ET = OrigT->getAs<EnumType>())
6415 T = ET->getDecl()->getIntegerType();
6416
6417 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00006418 if (T->isAnyCharacterType()) {
Aaron Ballman9a17c852016-01-07 20:59:26 +00006419 // This does not need to handle u8 character literals because those are
6420 // of type char, and so can also be covered by an ASCII character literal.
Douglas Gregorfb65e592011-07-27 05:40:30 +00006421 CharacterLiteral::CharacterKind Kind;
6422 if (T->isWideCharType())
6423 Kind = CharacterLiteral::Wide;
6424 else if (T->isChar16Type())
6425 Kind = CharacterLiteral::UTF16;
6426 else if (T->isChar32Type())
6427 Kind = CharacterLiteral::UTF32;
6428 else
6429 Kind = CharacterLiteral::Ascii;
6430
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006431 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
6432 Kind, T, Loc);
6433 } else if (T->isBooleanType()) {
6434 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
6435 T, Loc);
6436 } else if (T->isNullPtrType()) {
6437 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
6438 } else {
6439 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00006440 }
6441
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006442 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00006443 // FIXME: This is a hack. We need a better way to handle substituted
6444 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00006445 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
6446 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006447 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00006448 Loc, Loc);
6449 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006450
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006451 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006452}
6453
Douglas Gregor641040a2011-01-12 23:45:44 +00006454/// \brief Match two template parameters within template parameter lists.
6455static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
6456 bool Complain,
6457 Sema::TemplateParameterListEqualKind Kind,
6458 SourceLocation TemplateArgLoc) {
6459 // Check the actual kind (type, non-type, template).
6460 if (Old->getKind() != New->getKind()) {
6461 if (Complain) {
6462 unsigned NextDiag = diag::err_template_param_different_kind;
6463 if (TemplateArgLoc.isValid()) {
6464 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6465 NextDiag = diag::note_template_param_different_kind;
6466 }
6467 S.Diag(New->getLocation(), NextDiag)
6468 << (Kind != Sema::TPL_TemplateMatch);
6469 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
6470 << (Kind != Sema::TPL_TemplateMatch);
6471 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006472
Douglas Gregor641040a2011-01-12 23:45:44 +00006473 return false;
6474 }
6475
Richard Smith26b86ea2016-12-31 21:41:23 +00006476 // Check that both are parameter packs or neither are parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006477 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006478 // template template parameter, the template template parameter can have
6479 // a parameter pack where the template template argument does not.
6480 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
6481 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
6482 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00006483 if (Complain) {
6484 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
6485 if (TemplateArgLoc.isValid()) {
6486 S.Diag(TemplateArgLoc,
6487 diag::err_template_arg_template_params_mismatch);
6488 NextDiag = diag::note_template_parameter_pack_non_pack;
6489 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006490
Douglas Gregor641040a2011-01-12 23:45:44 +00006491 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
6492 : isa<NonTypeTemplateParmDecl>(New)? 1
6493 : 2;
6494 S.Diag(New->getLocation(), NextDiag)
6495 << ParamKind << New->isParameterPack();
6496 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
6497 << ParamKind << Old->isParameterPack();
6498 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006499
Douglas Gregor641040a2011-01-12 23:45:44 +00006500 return false;
6501 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006502
Douglas Gregor641040a2011-01-12 23:45:44 +00006503 // For non-type template parameters, check the type of the parameter.
6504 if (NonTypeTemplateParmDecl *OldNTTP
6505 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
6506 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006507
Douglas Gregor641040a2011-01-12 23:45:44 +00006508 // If we are matching a template template argument to a template
6509 // template parameter and one of the non-type template parameter types
Richard Smith13894182017-04-13 21:37:24 +00006510 // is dependent, then we must wait until template instantiation time
6511 // to actually compare the arguments.
Douglas Gregor641040a2011-01-12 23:45:44 +00006512 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
Richard Smith13894182017-04-13 21:37:24 +00006513 (OldNTTP->getType()->isDependentType() ||
6514 NewNTTP->getType()->isDependentType()))
Douglas Gregor641040a2011-01-12 23:45:44 +00006515 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006516
Douglas Gregor641040a2011-01-12 23:45:44 +00006517 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
6518 if (Complain) {
6519 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
6520 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006521 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00006522 diag::err_template_arg_template_params_mismatch);
6523 NextDiag = diag::note_template_nontype_parm_different_type;
6524 }
6525 S.Diag(NewNTTP->getLocation(), NextDiag)
6526 << NewNTTP->getType()
6527 << (Kind != Sema::TPL_TemplateMatch);
6528 S.Diag(OldNTTP->getLocation(),
6529 diag::note_template_nontype_parm_prev_declaration)
6530 << OldNTTP->getType();
6531 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006532
Douglas Gregor641040a2011-01-12 23:45:44 +00006533 return false;
6534 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006535
Douglas Gregor641040a2011-01-12 23:45:44 +00006536 return true;
6537 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006538
Douglas Gregor641040a2011-01-12 23:45:44 +00006539 // For template template parameters, check the template parameter types.
6540 // The template parameter lists of template template
6541 // parameters must agree.
6542 if (TemplateTemplateParmDecl *OldTTP
6543 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006544 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00006545 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
6546 OldTTP->getTemplateParameters(),
6547 Complain,
6548 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006549 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00006550 : Kind),
6551 TemplateArgLoc);
6552 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006553
Douglas Gregor641040a2011-01-12 23:45:44 +00006554 return true;
6555}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006556
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006557/// \brief Diagnose a known arity mismatch when comparing template argument
6558/// lists.
6559static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006560void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006561 TemplateParameterList *New,
6562 TemplateParameterList *Old,
6563 Sema::TemplateParameterListEqualKind Kind,
6564 SourceLocation TemplateArgLoc) {
6565 unsigned NextDiag = diag::err_template_param_list_different_arity;
6566 if (TemplateArgLoc.isValid()) {
6567 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6568 NextDiag = diag::note_template_param_list_different_arity;
6569 }
6570 S.Diag(New->getTemplateLoc(), NextDiag)
6571 << (New->size() > Old->size())
6572 << (Kind != Sema::TPL_TemplateMatch)
6573 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
6574 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
6575 << (Kind != Sema::TPL_TemplateMatch)
6576 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
6577}
6578
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006579/// \brief Determine whether the given template parameter lists are
6580/// equivalent.
6581///
Mike Stump11289f42009-09-09 15:08:12 +00006582/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006583/// source code as part of a new template declaration.
6584///
6585/// \param Old The old template parameter list, typically found via
6586/// name lookup of the template declared with this template parameter
6587/// list.
6588///
6589/// \param Complain If true, this routine will produce a diagnostic if
6590/// the template parameter lists are not equivalent.
6591///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006592/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00006593///
6594/// \param TemplateArgLoc If this source location is valid, then we
6595/// are actually checking the template parameter list of a template
6596/// argument (New) against the template parameter list of its
6597/// corresponding template template parameter (Old). We produce
6598/// slightly different diagnostics in this scenario.
6599///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006600/// \returns True if the template parameter lists are equal, false
6601/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00006602bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006603Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
6604 TemplateParameterList *Old,
6605 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006606 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00006607 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006608 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
6609 if (Complain)
6610 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6611 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006612
6613 return false;
6614 }
6615
Douglas Gregor641040a2011-01-12 23:45:44 +00006616 // C++0x [temp.arg.template]p3:
6617 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00006618 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00006619 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00006620 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006621 // template-parameter-list of P. [...]
6622 TemplateParameterList::iterator NewParm = New->begin();
6623 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006624 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006625 OldParmEnd = Old->end();
6626 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00006627 if (Kind != TPL_TemplateTemplateArgumentMatch ||
6628 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006629 if (NewParm == NewParmEnd) {
6630 if (Complain)
6631 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6632 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006633
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006634 return false;
6635 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006636
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006637 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6638 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006639 return false;
6640
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006641 ++NewParm;
6642 continue;
6643 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006644
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006645 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00006646 // [...] When P's template- parameter-list contains a template parameter
6647 // pack (14.5.3), the template parameter pack will match zero or more
6648 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006649 // template-parameter-list of A with the same type and form as the
6650 // template parameter pack in P (ignoring whether those template
6651 // parameters are template parameter packs).
6652 for (; NewParm != NewParmEnd; ++NewParm) {
6653 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6654 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006655 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006656 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006657 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006658
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006659 // Make sure we exhausted all of the arguments.
6660 if (NewParm != NewParmEnd) {
6661 if (Complain)
6662 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6663 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006664
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006665 return false;
6666 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006667
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006668 return true;
6669}
6670
6671/// \brief Check whether a template can be declared within this scope.
6672///
6673/// If the template declaration is valid in this scope, returns
6674/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00006675bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006676Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00006677 if (!S)
6678 return false;
6679
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006680 // Find the nearest enclosing declaration scope.
6681 while ((S->getFlags() & Scope::DeclScope) == 0 ||
6682 (S->getFlags() & Scope::TemplateParamScope) != 0)
6683 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00006684
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00006685 // C++ [temp]p4:
6686 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00006687 DeclContext *Ctx = S->getEntity();
Alex Lorenz560ae562016-11-02 15:46:34 +00006688 if (Ctx && Ctx->isExternCContext()) {
6689 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
6690 << TemplateParams->getSourceRange();
6691 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
6692 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
6693 return true;
6694 }
Richard Smith8df390f2016-09-08 23:14:54 +00006695 Ctx = Ctx->getRedeclContext();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006696
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00006697 // C++ [temp]p2:
6698 // A template-declaration can appear only as a namespace scope or
6699 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00006700 if (Ctx) {
6701 if (Ctx->isFileContext())
6702 return false;
6703 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
6704 // C++ [temp.mem]p2:
6705 // A local class shall not have member templates.
6706 if (RD->isLocalClass())
6707 return Diag(TemplateParams->getTemplateLoc(),
6708 diag::err_template_inside_local_class)
6709 << TemplateParams->getSourceRange();
6710 else
6711 return false;
6712 }
6713 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006714
Mike Stump11289f42009-09-09 15:08:12 +00006715 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006716 diag::err_template_outside_namespace_or_class_scope)
6717 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006718}
Douglas Gregor67a65642009-02-17 23:15:12 +00006719
Douglas Gregor54888652009-10-07 00:13:32 +00006720/// \brief Determine what kind of template specialization the given declaration
6721/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006722static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00006723 if (!D)
6724 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006725
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006726 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
6727 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00006728 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
6729 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00006730 if (VarDecl *Var = dyn_cast<VarDecl>(D))
6731 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006732
Douglas Gregor54888652009-10-07 00:13:32 +00006733 return TSK_Undeclared;
6734}
6735
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006736/// \brief Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006737/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00006738///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006739/// This routine determines whether a template specialization can be declared
6740/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00006741///
6742/// \param S the semantic analysis object for which this check is being
6743/// performed.
6744///
6745/// \param Specialized the entity being specialized or instantiated, which
6746/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006747/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00006748/// member class).
6749///
6750/// \param PrevDecl the previous declaration of this entity, if any.
6751///
6752/// \param Loc the location of the explicit specialization or instantiation of
6753/// this entity.
6754///
6755/// \param IsPartialSpecialization whether this is a partial specialization of
6756/// a class template.
6757///
Douglas Gregor54888652009-10-07 00:13:32 +00006758/// \returns true if there was an error that we cannot recover from, false
6759/// otherwise.
6760static bool CheckTemplateSpecializationScope(Sema &S,
6761 NamedDecl *Specialized,
6762 NamedDecl *PrevDecl,
6763 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006764 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00006765 // Keep these "kind" numbers in sync with the %select statements in the
6766 // various diagnostics emitted by this routine.
6767 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00006768 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006769 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006770 else if (isa<VarTemplateDecl>(Specialized))
6771 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00006772 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006773 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006774 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006775 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006776 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00006777 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006778 else if (isa<RecordDecl>(Specialized))
6779 EntityKind = 7;
6780 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
6781 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00006782 else {
Richard Smith7d137e32012-03-23 03:33:32 +00006783 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006784 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006785 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00006786 return true;
6787 }
6788
Douglas Gregorf47b9112009-02-25 22:02:03 +00006789 // C++ [temp.expl.spec]p2:
6790 // An explicit specialization shall be declared in the namespace
6791 // of which the template is a member, or, for member templates, in
6792 // the namespace of which the enclosing class or enclosing class
6793 // template is a member. An explicit specialization of a member
6794 // function, member class or static data member of a class
6795 // template shall be declared in the namespace of which the class
6796 // template is a member. Such a declaration may also be a
6797 // definition. If the declaration is not a definition, the
6798 // specialization may be defined later in the name- space in which
6799 // the explicit specialization was declared, or in a namespace
6800 // that encloses the one in which the explicit specialization was
6801 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00006802 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00006803 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006804 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00006805 return true;
6806 }
Douglas Gregore4b05162009-10-07 17:21:34 +00006807
Douglas Gregor40fb7442009-10-07 17:30:37 +00006808 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006809 if (S.getLangOpts().MicrosoftExt) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006810 // Do not warn for class scope explicit specialization during
6811 // instantiation, warning was already emitted during pattern
6812 // semantic analysis.
Richard Smith51ec0cf2017-02-21 01:17:38 +00006813 if (!S.inTemplateInstantiation())
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006814 S.Diag(Loc, diag::ext_function_specialization_in_class)
6815 << Specialized;
6816 } else {
6817 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
6818 << Specialized;
6819 return true;
6820 }
Douglas Gregor40fb7442009-10-07 17:30:37 +00006821 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006822
Douglas Gregor44e5a0a2011-10-20 16:41:18 +00006823 if (S.CurContext->isRecord() &&
6824 !S.CurContext->Equals(Specialized->getDeclContext())) {
6825 // Make sure that we're specializing in the right record context.
6826 // Otherwise, things can go horribly wrong.
6827 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
6828 << Specialized;
6829 return true;
6830 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006831
Douglas Gregore4b05162009-10-07 17:21:34 +00006832 // C++ [temp.class.spec]p6:
6833 // A class template partial specialization may be declared or redeclared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006834 // in any namespace scope in which its definition may be defined (14.5.1
6835 // and 14.5.2).
Richard Smitha98f8fc2013-12-07 05:09:50 +00006836 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00006837 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00006838 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00006839
6840 // Make sure that this redeclaration (or definition) occurs in an enclosing
6841 // namespace.
6842 // Note that HandleDeclarator() performs this check for explicit
6843 // specializations of function templates, static data members, and member
6844 // functions, so we skip the check here for those kinds of entities.
6845 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
6846 // Should we refactor that check, so that it occurs later?
6847 if (!DC->Encloses(SpecializedContext) &&
6848 !(isa<FunctionTemplateDecl>(Specialized) ||
6849 isa<FunctionDecl>(Specialized) ||
6850 isa<VarTemplateDecl>(Specialized) ||
6851 isa<VarDecl>(Specialized))) {
6852 if (isa<TranslationUnitDecl>(SpecializedContext))
6853 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
6854 << EntityKind << Specialized;
Alexey Bataev0068cb22015-03-20 07:21:46 +00006855 else if (isa<NamespaceDecl>(SpecializedContext)) {
6856 int Diag = diag::err_template_spec_redecl_out_of_scope;
6857 if (S.getLangOpts().MicrosoftExt)
6858 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
6859 S.Diag(Loc, Diag) << EntityKind << Specialized
6860 << cast<NamedDecl>(SpecializedContext);
6861 } else
Richard Smitha98f8fc2013-12-07 05:09:50 +00006862 llvm_unreachable("unexpected namespace context for specialization");
6863
6864 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
6865 } else if ((!PrevDecl ||
6866 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
6867 getTemplateSpecializationKind(PrevDecl) ==
6868 TSK_ImplicitInstantiation)) {
Douglas Gregorb1aab432010-09-12 05:08:28 +00006869 // C++ [temp.exp.spec]p2:
6870 // An explicit specialization shall be declared in the namespace of which
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006871 // the template is a member, or, for member templates, in the namespace
Douglas Gregorb1aab432010-09-12 05:08:28 +00006872 // of which the enclosing class or enclosing class template is a member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006873 // An explicit specialization of a member function, member class or
6874 // static data member of a class template shall be declared in the
Douglas Gregorb1aab432010-09-12 05:08:28 +00006875 // namespace of which the class template is a member.
6876 //
Richard Smitha98f8fc2013-12-07 05:09:50 +00006877 // C++11 [temp.expl.spec]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006878 // An explicit specialization shall be declared in a namespace enclosing
Douglas Gregorb1aab432010-09-12 05:08:28 +00006879 // the specialized template.
Richard Smitha98f8fc2013-12-07 05:09:50 +00006880 // C++11 [temp.explicit]p3:
6881 // An explicit instantiation shall appear in an enclosing namespace of its
6882 // template.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006883 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006884 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
Richard Smith0bf8a4922011-10-18 20:49:44 +00006885 if (isa<TranslationUnitDecl>(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006886 assert(!IsCPlusPlus11Extension &&
Richard Smith0bf8a4922011-10-18 20:49:44 +00006887 "DC encloses TU but isn't in enclosing namespace set");
6888 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor8ce63152010-09-12 05:24:55 +00006889 << EntityKind << Specialized;
Richard Smith0bf8a4922011-10-18 20:49:44 +00006890 } else if (isa<NamespaceDecl>(SpecializedContext)) {
6891 int Diag;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006892 if (!IsCPlusPlus11Extension)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006893 Diag = diag::err_template_spec_decl_out_of_scope;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006894 else if (!S.getLangOpts().CPlusPlus11)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006895 Diag = diag::ext_template_spec_decl_out_of_scope;
6896 else
6897 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
6898 S.Diag(Loc, Diag)
6899 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
6900 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006901
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006902 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00006903 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006904 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006905
Douglas Gregorf47b9112009-02-25 22:02:03 +00006906 return false;
6907}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006908
Richard Smith57aae072016-12-28 02:37:25 +00006909static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
6910 if (!E->isTypeDependent())
Richard Smith6056d5e2014-02-09 00:54:43 +00006911 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00006912 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00006913 Checker.TraverseStmt(E);
Richard Smith57aae072016-12-28 02:37:25 +00006914 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00006915 return E->getSourceRange();
6916 return Checker.MatchLoc;
6917}
6918
6919static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
6920 if (!TL.getType()->isDependentType())
6921 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00006922 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00006923 Checker.TraverseTypeLoc(TL);
Richard Smith57aae072016-12-28 02:37:25 +00006924 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00006925 return TL.getSourceRange();
6926 return Checker.MatchLoc;
6927}
6928
Larisse Voufo39a1e502013-08-06 01:03:05 +00006929/// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006930/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006931static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006932 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
6933 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006934 for (unsigned I = 0; I != NumArgs; ++I) {
6935 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006936 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006937 S, TemplateNameLoc, Param, Args[I].pack_begin(),
6938 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006939 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006940
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006941 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006942 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006943
Eli Friedmanb826a002012-09-26 02:36:12 +00006944 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006945 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00006946
6947 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006948
Douglas Gregor98318c22011-01-03 21:37:45 +00006949 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006950 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
6951 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00006952
6953 // Strip off any implicit casts we added as part of type checking.
6954 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
6955 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006956
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006957 // C++ [temp.class.spec]p8:
6958 // A non-type argument is non-specialized if it is the name of a
6959 // non-type parameter. All other non-type arguments are
6960 // specialized.
6961 //
6962 // Below, we check the two conditions that only apply to
6963 // specialized non-type arguments, so skip any non-specialized
6964 // arguments.
6965 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00006966 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006967 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006968
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006969 // C++ [temp.class.spec]p9:
6970 // Within the argument list of a class template partial
6971 // specialization, the following restrictions apply:
6972 // -- A partially specialized non-type argument expression
6973 // shall not involve a template parameter of the partial
6974 // specialization except when the argument expression is a
6975 // simple identifier.
Richard Smith57aae072016-12-28 02:37:25 +00006976 // -- The type of a template parameter corresponding to a
6977 // specialized non-type argument shall not be dependent on a
6978 // parameter of the specialization.
6979 // DR1315 removes the first bullet, leaving an incoherent set of rules.
6980 // We implement a compromise between the original rules and DR1315:
6981 // -- A specialized non-type template argument shall not be
6982 // type-dependent and the corresponding template parameter
6983 // shall have a non-dependent type.
Richard Smith6056d5e2014-02-09 00:54:43 +00006984 SourceRange ParamUseRange =
Richard Smith57aae072016-12-28 02:37:25 +00006985 findTemplateParameterInType(Param->getDepth(), ArgExpr);
Richard Smith6056d5e2014-02-09 00:54:43 +00006986 if (ParamUseRange.isValid()) {
6987 if (IsDefaultArgument) {
6988 S.Diag(TemplateNameLoc,
6989 diag::err_dependent_non_type_arg_in_partial_spec);
6990 S.Diag(ParamUseRange.getBegin(),
6991 diag::note_dependent_non_type_default_arg_in_partial_spec)
6992 << ParamUseRange;
6993 } else {
6994 S.Diag(ParamUseRange.getBegin(),
6995 diag::err_dependent_non_type_arg_in_partial_spec)
6996 << ParamUseRange;
6997 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006998 return true;
6999 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007000
Richard Smith6056d5e2014-02-09 00:54:43 +00007001 ParamUseRange = findTemplateParameter(
Richard Smith57aae072016-12-28 02:37:25 +00007002 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
Richard Smith6056d5e2014-02-09 00:54:43 +00007003 if (ParamUseRange.isValid()) {
7004 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
7005 diag::err_dependent_typed_non_type_arg_in_partial_spec)
Richard Smith57aae072016-12-28 02:37:25 +00007006 << Param->getType();
Richard Smith6056d5e2014-02-09 00:54:43 +00007007 S.Diag(Param->getLocation(), diag::note_template_param_here)
Richard Smith57aae072016-12-28 02:37:25 +00007008 << (IsDefaultArgument ? ParamUseRange : SourceRange())
7009 << ParamUseRange;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007010 return true;
7011 }
7012 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007013
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007014 return false;
7015}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007016
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007017/// \brief Check the non-type template arguments of a class template
7018/// partial specialization according to C++ [temp.class.spec]p9.
7019///
Richard Smith6056d5e2014-02-09 00:54:43 +00007020/// \param TemplateNameLoc the location of the template name.
Simon Pilgrim6905d222016-12-30 22:55:33 +00007021/// \param PrimaryTemplate the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00007022/// template.
7023/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00007024/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00007025/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007026///
Richard Smith6056d5e2014-02-09 00:54:43 +00007027/// \returns \c true if there was an error, \c false otherwise.
Richard Smith57aae072016-12-28 02:37:25 +00007028bool Sema::CheckTemplatePartialSpecializationArgs(
7029 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
7030 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
7031 // We have to be conservative when checking a template in a dependent
7032 // context.
7033 if (PrimaryTemplate->getDeclContext()->isDependentContext())
7034 return false;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007035
Richard Smith57aae072016-12-28 02:37:25 +00007036 TemplateParameterList *TemplateParams =
7037 PrimaryTemplate->getTemplateParameters();
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007038 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7039 NonTypeTemplateParmDecl *Param
7040 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
7041 if (!Param)
7042 continue;
7043
Richard Smith57aae072016-12-28 02:37:25 +00007044 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
7045 Param, &TemplateArgs[I],
7046 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007047 return true;
7048 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007049
7050 return false;
7051}
7052
John McCall48871652010-08-21 09:40:31 +00007053DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00007054Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
7055 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00007056 SourceLocation KWLoc,
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00007057 SourceLocation ModulePrivateLoc,
Richard Smith4b55a9c2014-04-17 03:29:33 +00007058 TemplateIdAnnotation &TemplateId,
Douglas Gregor67a65642009-02-17 23:15:12 +00007059 AttributeList *Attr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00007060 MultiTemplateParamsArg
7061 TemplateParameterLists,
7062 SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00007063 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00007064
Richard Smith4b55a9c2014-04-17 03:29:33 +00007065 CXXScopeSpec &SS = TemplateId.SS;
7066
Abramo Bagnara60804e12011-03-18 15:16:37 +00007067 // NOTE: KWLoc is the location of the tag keyword. This will instead
7068 // store the location of the outermost template keyword in the declaration.
7069 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00007070 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
7071 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
7072 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
7073 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00007074
Douglas Gregor67a65642009-02-17 23:15:12 +00007075 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00007076 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00007077 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00007078 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
7079
7080 if (!ClassTemplate) {
7081 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007082 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00007083 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
7084 return true;
7085 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007086
Richard Smithf445f192017-02-09 21:04:43 +00007087 bool isMemberSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00007088 bool isPartialSpecialization = false;
7089
Douglas Gregorf47b9112009-02-25 22:02:03 +00007090 // Check the validity of the template headers that introduce this
7091 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00007092 // FIXME: We probably shouldn't complain about these headers for
7093 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007094 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00007095 TemplateParameterList *TemplateParams =
7096 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00007097 KWLoc, TemplateNameLoc, SS, &TemplateId,
Richard Smithf445f192017-02-09 21:04:43 +00007098 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
Richard Smith4b55a9c2014-04-17 03:29:33 +00007099 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007100 if (Invalid)
7101 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007102
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007103 if (TemplateParams && TemplateParams->size() > 0) {
7104 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007105
Douglas Gregorec9518b2010-12-21 08:14:57 +00007106 if (TUK == TUK_Friend) {
7107 Diag(KWLoc, diag::err_partial_specialization_friend)
7108 << SourceRange(LAngleLoc, RAngleLoc);
7109 return true;
7110 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007111
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007112 // C++ [temp.class.spec]p10:
7113 // The template parameter list of a specialization shall not
7114 // contain default template argument values.
7115 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7116 Decl *Param = TemplateParams->getParam(I);
7117 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
7118 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00007119 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007120 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00007121 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007122 }
7123 } else if (NonTypeTemplateParmDecl *NTTP
7124 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
7125 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00007126 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007127 diag::err_default_arg_in_partial_spec)
7128 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00007129 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007130 }
7131 } else {
7132 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00007133 if (TTP->hasDefaultArgument()) {
7134 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007135 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00007136 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00007137 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00007138 }
7139 }
7140 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007141 } else if (TemplateParams) {
7142 if (TUK == TUK_Friend)
7143 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00007144 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007145 SourceRange(TemplateParams->getTemplateLoc(),
7146 TemplateParams->getRAngleLoc()))
7147 << SourceRange(LAngleLoc, RAngleLoc);
Richard Smith4b55a9c2014-04-17 03:29:33 +00007148 } else {
7149 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007150 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00007151
Douglas Gregor67a65642009-02-17 23:15:12 +00007152 // Check that the specialization uses the same tag kind as the
7153 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007154 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7155 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00007156 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007157 Kind, TUK == TUK_Definition, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00007158 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007159 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00007160 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007161 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00007162 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007163 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00007164 diag::note_previous_use);
7165 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7166 }
7167
Douglas Gregorc40290e2009-03-09 23:48:35 +00007168 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00007169 TemplateArgumentListInfo TemplateArgs =
7170 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00007171
Douglas Gregor14406932011-01-03 20:35:03 +00007172 // Check for unexpanded parameter packs in any of the template arguments.
7173 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007174 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00007175 UPPC_PartialSpecialization))
7176 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007177
Douglas Gregor67a65642009-02-17 23:15:12 +00007178 // Check that the template argument list is well-formed for this
7179 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007180 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007181 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7182 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00007183 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00007184
Douglas Gregor2373c592009-05-31 09:31:02 +00007185 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00007186 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00007187 if (isPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00007188 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
7189 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007190 return true;
7191
Richard Smith57aae072016-12-28 02:37:25 +00007192 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
7193 // also do it during instantiation.
Douglas Gregor678d76c2011-07-01 01:22:09 +00007194 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007195 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00007196 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00007197 TemplateArgs.arguments(), InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00007198 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
7199 << ClassTemplate->getDeclName();
7200 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00007201 }
7202 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007203
Craig Topperc3ec1492014-05-26 06:22:03 +00007204 void *InsertPos = nullptr;
7205 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00007206
7207 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007208 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00007209 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00007210 else
Craig Topper7e0daca2014-06-26 04:58:53 +00007211 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00007212
Craig Topperc3ec1492014-05-26 06:22:03 +00007213 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00007214
Douglas Gregorf47b9112009-02-25 22:02:03 +00007215 // Check whether we can declare a class template specialization in
7216 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00007217 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007218 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
7219 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007220 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00007221 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007222
Douglas Gregor15301382009-07-30 17:40:51 +00007223 // The canonical type
7224 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00007225 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00007226 // Build the canonical type that describes the converted template
7227 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00007228 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7229 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00007230 Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007231
7232 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007233 ClassTemplate->getInjectedClassNameSpecialization())) {
7234 // C++ [temp.class.spec]p9b3:
7235 //
7236 // -- The argument list of the specialization shall not be identical
7237 // to the implicit argument list of the primary template.
Richard Smith0e617ec2016-12-27 07:56:27 +00007238 //
7239 // This rule has since been removed, because it's redundant given DR1495,
7240 // but we keep it because it produces better diagnostics and recovery.
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007241 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00007242 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00007243 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007244 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
7245 ClassTemplate->getIdentifier(),
7246 TemplateNameLoc,
7247 Attr,
7248 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00007249 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00007250 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00007251 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007252 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007253 }
Douglas Gregor15301382009-07-30 17:40:51 +00007254
Douglas Gregor2373c592009-05-31 09:31:02 +00007255 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00007256 ClassTemplatePartialSpecializationDecl *PrevPartial
7257 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007258 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00007259 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00007260 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007261 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00007262 TemplateParams,
7263 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007264 Converted,
John McCall6b51f282009-11-23 01:53:49 +00007265 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00007266 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00007267 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00007268 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007269 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Benjamin Kramer9cc210652015-08-05 09:40:49 +00007270 Partial->setTemplateParameterListsInfo(
7271 Context, TemplateParameterLists.drop_back(1));
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007272 }
Douglas Gregor2373c592009-05-31 09:31:02 +00007273
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007274 if (!PrevPartial)
7275 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00007276 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00007277
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007278 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00007279 // template specialization, make a note of that.
7280 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
7281 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007282
Richard Smith57aae072016-12-28 02:37:25 +00007283 CheckTemplatePartialSpecialization(Partial);
Douglas Gregor67a65642009-02-17 23:15:12 +00007284 } else {
7285 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00007286 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00007287 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007288 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00007289 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007290 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007291 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007292 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00007293 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00007294 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007295 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00007296 Specialization->setTemplateParameterListsInfo(Context,
Benjamin Kramer9cc210652015-08-05 09:40:49 +00007297 TemplateParameterLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007298 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007299
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007300 if (!PrevDecl)
7301 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00007302
David Majnemer678f50b2015-11-18 19:49:19 +00007303 if (CurContext->isDependentContext()) {
7304 // -fms-extensions permits specialization of nested classes without
7305 // fully specializing the outer class(es).
7306 assert(getLangOpts().MicrosoftExt &&
7307 "Only possible with -fms-extensions!");
7308 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7309 CanonType = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00007310 CanonTemplate, Converted);
David Majnemer678f50b2015-11-18 19:49:19 +00007311 } else {
7312 CanonType = Context.getTypeDeclType(Specialization);
7313 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007314 }
7315
Douglas Gregor06db9f52009-10-12 20:18:28 +00007316 // C++ [temp.expl.spec]p6:
7317 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007318 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007319 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007320 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007321 // use occurs; no diagnostic is required.
7322 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007323 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007324 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007325 // Is there any previous explicit specialization declaration?
7326 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7327 Okay = true;
7328 break;
7329 }
7330 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007331
Douglas Gregorc854c662010-02-26 06:03:23 +00007332 if (!Okay) {
7333 SourceRange Range(TemplateNameLoc, RAngleLoc);
7334 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
7335 << Context.getTypeDeclType(Specialization) << Range;
7336
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007337 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00007338 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007339 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00007340 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00007341 return true;
7342 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007343 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007344
Douglas Gregor2208a292009-09-26 20:57:03 +00007345 // If this is not a friend, note that this is an explicit specialization.
7346 if (TUK != TUK_Friend)
7347 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00007348
7349 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00007350 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00007351 RecordDecl *Def = Specialization->getDefinition();
7352 NamedDecl *Hidden = nullptr;
7353 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
7354 SkipBody->ShouldSkip = true;
7355 makeMergedDefinitionVisible(Hidden, KWLoc);
7356 // From here on out, treat this as just a redeclaration.
7357 TUK = TUK_Declaration;
7358 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00007359 SourceRange Range(TemplateNameLoc, RAngleLoc);
Richard Smith792c22d2016-12-24 04:09:05 +00007360 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00007361 Diag(Def->getLocation(), diag::note_previous_definition);
7362 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00007363 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00007364 }
7365 }
7366
John McCall659a3372010-12-18 03:30:47 +00007367 if (Attr)
7368 ProcessDeclAttributeList(S, Specialization, Attr);
7369
Richard Smith034b94a2012-08-17 03:20:55 +00007370 // Add alignment attributes if necessary; these attributes are checked when
7371 // the ASTContext lays out the structure.
7372 if (TUK == TUK_Definition) {
7373 AddAlignmentAttributesForRecord(Specialization);
7374 AddMsStructLayoutForRecord(Specialization);
7375 }
7376
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00007377 if (ModulePrivateLoc.isValid())
7378 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
7379 << (isPartialSpecialization? 1 : 0)
7380 << FixItHint::CreateRemoval(ModulePrivateLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00007381
Douglas Gregord56a91e2009-02-26 22:19:44 +00007382 // Build the fully-sugared type for this class template
7383 // specialization as the user wrote in the specialization
7384 // itself. This means that we'll pretty-print the type retrieved
7385 // from the specialization's declaration the way that the user
7386 // actually wrote the specialization, rather than formatting the
7387 // name based on the "canonical" representation used to store the
7388 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007389 TypeSourceInfo *WrittenTy
7390 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7391 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007392 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00007393 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007394 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007395 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007396
Douglas Gregor1e249f82009-02-25 22:18:32 +00007397 // C++ [temp.expl.spec]p9:
7398 // A template explicit specialization is in the scope of the
7399 // namespace in which the template was defined.
7400 //
7401 // We actually implement this paragraph where we set the semantic
7402 // context (in the creation of the ClassTemplateSpecializationDecl),
7403 // but we also maintain the lexical context where the actual
7404 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00007405 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00007406
Douglas Gregor67a65642009-02-17 23:15:12 +00007407 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00007408 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00007409 Specialization->startDefinition();
7410
Douglas Gregor2208a292009-09-26 20:57:03 +00007411 if (TUK == TUK_Friend) {
7412 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
7413 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00007414 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00007415 /*FIXME:*/KWLoc);
7416 Friend->setAccess(AS_public);
7417 CurContext->addDecl(Friend);
7418 } else {
7419 // Add the specialization into its lexical context, so that it can
7420 // be seen when iterating through the list of declarations in that
7421 // context. However, specializations are not found by name lookup.
7422 CurContext->addDecl(Specialization);
7423 }
John McCall48871652010-08-21 09:40:31 +00007424 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00007425}
Douglas Gregor333489b2009-03-27 23:10:48 +00007426
John McCall48871652010-08-21 09:40:31 +00007427Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00007428 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00007429 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007430 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00007431 ActOnDocumentableDecl(NewDecl);
7432 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00007433}
7434
John McCall4f7ced62010-02-11 01:33:53 +00007435/// \brief Strips various properties off an implicit instantiation
7436/// that has just been explicitly specialized.
7437static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00007438 D->dropAttr<DLLImportAttr>();
7439 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00007440
Nico Webere4974382014-12-19 23:52:45 +00007441 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00007442 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00007443}
7444
Nico Webera8f80b32012-01-09 19:52:25 +00007445/// \brief Compute the diagnostic location for an explicit instantiation
7446// declaration or definition.
7447static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007448 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00007449 // Explicit instantiations following a specialization have no effect and
7450 // hence no PointOfInstantiation. In that case, walk decl backwards
7451 // until a valid name loc is found.
7452 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007453 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
7454 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00007455 PrevDiagLoc = Prev->getLocation();
7456 }
7457 assert(PrevDiagLoc.isValid() &&
7458 "Explicit instantiation without point of instantiation?");
7459 return PrevDiagLoc;
7460}
7461
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007462/// \brief Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007463/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007464/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007465/// new specialization/instantiation will have any effect.
7466///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007467/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007468/// instantiation.
7469///
7470/// \param NewTSK the kind of the new explicit specialization or instantiation.
7471///
7472/// \param PrevDecl the previous declaration of the entity.
7473///
7474/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
7475///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007476/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007477/// declaration was instantiated (either implicitly or explicitly).
7478///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007479/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007480/// specialization or instantiation has no effect and should be ignored.
7481///
7482/// \returns true if there was an error that should prevent the introduction of
7483/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00007484bool
7485Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7486 TemplateSpecializationKind NewTSK,
7487 NamedDecl *PrevDecl,
7488 TemplateSpecializationKind PrevTSK,
7489 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007490 bool &HasNoEffect) {
7491 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007492
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007493 switch (NewTSK) {
7494 case TSK_Undeclared:
7495 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00007496 assert(
7497 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
7498 "previous declaration must be implicit!");
7499 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007500
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007501 case TSK_ExplicitSpecialization:
7502 switch (PrevTSK) {
7503 case TSK_Undeclared:
7504 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007505 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007506 // explicitly specialized or has merely been mentioned without any
7507 // instantiation.
7508 return false;
7509
7510 case TSK_ImplicitInstantiation:
7511 if (PrevPointOfInstantiation.isInvalid()) {
7512 // The declaration itself has not actually been instantiated, so it is
7513 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00007514 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007515 return false;
7516 }
7517 // Fall through
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007518
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007519 case TSK_ExplicitInstantiationDeclaration:
7520 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007521 assert((PrevTSK == TSK_ImplicitInstantiation ||
7522 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007523 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007524
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007525 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007526 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007527 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007528 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007529 // implicit instantiation to take place, in every translation unit in
7530 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007531 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007532 // Is there any previous explicit specialization declaration?
7533 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
7534 return false;
7535 }
7536
Douglas Gregor1d957a32009-10-27 18:42:08 +00007537 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007538 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007539 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007540 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007541
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007542 return true;
7543 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007544
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007545 case TSK_ExplicitInstantiationDeclaration:
7546 switch (PrevTSK) {
7547 case TSK_ExplicitInstantiationDeclaration:
7548 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00007549 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007550 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007551
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007552 case TSK_Undeclared:
7553 case TSK_ImplicitInstantiation:
7554 // We're explicitly instantiating something that may have already been
7555 // implicitly instantiated; that's fine.
7556 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007557
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007558 case TSK_ExplicitSpecialization:
7559 // C++0x [temp.explicit]p4:
7560 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007561 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007562 // specialization for that template, the explicit instantiation has no
7563 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007564 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007565 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007566
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007567 case TSK_ExplicitInstantiationDefinition:
7568 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007569 // If an entity is the subject of both an explicit instantiation
7570 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007571 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007572 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00007573 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00007574
7575 // Explicit instantiations following a specialization have no effect and
7576 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
7577 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00007578 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7579 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007580 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007581 return false;
7582 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007583
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007584 case TSK_ExplicitInstantiationDefinition:
7585 switch (PrevTSK) {
7586 case TSK_Undeclared:
7587 case TSK_ImplicitInstantiation:
7588 // We're explicitly instantiating something that may have already been
7589 // implicitly instantiated; that's fine.
7590 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007591
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007592 case TSK_ExplicitSpecialization:
7593 // C++ DR 259, C++0x [temp.explicit]p4:
7594 // For a given set of template parameters, if an explicit
7595 // instantiation of a template appears after a declaration of
7596 // an explicit specialization for that template, the explicit
7597 // instantiation has no effect.
Richard Smithe4caa482016-08-31 23:23:25 +00007598 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
Richard Smith0bf8a4922011-10-18 20:49:44 +00007599 << PrevDecl;
7600 Diag(PrevDecl->getLocation(),
7601 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007602 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007603 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007604
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007605 case TSK_ExplicitInstantiationDeclaration:
7606 // We're explicity instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007607 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00007608
7609 // C++0x [temp.explicit]p4:
7610 // For a given set of template parameters, if an explicit instantiation
7611 // of a template appears after a declaration of an explicit
7612 // specialization for that template, the explicit instantiation has no
7613 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007614 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00007615 // Is there any previous explicit specialization declaration?
7616 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7617 HasNoEffect = true;
7618 break;
7619 }
7620 }
7621
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007622 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007623
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007624 case TSK_ExplicitInstantiationDefinition:
7625 // C++0x [temp.spec]p5:
7626 // For a given template and a given set of template-arguments,
7627 // - an explicit instantiation definition shall appear at most once
7628 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00007629
7630 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
7631 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00007632 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00007633 : diag::err_explicit_instantiation_duplicate)
7634 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00007635 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00007636 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007637 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007638 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007639 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007640 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007641
David Blaikie83d382b2011-09-23 05:06:16 +00007642 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007643}
7644
John McCallb9c78482010-04-08 09:05:18 +00007645/// \brief Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00007646/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00007647///
James Dennettf14a6e52012-06-15 22:23:43 +00007648/// The only possible way to get a dependent function template specialization
7649/// is with a friend declaration, like so:
7650///
7651/// \code
7652/// template \<class T> void foo(T);
7653/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00007654/// friend void foo<>(T);
7655/// };
James Dennettf14a6e52012-06-15 22:23:43 +00007656/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00007657///
7658/// There really isn't any useful analysis we can do here, so we
7659/// just store the information.
7660bool
7661Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
7662 const TemplateArgumentListInfo &ExplicitTemplateArgs,
7663 LookupResult &Previous) {
7664 // Remove anything from Previous that isn't a function template in
7665 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00007666 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00007667 LookupResult::Filter F = Previous.makeFilter();
7668 while (F.hasNext()) {
7669 NamedDecl *D = F.next()->getUnderlyingDecl();
7670 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00007671 !FDLookupContext->InEnclosingNamespaceSetOf(
7672 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00007673 F.erase();
7674 }
7675 F.done();
7676
7677 // Should this be diagnosed here?
7678 if (Previous.empty()) return true;
7679
7680 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
7681 ExplicitTemplateArgs);
7682 return false;
7683}
7684
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007685/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007686/// specialization.
7687///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007688/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007689/// explicit function template specialization. On successful completion,
7690/// the function declaration \p FD will become a function template
7691/// specialization.
7692///
7693/// \param FD the function declaration, which will be updated to become a
7694/// function template specialization.
7695///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007696/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
7697/// if any. Note that this may be valid info even when 0 arguments are
7698/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
7699/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007700///
Francois Pichet3a44e432011-07-08 06:21:47 +00007701/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007702/// this function specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007703bool Sema::CheckFunctionTemplateSpecialization(
7704 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
7705 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007706 // The set of function template specializations that could match this
7707 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00007708 UnresolvedSet<8> Candidates;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007709 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
7710 /*ForTakingAddress=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007711
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007712 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
7713 ConvertedTemplateArgs;
7714
Sebastian Redl50c68252010-08-31 00:36:30 +00007715 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00007716 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7717 I != E; ++I) {
7718 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
7719 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007720 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007721 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00007722 if (!FDLookupContext->InEnclosingNamespaceSetOf(
7723 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007724 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007725
Richard Smith574f4f62013-01-14 05:37:29 +00007726 // When matching a constexpr member function template specialization
7727 // against the primary template, we don't yet know whether the
7728 // specialization has an implicit 'const' (because we don't know whether
7729 // it will be a static member function until we know which template it
7730 // specializes), so adjust it now assuming it specializes this template.
7731 QualType FT = FD->getType();
7732 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00007733 CXXMethodDecl *OldMD =
7734 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00007735 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00007736 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00007737 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7738 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00007739 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00007740 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00007741 }
7742 }
7743
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007744 TemplateArgumentListInfo Args;
7745 if (ExplicitTemplateArgs)
7746 Args = *ExplicitTemplateArgs;
7747
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007748 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007749 // A trailing template-argument can be left unspecified in the
7750 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007751 // provided it can be deduced from the function argument type.
7752 // Perform template argument deduction to determine whether we may be
7753 // specializing this template.
7754 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00007755 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00007756 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00007757 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
7758 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
Richard Smithc2bebe92016-05-11 20:37:46 +00007759 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
7760 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00007761 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007762 // that we can provide nifty diagnostics.
Richard Smithc2bebe92016-05-11 20:37:46 +00007763 FailedCandidates.addCandidate().set(
7764 I.getPair(), FunTmpl->getTemplatedDecl(),
7765 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007766 (void)TDK;
7767 continue;
7768 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007769
Artem Belevich64135c32016-12-08 19:38:13 +00007770 // Target attributes are part of the cuda function signature, so
7771 // the deduced template's cuda target must match that of the
7772 // specialization. Given that C++ template deduction does not
7773 // take target attributes into account, we reject candidates
7774 // here that have a different target.
Artem Belevich13e9b4d2016-12-07 19:27:16 +00007775 if (LangOpts.CUDA &&
Artem Belevich64135c32016-12-08 19:38:13 +00007776 IdentifyCUDATarget(Specialization,
7777 /* IgnoreImplicitHDAttributes = */ true) !=
7778 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttributes = */ true)) {
Artem Belevich13e9b4d2016-12-07 19:27:16 +00007779 FailedCandidates.addCandidate().set(
7780 I.getPair(), FunTmpl->getTemplatedDecl(),
7781 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
7782 continue;
7783 }
7784
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007785 // Record this candidate.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007786 if (ExplicitTemplateArgs)
7787 ConvertedTemplateArgs[Specialization] = std::move(Args);
John McCall58cc69d2010-01-27 01:50:18 +00007788 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007789 }
7790 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007791
Douglas Gregor5de279c2009-09-26 03:41:46 +00007792 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007793 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00007794 Candidates.begin(), Candidates.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00007795 FD->getLocation(),
7796 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
7797 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00007798 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00007799 PDiag(diag::note_function_template_spec_matched));
7800
John McCall58cc69d2010-01-27 01:50:18 +00007801 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007802 return true;
John McCall58cc69d2010-01-27 01:50:18 +00007803
7804 // Ignore access information; it doesn't figure into redeclaration checking.
7805 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00007806
Nathan Wilson83839122016-04-09 02:55:27 +00007807 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
7808 // an explicit specialization (14.8.3) [...] of a concept definition.
7809 if (Specialization->getPrimaryTemplate()->isConcept()) {
7810 Diag(FD->getLocation(), diag::err_concept_specialized)
7811 << 0 /*function*/ << 1 /*explicitly specialized*/;
7812 Diag(Specialization->getLocation(), diag::note_previous_declaration);
7813 return true;
7814 }
7815
Abramo Bagnarab9893d62011-03-04 17:20:30 +00007816 FunctionTemplateSpecializationInfo *SpecInfo
7817 = Specialization->getTemplateSpecializationInfo();
7818 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00007819
7820 // Note: do not overwrite location info if previous template
7821 // specialization kind was explicit.
7822 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00007823 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00007824 Specialization->setLocation(FD->getLocation());
Richard Smith5b8b3db2012-02-20 23:28:05 +00007825 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
7826 // function can differ from the template declaration with respect to
7827 // the constexpr specifier.
7828 Specialization->setConstexpr(FD->isConstexpr());
7829 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007830
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007831 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00007832 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00007833
7834 // If this is a friend declaration, then we're not really declaring
7835 // an explicit specialization.
7836 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007837
Douglas Gregor54888652009-10-07 00:13:32 +00007838 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00007839 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007840 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00007841 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007842 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007843 false))
Douglas Gregor54888652009-10-07 00:13:32 +00007844 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00007845
7846 // C++ [temp.expl.spec]p6:
7847 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007848 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007849 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007850 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007851 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007852 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00007853 if (!isFriend &&
7854 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00007855 TSK_ExplicitSpecialization,
7856 Specialization,
7857 SpecInfo->getTemplateSpecializationKind(),
7858 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007859 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007860 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00007861
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007862 // Mark the prior declaration as an explicit specialization, so that later
7863 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007864 if (!isFriend) {
Faisal Vali81a88be2016-06-14 03:23:15 +00007865 // Since explicit specializations do not inherit '=delete' from their
7866 // primary function template - check if the 'specialization' that was
7867 // implicitly generated (during template argument deduction for partial
7868 // ordering) from the most specialized of all the function templates that
7869 // 'FD' could have been specializing, has a 'deleted' definition. If so,
7870 // first check that it was implicitly generated during template argument
7871 // deduction by making sure it wasn't referenced, and then reset the deleted
7872 // flag to not-deleted, so that we can inherit that information from 'FD'.
7873 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
7874 !Specialization->getCanonicalDecl()->isReferenced()) {
7875 assert(
7876 Specialization->getCanonicalDecl() == Specialization &&
7877 "This must be the only existing declaration of this specialization");
7878 Specialization->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007879 }
John McCall816d75b2010-03-24 07:46:06 +00007880 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007881 MarkUnusedFileScopedDecl(Specialization);
7882 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007883
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007884 // Turn the given function declaration into a function template
7885 // specialization, with the template arguments from the previous
7886 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007887 // Take copies of (semantic and syntactic) template argument lists.
7888 const TemplateArgumentList* TemplArgs = new (Context)
7889 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007890 FD->setFunctionTemplateSpecialization(
7891 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
7892 SpecInfo->getTemplateSpecializationKind(),
7893 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00007894
Artem Belevich64135c32016-12-08 19:38:13 +00007895 // A function template specialization inherits the target attributes
7896 // of its template. (We require the attributes explicitly in the
7897 // code to match, but a template may have implicit attributes by
7898 // virtue e.g. of being constexpr, and it passes these implicit
7899 // attributes on to its specializations.)
7900 if (LangOpts.CUDA)
7901 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
7902
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007903 // The "previous declaration" for this function template specialization is
7904 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00007905 Previous.clear();
7906 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007907 return false;
7908}
7909
Douglas Gregor86d142a2009-10-08 07:24:58 +00007910/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007911/// specialization.
7912///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007913/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007914/// explicit member function specialization. On successful completion,
7915/// the function declaration \p FD will become a member function
7916/// specialization.
7917///
Douglas Gregor86d142a2009-10-08 07:24:58 +00007918/// \param Member the member declaration, which will be updated to become a
7919/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007920///
John McCall1f82f242009-11-18 22:49:29 +00007921/// \param Previous the set of declarations, one of which may be specialized
7922/// by this function specialization; the set will be modified to contain the
7923/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007924bool
John McCall1f82f242009-11-18 22:49:29 +00007925Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007926 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00007927
Douglas Gregor86d142a2009-10-08 07:24:58 +00007928 // Try to find the member we are instantiating.
Richard Smith22e7cc62016-05-24 00:01:49 +00007929 NamedDecl *FoundInstantiation = nullptr;
Craig Topperc3ec1492014-05-26 06:22:03 +00007930 NamedDecl *Instantiation = nullptr;
7931 NamedDecl *InstantiatedFrom = nullptr;
7932 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00007933
John McCall1f82f242009-11-18 22:49:29 +00007934 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007935 // Nowhere to look anyway.
7936 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007937 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7938 I != E; ++I) {
7939 NamedDecl *D = (*I)->getUnderlyingDecl();
7940 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00007941 QualType Adjusted = Function->getType();
7942 if (!hasExplicitCallingConv(Adjusted))
7943 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
7944 if (Context.hasSameType(Adjusted, Method->getType())) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007945 FoundInstantiation = *I;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007946 Instantiation = Method;
7947 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007948 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007949 break;
7950 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007951 }
7952 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00007953 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007954 VarDecl *PrevVar;
7955 if (Previous.isSingleResult() &&
7956 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00007957 if (PrevVar->isStaticDataMember()) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007958 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00007959 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007960 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007961 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007962 }
7963 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007964 CXXRecordDecl *PrevRecord;
7965 if (Previous.isSingleResult() &&
7966 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007967 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00007968 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007969 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007970 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007971 }
Richard Smith7d137e32012-03-23 03:33:32 +00007972 } else if (isa<EnumDecl>(Member)) {
7973 EnumDecl *PrevEnum;
7974 if (Previous.isSingleResult() &&
7975 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007976 FoundInstantiation = Previous.getRepresentativeDecl();
Richard Smith7d137e32012-03-23 03:33:32 +00007977 Instantiation = PrevEnum;
7978 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
7979 MSInfo = PrevEnum->getMemberSpecializationInfo();
7980 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007981 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007982
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007983 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007984 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007985 // specializations are always out-of-line, the caller will complain about
7986 // this mismatch later.
7987 return false;
7988 }
John McCalle820e5e2010-04-13 20:37:33 +00007989
7990 // If this is a friend, just bail out here before we start turning
7991 // things into explicit specializations.
7992 if (Member->getFriendObjectKind() != Decl::FOK_None) {
7993 // Preserve instantiation information.
7994 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
7995 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
7996 cast<CXXMethodDecl>(InstantiatedFrom),
7997 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
7998 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
7999 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
8000 cast<CXXRecordDecl>(InstantiatedFrom),
8001 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
8002 }
8003
8004 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00008005 Previous.addDecl(FoundInstantiation);
John McCalle820e5e2010-04-13 20:37:33 +00008006 return false;
8007 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008008
Douglas Gregor86d142a2009-10-08 07:24:58 +00008009 // Make sure that this is a specialization of a member.
8010 if (!InstantiatedFrom) {
8011 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
8012 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008013 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
8014 return true;
8015 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008016
Douglas Gregor06db9f52009-10-12 20:18:28 +00008017 // C++ [temp.expl.spec]p6:
8018 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00008019 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00008020 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008021 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00008022 // use occurs; no diagnostic is required.
8023 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00008024
Abramo Bagnara8075c852010-06-12 07:44:57 +00008025 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00008026 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
8027 TSK_ExplicitSpecialization,
8028 Instantiation,
8029 MSInfo->getTemplateSpecializationKind(),
8030 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008031 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00008032 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008033
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008034 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008035 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00008036 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008037 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00008038 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008039 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00008040
Douglas Gregor86d142a2009-10-08 07:24:58 +00008041 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008042 // the original declaration to note that it is an explicit specialization
8043 // (if it was previously an implicit instantiation). This latter step
8044 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00008045 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008046 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
8047 if (InstantiationFunction->getTemplateSpecializationKind() ==
8048 TSK_ImplicitInstantiation) {
8049 InstantiationFunction->setTemplateSpecializationKind(
8050 TSK_ExplicitSpecialization);
8051 InstantiationFunction->setLocation(Member->getLocation());
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008052 // Explicit specializations of member functions of class templates do not
8053 // inherit '=delete' from the member function they are specializing.
8054 if (InstantiationFunction->isDeleted()) {
8055 assert(InstantiationFunction->getCanonicalDecl() ==
8056 InstantiationFunction);
Richard Smith5f274382016-09-28 23:55:27 +00008057 InstantiationFunction->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008058 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008059 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008060
Douglas Gregor86d142a2009-10-08 07:24:58 +00008061 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
8062 cast<CXXMethodDecl>(InstantiatedFrom),
8063 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00008064 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00008065 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008066 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
8067 if (InstantiationVar->getTemplateSpecializationKind() ==
8068 TSK_ImplicitInstantiation) {
8069 InstantiationVar->setTemplateSpecializationKind(
8070 TSK_ExplicitSpecialization);
8071 InstantiationVar->setLocation(Member->getLocation());
8072 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008073
Larisse Voufo39a1e502013-08-06 01:03:05 +00008074 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
8075 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00008076 MarkUnusedFileScopedDecl(InstantiationVar);
Richard Smith7d137e32012-03-23 03:33:32 +00008077 } else if (isa<CXXRecordDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008078 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
8079 if (InstantiationClass->getTemplateSpecializationKind() ==
8080 TSK_ImplicitInstantiation) {
8081 InstantiationClass->setTemplateSpecializationKind(
8082 TSK_ExplicitSpecialization);
8083 InstantiationClass->setLocation(Member->getLocation());
8084 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008085
Douglas Gregor86d142a2009-10-08 07:24:58 +00008086 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008087 cast<CXXRecordDecl>(InstantiatedFrom),
8088 TSK_ExplicitSpecialization);
Richard Smith7d137e32012-03-23 03:33:32 +00008089 } else {
8090 assert(isa<EnumDecl>(Member) && "Only member enums remain");
8091 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
8092 if (InstantiationEnum->getTemplateSpecializationKind() ==
8093 TSK_ImplicitInstantiation) {
8094 InstantiationEnum->setTemplateSpecializationKind(
8095 TSK_ExplicitSpecialization);
8096 InstantiationEnum->setLocation(Member->getLocation());
8097 }
8098
8099 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
8100 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00008101 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008102
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008103 // Save the caller the trouble of having to figure out which declaration
8104 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00008105 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00008106 Previous.addDecl(FoundInstantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008107 return false;
8108}
8109
Douglas Gregore47f5a72009-10-14 23:41:34 +00008110/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008111///
8112/// \returns true if a serious error occurs, false otherwise.
8113static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00008114 SourceLocation InstLoc,
8115 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00008116 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
8117 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008118
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008119 if (CurContext->isRecord()) {
8120 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
8121 << D;
8122 return true;
8123 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008124
Richard Smith050d2612011-10-18 02:28:33 +00008125 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008126 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00008127 // template. If the name declared in the explicit instantiation is an
8128 // unqualified name, the explicit instantiation shall appear in the
8129 // namespace where its template is declared or, if that namespace is inline
8130 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008131 //
8132 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00008133 if (WasQualifiedName) {
8134 if (CurContext->Encloses(OrigContext))
8135 return false;
8136 } else {
8137 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
8138 return false;
8139 }
8140
8141 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
8142 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008143 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008144 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008145 diag::err_explicit_instantiation_out_of_scope :
8146 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008147 << D << NS;
8148 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008149 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008150 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008151 diag::err_explicit_instantiation_unqualified_wrong_namespace :
8152 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
8153 << D << NS;
8154 } else
8155 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008156 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008157 diag::err_explicit_instantiation_must_be_global :
8158 diag::warn_explicit_instantiation_must_be_global_0x)
8159 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00008160 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008161 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00008162}
8163
8164/// \brief Determine whether the given scope specifier has a template-id in it.
8165static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
8166 if (!SS.isSet())
8167 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008168
Richard Smith050d2612011-10-18 02:28:33 +00008169 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008170 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008171 // or a static data member of a class template specialization, the name of
8172 // the class template specialization in the qualified-id for the member
8173 // name shall be a simple-template-id.
8174 //
8175 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00008176 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
8177 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00008178 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00008179 if (isa<TemplateSpecializationType>(T))
8180 return true;
8181
8182 return false;
8183}
8184
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008185/// Make a dllexport or dllimport attr on a class template specialization take
8186/// effect.
8187static void dllExportImportClassTemplateSpecialization(
8188 Sema &S, ClassTemplateSpecializationDecl *Def) {
8189 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
8190 assert(A && "dllExportImportClassTemplateSpecialization called "
8191 "on Def without dllexport or dllimport");
8192
8193 // We reject explicit instantiations in class scope, so there should
8194 // never be any delayed exported classes to worry about.
8195 assert(S.DelayedDllExportClasses.empty() &&
8196 "delayed exports present at explicit instantiation");
8197 S.checkClassLevelDLLAttribute(Def);
8198
8199 // Propagate attribute to base class templates.
8200 for (auto &B : Def->bases()) {
8201 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
8202 B.getType()->getAsCXXRecordDecl()))
8203 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
8204 }
8205
8206 S.referenceDLLExportedClassMethods();
8207}
8208
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008209// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00008210DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00008211Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00008212 SourceLocation ExternLoc,
8213 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00008214 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00008215 SourceLocation KWLoc,
8216 const CXXScopeSpec &SS,
8217 TemplateTy TemplateD,
8218 SourceLocation TemplateNameLoc,
8219 SourceLocation LAngleLoc,
8220 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00008221 SourceLocation RAngleLoc,
8222 AttributeList *Attr) {
8223 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00008224 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00008225 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00008226 // Check that the specialization uses the same tag kind as the
8227 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00008228 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8229 assert(Kind != TTK_Enum &&
8230 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00008231
Richard Trieu265c3442016-04-05 21:13:54 +00008232 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
8233
8234 if (!ClassTemplate) {
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00008235 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
8236 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
Richard Trieu265c3442016-04-05 21:13:54 +00008237 Diag(TD->getLocation(), diag::note_previous_use);
Richard Smith392497b2013-06-22 22:03:31 +00008238 return true;
8239 }
8240
Douglas Gregord9034f02009-05-14 16:41:31 +00008241 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00008242 Kind, /*isDefinition*/false, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00008243 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00008244 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00008245 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00008246 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00008247 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00008248 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00008249 diag::note_previous_use);
8250 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8251 }
8252
Douglas Gregore47f5a72009-10-14 23:41:34 +00008253 // C++0x [temp.explicit]p2:
8254 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008255 // definition and an explicit instantiation declaration. An explicit
8256 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00008257 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
8258 ? TSK_ExplicitInstantiationDefinition
8259 : TSK_ExplicitInstantiationDeclaration;
8260
8261 if (TSK == TSK_ExplicitInstantiationDeclaration) {
8262 // Check for dllexport class template instantiation declarations.
8263 for (AttributeList *A = Attr; A; A = A->getNext()) {
8264 if (A->getKind() == AttributeList::AT_DLLExport) {
8265 Diag(ExternLoc,
8266 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8267 Diag(A->getLoc(), diag::note_attribute);
8268 break;
8269 }
8270 }
8271
8272 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
8273 Diag(ExternLoc,
8274 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8275 Diag(A->getLocation(), diag::note_attribute);
8276 }
8277 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008278
Hans Wennborga86a83b2016-05-26 19:42:56 +00008279 // In MSVC mode, dllimported explicit instantiation definitions are treated as
8280 // instantiation declarations for most purposes.
8281 bool DLLImportExplicitInstantiationDef = false;
8282 if (TSK == TSK_ExplicitInstantiationDefinition &&
8283 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
8284 // Check for dllimport class template instantiation definitions.
8285 bool DLLImport =
8286 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
8287 for (AttributeList *A = Attr; A; A = A->getNext()) {
8288 if (A->getKind() == AttributeList::AT_DLLImport)
8289 DLLImport = true;
8290 if (A->getKind() == AttributeList::AT_DLLExport) {
8291 // dllexport trumps dllimport here.
8292 DLLImport = false;
8293 break;
8294 }
8295 }
8296 if (DLLImport) {
8297 TSK = TSK_ExplicitInstantiationDeclaration;
8298 DLLImportExplicitInstantiationDef = true;
8299 }
8300 }
8301
Douglas Gregora1f49972009-05-13 00:25:59 +00008302 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00008303 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00008304 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00008305
8306 // Check that the template argument list is well-formed for this
8307 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008308 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00008309 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
8310 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00008311 return true;
8312
Douglas Gregora1f49972009-05-13 00:25:59 +00008313 // Find the class template specialization declaration that
8314 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00008315 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00008316 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00008317 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00008318
Abramo Bagnara8075c852010-06-12 07:44:57 +00008319 TemplateSpecializationKind PrevDecl_TSK
8320 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
8321
Douglas Gregor54888652009-10-07 00:13:32 +00008322 // C++0x [temp.explicit]p2:
8323 // [...] An explicit instantiation shall appear in an enclosing
8324 // namespace of its template. [...]
8325 //
8326 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008327 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
8328 SS.isSet()))
8329 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008330
Craig Topperc3ec1492014-05-26 06:22:03 +00008331 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00008332
Abramo Bagnara8075c852010-06-12 07:44:57 +00008333 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00008334 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00008335 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00008336 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00008337 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008338 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00008339 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00008340
Abramo Bagnara8075c852010-06-12 07:44:57 +00008341 // Even though HasNoEffect == true means that this explicit instantiation
8342 // has no effect on semantics, we go on to put its syntax in the AST.
8343
8344 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
8345 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008346 // Since the only prior class template specialization with these
8347 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00008348 // declaration node as our own, updating the source location
8349 // for the template name to reflect our new declaration.
8350 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008351 Specialization = PrevDecl;
8352 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00008353 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008354 }
Hans Wennborga86a83b2016-05-26 19:42:56 +00008355
8356 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
8357 DLLImportExplicitInstantiationDef) {
8358 // The new specialization might add a dllimport attribute.
8359 HasNoEffect = false;
8360 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00008361 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00008362
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008363 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00008364 // Create a new class template specialization declaration node for
8365 // this explicit specialization.
8366 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00008367 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00008368 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00008369 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00008370 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00008371 Converted,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008372 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00008373 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00008374
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00008375 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00008376 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00008377 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008378 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008379 }
8380
8381 // Build the fully-sugared type for this explicit instantiation as
8382 // the user wrote in the explicit instantiation itself. This means
8383 // that we'll pretty-print the type retrieved from the
8384 // specialization's declaration the way that the user actually wrote
8385 // the explicit instantiation, rather than formatting the name based
8386 // on the "canonical" representation used to store the template
8387 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00008388 TypeSourceInfo *WrittenTy
8389 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
8390 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00008391 Context.getTypeDeclType(Specialization));
8392 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00008393
Abramo Bagnara8075c852010-06-12 07:44:57 +00008394 // Set source locations for keywords.
8395 Specialization->setExternLoc(ExternLoc);
8396 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00008397 Specialization->setBraceRange(SourceRange());
Abramo Bagnara8075c852010-06-12 07:44:57 +00008398
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00008399 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
Rafael Espindola0b062072012-01-03 06:04:21 +00008400 if (Attr)
8401 ProcessDeclAttributeList(S, Specialization, Attr);
8402
Abramo Bagnara8075c852010-06-12 07:44:57 +00008403 // Add the explicit instantiation into its lexical context. However,
8404 // since explicit instantiations are never found by name lookup, we
8405 // just put it into the declaration context directly.
8406 Specialization->setLexicalDeclContext(CurContext);
8407 CurContext->addDecl(Specialization);
8408
8409 // Syntax is now OK, so return if it has no other effect on semantics.
8410 if (HasNoEffect) {
8411 // Set the template specialization kind.
8412 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00008413 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00008414 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008415
8416 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00008417 // A definition of a class template or class member template
8418 // shall be in scope at the point of the explicit instantiation of
8419 // the class template or class member template.
8420 //
8421 // This check comes when we actually try to perform the
8422 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00008423 ClassTemplateSpecializationDecl *Def
8424 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008425 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00008426 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00008427 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008428 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00008429 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008430 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
8431 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00008432
Douglas Gregor1d957a32009-10-27 18:42:08 +00008433 // Instantiate the members of this class template specialization.
8434 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008435 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00008436 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008437 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008438 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
8439 // TSK_ExplicitInstantiationDefinition
8440 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborga86a83b2016-05-26 19:42:56 +00008441 (TSK == TSK_ExplicitInstantiationDefinition ||
8442 DLLImportExplicitInstantiationDef)) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00008443 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008444 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00008445
Hans Wennborgc0875502015-06-09 00:39:05 +00008446 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
Shoaib Meenaiab3f96c2016-11-09 23:52:20 +00008447 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8448 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
Hans Wennborgc0875502015-06-09 00:39:05 +00008449 // In the MS ABI, an explicit instantiation definition can add a dll
8450 // attribute to a template with a previous instantiation declaration.
8451 // MinGW doesn't allow this.
Hans Wennborg17f9b442015-05-27 00:06:45 +00008452 auto *A = cast<InheritableAttr>(
8453 getDLLAttr(Specialization)->clone(getASTContext()));
8454 A->setInherited(true);
8455 Def->addAttr(A);
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008456 dllExportImportClassTemplateSpecialization(*this, Def);
Hans Wennborg17f9b442015-05-27 00:06:45 +00008457 }
8458 }
8459
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008460 // Fix a TSK_ImplicitInstantiation followed by a
8461 // TSK_ExplicitInstantiationDefinition
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00008462 bool NewlyDLLExported =
8463 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
8464 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008465 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8466 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
8467 // In the MS ABI, an explicit instantiation definition can add a dll
8468 // attribute to a template with a previous implicit instantiation.
8469 // MinGW doesn't allow this. We limit clang to only adding dllexport, to
8470 // avoid potentially strange codegen behavior. For example, if we extend
8471 // this conditional to dllimport, and we have a source file calling a
8472 // method on an implicitly instantiated template class instance and then
8473 // declaring a dllimport explicit instantiation definition for the same
8474 // template class, the codegen for the method call will not respect the
8475 // dllimport, while it will with cl. The Def will already have the DLL
8476 // attribute, since the Def and Specialization will be the same in the
8477 // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
8478 // attribute to the Specialization; we just need to make it take effect.
8479 assert(Def == Specialization &&
8480 "Def and Specialization should match for implicit instantiation");
8481 dllExportImportClassTemplateSpecialization(*this, Def);
8482 }
8483
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00008484 // Set the template specialization kind. Make sure it is set before
8485 // instantiating the members which will trigger ASTConsumer callbacks.
8486 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregor12e49d32009-10-15 22:53:21 +00008487 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00008488 } else {
8489
8490 // Set the template specialization kind.
8491 Specialization->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00008492 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008493
John McCall48871652010-08-21 09:40:31 +00008494 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00008495}
8496
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008497// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00008498DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00008499Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00008500 SourceLocation ExternLoc,
8501 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00008502 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008503 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00008504 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008505 IdentifierInfo *Name,
8506 SourceLocation NameLoc,
8507 AttributeList *Attr) {
8508
Douglas Gregord6ab8742009-05-28 23:31:59 +00008509 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00008510 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00008511 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00008512 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00008513 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00008514 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00008515 SourceLocation(), false, TypeResult(),
8516 /*IsTypeSpecifier*/false);
John McCall7f41d982009-09-11 04:59:25 +00008517 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
8518
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008519 if (!TagD)
8520 return true;
8521
John McCall48871652010-08-21 09:40:31 +00008522 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00008523 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008524
Douglas Gregorb8006faf2009-05-27 17:30:49 +00008525 if (Tag->isInvalidDecl())
8526 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008527
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008528 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
8529 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
8530 if (!Pattern) {
8531 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
8532 << Context.getTypeDeclType(Record);
8533 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
8534 return true;
8535 }
8536
Douglas Gregore47f5a72009-10-14 23:41:34 +00008537 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008538 // If the explicit instantiation is for a class or member class, the
8539 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00008540 // simple-template-id.
8541 //
8542 // C++98 has the same restriction, just worded differently.
8543 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00008544 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008545 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008546
Douglas Gregore47f5a72009-10-14 23:41:34 +00008547 // C++0x [temp.explicit]p2:
8548 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008549 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00008550 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00008551 TemplateSpecializationKind TSK
8552 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8553 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008554
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008555 // C++0x [temp.explicit]p2:
8556 // [...] An explicit instantiation shall appear in an enclosing
8557 // namespace of its template. [...]
8558 //
8559 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008560 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008561
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008562 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008563 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00008564 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008565 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00008566 PrevDecl = Record;
8567 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008568 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00008569 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008570 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008571 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008572 PrevDecl,
8573 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008574 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008575 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008576 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00008577 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008578 return TagD;
8579 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008580
Douglas Gregor12e49d32009-10-15 22:53:21 +00008581 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008582 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00008583 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00008584 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008585 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00008586 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008587 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008588 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00008589 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00008590 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
8591 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00008592 Diag(Pattern->getLocation(), diag::note_forward_declaration)
8593 << Pattern;
8594 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008595 } else {
8596 if (InstantiateClass(NameLoc, Record, Def,
8597 getTemplateInstantiationArgs(Record),
8598 TSK))
8599 return true;
8600
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008601 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00008602 if (!RecordDef)
8603 return true;
8604 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008605 }
8606
Douglas Gregor1d957a32009-10-27 18:42:08 +00008607 // Instantiate all of the members of the class.
8608 InstantiateClassMembers(NameLoc, RecordDef,
8609 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008610
Douglas Gregor88d292c2010-05-13 16:44:06 +00008611 if (TSK == TSK_ExplicitInstantiationDefinition)
8612 MarkVTableUsed(NameLoc, RecordDef, true);
8613
Mike Stump87c57ac2009-05-16 07:39:55 +00008614 // FIXME: We don't have any representation for explicit instantiations of
8615 // member classes. Such a representation is not needed for compilation, but it
8616 // should be available for clients that want to see all of the declarations in
8617 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008618 return TagD;
8619}
8620
John McCallfaf5fb42010-08-26 23:41:50 +00008621DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
8622 SourceLocation ExternLoc,
8623 SourceLocation TemplateLoc,
8624 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00008625 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008626 // TODO: check if/when DNInfo should replace Name.
8627 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8628 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00008629 if (!Name) {
8630 if (!D.isInvalidType())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008631 Diag(D.getDeclSpec().getLocStart(),
Douglas Gregor450f00842009-09-25 18:43:00 +00008632 diag::err_explicit_instantiation_requires_name)
8633 << D.getDeclSpec().getSourceRange()
8634 << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008635
Douglas Gregor450f00842009-09-25 18:43:00 +00008636 return true;
8637 }
8638
8639 // The scope passed in may not be a decl scope. Zip up the scope tree until
8640 // we find one that is.
8641 while ((S->getFlags() & Scope::DeclScope) == 0 ||
8642 (S->getFlags() & Scope::TemplateParamScope) != 0)
8643 S = S->getParent();
8644
8645 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00008646 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
8647 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00008648 if (R.isNull())
8649 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008650
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008651 // C++ [dcl.stc]p1:
Simon Pilgrim6905d222016-12-30 22:55:33 +00008652 // A storage-class-specifier shall not be specified in [...] an explicit
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008653 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00008654 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00008655 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
8656 << Name;
8657 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008658 } else if (D.getDeclSpec().getStorageClassSpec()
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008659 != DeclSpec::SCS_unspecified) {
8660 // Complain about then remove the storage class specifier.
8661 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
8662 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Simon Pilgrim6905d222016-12-30 22:55:33 +00008663
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008664 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00008665 }
8666
Douglas Gregor3c74d412009-10-14 20:14:33 +00008667 // C++0x [temp.explicit]p1:
8668 // [...] An explicit instantiation of a function template shall not use the
8669 // inline or constexpr specifiers.
8670 // Presumably, this also applies to member functions of class templates as
8671 // well.
Richard Smith83c19292011-10-18 03:44:03 +00008672 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008673 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008674 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00008675 diag::err_explicit_instantiation_inline :
8676 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00008677 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00008678 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00008679 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
8680 // not already specified.
8681 Diag(D.getDeclSpec().getConstexprSpecLoc(),
8682 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008683
Nathan Wilsonde498452016-02-08 05:34:00 +00008684 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8685 // applied only to the definition of a function template or variable template,
8686 // declared in namespace scope.
8687 if (D.getDeclSpec().isConceptSpecified()) {
8688 Diag(D.getDeclSpec().getConceptSpecLoc(),
8689 diag::err_concept_specified_specialization) << 0;
8690 return true;
8691 }
8692
Richard Smith19a311a2017-02-09 22:47:51 +00008693 // A deduction guide is not on the list of entities that can be explicitly
8694 // instantiated.
8695 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8696 Diag(D.getDeclSpec().getLocStart(), diag::err_deduction_guide_specialized)
8697 << /*explicit instantiation*/ 0;
8698 return true;
8699 }
8700
Douglas Gregore47f5a72009-10-14 23:41:34 +00008701 // C++0x [temp.explicit]p2:
8702 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008703 // definition and an explicit instantiation declaration. An explicit
8704 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00008705 TemplateSpecializationKind TSK
8706 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8707 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008708
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008709 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00008710 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00008711
8712 if (!R->isFunctionType()) {
8713 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008714 // A [...] static data member of a class template can be explicitly
8715 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00008716 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00008717 // C++1y [temp.explicit]p1:
8718 // A [...] variable [...] template specialization can be explicitly
8719 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00008720 if (Previous.isAmbiguous())
8721 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008722
John McCall67c00872009-12-02 08:25:40 +00008723 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00008724 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008725
Larisse Voufo39a1e502013-08-06 01:03:05 +00008726 if (!PrevTemplate) {
8727 if (!Prev || !Prev->isStaticDataMember()) {
8728 // We expect to see a data data member here.
8729 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
8730 << Name;
8731 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
8732 P != PEnd; ++P)
8733 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
8734 return true;
8735 }
8736
8737 if (!Prev->getInstantiatedFromStaticDataMember()) {
8738 // FIXME: Check for explicit specialization?
8739 Diag(D.getIdentifierLoc(),
8740 diag::err_explicit_instantiation_data_member_not_instantiated)
8741 << Prev;
8742 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
8743 // FIXME: Can we provide a note showing where this was declared?
8744 return true;
8745 }
8746 } else {
8747 // Explicitly instantiate a variable template.
8748
8749 // C++1y [dcl.spec.auto]p6:
8750 // ... A program that uses auto or decltype(auto) in a context not
8751 // explicitly allowed in this section is ill-formed.
8752 //
8753 // This includes auto-typed variable template instantiations.
8754 if (R->isUndeducedType()) {
8755 Diag(T->getTypeLoc().getLocStart(),
8756 diag::err_auto_not_allowed_var_inst);
8757 return true;
8758 }
8759
Richard Smithef985ac2013-09-18 02:10:12 +00008760 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
8761 // C++1y [temp.explicit]p3:
8762 // If the explicit instantiation is for a variable, the unqualified-id
8763 // in the declaration shall be a template-id.
8764 Diag(D.getIdentifierLoc(),
8765 diag::err_explicit_instantiation_without_template_id)
8766 << PrevTemplate;
8767 Diag(PrevTemplate->getLocation(),
8768 diag::note_explicit_instantiation_here);
8769 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00008770 }
8771
Nathan Wilson83839122016-04-09 02:55:27 +00008772 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
8773 // explicit instantiation (14.8.2) [...] of a concept definition.
8774 if (PrevTemplate->isConcept()) {
8775 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
8776 << 1 /*variable*/ << 0 /*explicitly instantiated*/;
8777 Diag(PrevTemplate->getLocation(), diag::note_previous_declaration);
8778 return true;
8779 }
8780
Richard Smithef985ac2013-09-18 02:10:12 +00008781 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00008782 TemplateArgumentListInfo TemplateArgs =
8783 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00008784
Larisse Voufo39a1e502013-08-06 01:03:05 +00008785 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
8786 D.getIdentifierLoc(), TemplateArgs);
8787 if (Res.isInvalid())
8788 return true;
8789
8790 // Ignore access control bits, we don't need them for redeclaration
8791 // checking.
8792 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00008793 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008794
Douglas Gregore47f5a72009-10-14 23:41:34 +00008795 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008796 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008797 // or a static data member of a class template specialization, the name of
8798 // the class template specialization in the qualified-id for the member
8799 // name shall be a simple-template-id.
8800 //
8801 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00008802 //
Richard Smith5977d872013-09-18 21:55:14 +00008803 // This does not apply to variable template specializations, where the
8804 // template-id is in the unqualified-id instead.
8805 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008806 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00008807 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008808 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008809
Douglas Gregore47f5a72009-10-14 23:41:34 +00008810 // Check the scope of this explicit instantiation.
8811 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008812
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008813 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00008814 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
8815 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00008816 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008817 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00008818 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008819 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008820
Larisse Voufo39a1e502013-08-06 01:03:05 +00008821 if (!HasNoEffect) {
8822 // Instantiate static data member or variable template.
8823
8824 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
8825 if (PrevTemplate) {
8826 // Merge attributes.
8827 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
8828 ProcessDeclAttributeList(S, Prev, Attr);
8829 }
8830 if (TSK == TSK_ExplicitInstantiationDefinition)
8831 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
8832 }
8833
8834 // Check the new variable specialization against the parsed input.
8835 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
8836 Diag(T->getTypeLoc().getLocStart(),
8837 diag::err_invalid_var_template_spec_type)
8838 << 0 << PrevTemplate << R << Prev->getType();
8839 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
8840 << 2 << PrevTemplate->getDeclName();
8841 return true;
8842 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008843
Douglas Gregor450f00842009-09-25 18:43:00 +00008844 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00008845 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008846 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008847
8848 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00008849 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00008850 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00008851 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00008852 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00008853 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00008854 HasExplicitTemplateArgs = true;
8855 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008856
Douglas Gregor450f00842009-09-25 18:43:00 +00008857 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008858 // A [...] function [...] can be explicitly instantiated from its template.
8859 // A member function [...] of a class template can be explicitly
8860 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00008861 // template.
John McCall58cc69d2010-01-27 01:50:18 +00008862 UnresolvedSet<8> Matches;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008863 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
Larisse Voufo98b20f12013-07-19 23:00:19 +00008864 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00008865 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
8866 P != PEnd; ++P) {
8867 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00008868 if (!HasExplicitTemplateArgs) {
8869 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Richard Smithbaa47832016-12-01 02:11:49 +00008870 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
8871 /*AdjustExceptionSpec*/true);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00008872 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
Douglas Gregord90fd522009-09-25 21:45:23 +00008873 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00008874
John McCall58cc69d2010-01-27 01:50:18 +00008875 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00008876 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
8877 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00008878 }
Douglas Gregor450f00842009-09-25 18:43:00 +00008879 }
8880 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008881
Douglas Gregor450f00842009-09-25 18:43:00 +00008882 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
8883 if (!FunTmpl)
8884 continue;
8885
Larisse Voufo98b20f12013-07-19 23:00:19 +00008886 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00008887 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008888 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008889 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00008890 (HasExplicitTemplateArgs ? &TemplateArgs
8891 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00008892 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008893 // Keep track of almost-matches.
8894 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +00008895 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +00008896 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00008897 (void)TDK;
8898 continue;
8899 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008900
Artem Belevich64135c32016-12-08 19:38:13 +00008901 // Target attributes are part of the cuda function signature, so
8902 // the cuda target of the instantiated function must match that of its
8903 // template. Given that C++ template deduction does not take
8904 // target attributes into account, we reject candidates here that
8905 // have a different target.
8906 if (LangOpts.CUDA &&
8907 IdentifyCUDATarget(Specialization,
8908 /* IgnoreImplicitHDAttributes = */ true) !=
8909 IdentifyCUDATarget(Attr)) {
8910 FailedCandidates.addCandidate().set(
8911 P.getPair(), FunTmpl->getTemplatedDecl(),
8912 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
8913 continue;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008914 }
8915
John McCall58cc69d2010-01-27 01:50:18 +00008916 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00008917 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008918
Douglas Gregor450f00842009-09-25 18:43:00 +00008919 // Find the most specialized function template specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008920 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00008921 Matches.begin(), Matches.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00008922 D.getIdentifierLoc(),
8923 PDiag(diag::err_explicit_instantiation_not_known) << Name,
8924 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
8925 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00008926
John McCall58cc69d2010-01-27 01:50:18 +00008927 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00008928 return true;
John McCall58cc69d2010-01-27 01:50:18 +00008929
8930 // Ignore access control bits, we don't need them for redeclaration checking.
8931 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008932
Alexey Bataev73983912014-11-06 10:10:50 +00008933 // C++11 [except.spec]p4
8934 // In an explicit instantiation an exception-specification may be specified,
8935 // but is not required.
8936 // If an exception-specification is specified in an explicit instantiation
8937 // directive, it shall be compatible with the exception-specifications of
8938 // other declarations of that function.
8939 if (auto *FPT = R->getAs<FunctionProtoType>())
8940 if (FPT->hasExceptionSpec()) {
8941 unsigned DiagID =
8942 diag::err_mismatched_exception_spec_explicit_instantiation;
8943 if (getLangOpts().MicrosoftExt)
8944 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
8945 bool Result = CheckEquivalentExceptionSpec(
8946 PDiag(DiagID) << Specialization->getType(),
8947 PDiag(diag::note_explicit_instantiation_here),
8948 Specialization->getType()->getAs<FunctionProtoType>(),
8949 Specialization->getLocation(), FPT, D.getLocStart());
8950 // In Microsoft mode, mismatching exception specifications just cause a
8951 // warning.
8952 if (!getLangOpts().MicrosoftExt && Result)
8953 return true;
8954 }
8955
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008956 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008957 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00008958 diag::err_explicit_instantiation_member_function_not_instantiated)
8959 << Specialization
8960 << (Specialization->getTemplateSpecializationKind() ==
8961 TSK_ExplicitSpecialization);
8962 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
8963 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008964 }
8965
Douglas Gregorec9fd132012-01-14 16:38:05 +00008966 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00008967 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
8968 PrevDecl = Specialization;
8969
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008970 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00008971 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008972 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008973 PrevDecl,
8974 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008975 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008976 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008977 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008978
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008979 // FIXME: We may still want to build some representation of this
8980 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00008981 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00008982 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008983 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00008984
8985 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Rafael Espindola2aa7acf2012-01-04 05:40:59 +00008986 if (Attr)
8987 ProcessDeclAttributeList(S, Specialization, Attr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008988
Richard Smitheb36ddf2014-04-24 22:45:46 +00008989 if (Specialization->isDefined()) {
8990 // Let the ASTConsumer know that this function has been explicitly
8991 // instantiated now, and its linkage might have changed.
8992 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
8993 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00008994 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008995
Douglas Gregore47f5a72009-10-14 23:41:34 +00008996 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008997 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008998 // or a static data member of a class template specialization, the name of
8999 // the class template specialization in the qualified-id for the member
9000 // name shall be a simple-template-id.
9001 //
9002 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009003 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00009004 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009005 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00009006 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009007 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00009008 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00009009 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009010
Nathan Wilson83839122016-04-09 02:55:27 +00009011 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
9012 // explicit instantiation (14.8.2) [...] of a concept definition.
9013 if (FunTmpl && FunTmpl->isConcept() &&
9014 !D.getDeclSpec().isConceptSpecified()) {
9015 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
9016 << 0 /*function*/ << 0 /*explicitly instantiated*/;
9017 Diag(FunTmpl->getLocation(), diag::note_previous_declaration);
9018 return true;
9019 }
9020
Douglas Gregore47f5a72009-10-14 23:41:34 +00009021 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009022 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregore47f5a72009-10-14 23:41:34 +00009023 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009024 D.getIdentifierLoc(),
Douglas Gregore47f5a72009-10-14 23:41:34 +00009025 D.getCXXScopeSpec().isSet());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009026
Douglas Gregor450f00842009-09-25 18:43:00 +00009027 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00009028 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009029}
9030
John McCallfaf5fb42010-08-26 23:41:50 +00009031TypeResult
John McCall7f41d982009-09-11 04:59:25 +00009032Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
9033 const CXXScopeSpec &SS, IdentifierInfo *Name,
9034 SourceLocation TagLoc, SourceLocation NameLoc) {
9035 // This has to hold, because SS is expected to be defined.
9036 assert(Name && "Expected a name in a dependent tag");
9037
Aaron Ballman4a979672014-01-03 13:56:08 +00009038 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00009039 if (!NNS)
9040 return true;
9041
Abramo Bagnara6150c882010-05-11 21:36:43 +00009042 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00009043
Douglas Gregorba41d012010-04-24 16:38:41 +00009044 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
9045 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00009046 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00009047 return true;
9048 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00009049
Douglas Gregore7c20652011-03-02 00:47:37 +00009050 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00009051 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00009052 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009053
Douglas Gregore7c20652011-03-02 00:47:37 +00009054 // Create type-source location information for this type.
9055 TypeLocBuilder TLB;
9056 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009057 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00009058 TL.setQualifierLoc(SS.getWithLocInContext(Context));
9059 TL.setNameLoc(NameLoc);
9060 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00009061}
9062
John McCallfaf5fb42010-08-26 23:41:50 +00009063TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009064Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
9065 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00009066 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009067 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00009068 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009069
Richard Smith0bf8a4922011-10-18 20:49:44 +00009070 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9071 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009072 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00009073 diag::warn_cxx98_compat_typename_outside_of_template :
9074 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009075 << FixItHint::CreateRemoval(TypenameLoc);
9076
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009077 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00009078 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
9079 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00009080 if (T.isNull())
9081 return true;
John McCall99b2fe52010-04-29 23:50:39 +00009082
9083 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9084 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00009085 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009086 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009087 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00009088 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00009089 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00009090 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009091 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009092 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00009093 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00009094 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009095
John McCallba7bf592010-08-24 05:47:05 +00009096 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00009097}
9098
John McCallfaf5fb42010-08-26 23:41:50 +00009099TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009100Sema::ActOnTypenameType(Scope *S,
9101 SourceLocation TypenameLoc,
9102 const CXXScopeSpec &SS,
9103 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00009104 TemplateTy TemplateIn,
Richard Smith74f02342017-01-19 21:00:13 +00009105 IdentifierInfo *TemplateII,
9106 SourceLocation TemplateIILoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00009107 SourceLocation LAngleLoc,
9108 ASTTemplateArgsPtr TemplateArgsIn,
9109 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00009110 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9111 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009112 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00009113 diag::warn_cxx98_compat_typename_outside_of_template :
9114 diag::ext_typename_outside_of_template)
9115 << FixItHint::CreateRemoval(TypenameLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009116
Richard Smith74f02342017-01-19 21:00:13 +00009117 // Strangely, non-type results are not ignored by this lookup, so the
9118 // program is ill-formed if it finds an injected-class-name.
Richard Smith62559bd2017-02-01 21:36:38 +00009119 if (TypenameLoc.isValid()) {
9120 auto *LookupRD =
9121 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
9122 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
9123 Diag(TemplateIILoc,
9124 diag::ext_out_of_line_qualified_id_type_names_constructor)
9125 << TemplateII << 0 /*injected-class-name used as template name*/
9126 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
9127 }
Richard Smith74f02342017-01-19 21:00:13 +00009128 }
9129
Douglas Gregorb09518c2011-02-27 22:46:49 +00009130 // Translate the parser's template argument list in our AST format.
9131 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9132 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009133
Douglas Gregorb09518c2011-02-27 22:46:49 +00009134 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009135 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
9136 // Construct a dependent template specialization type.
9137 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00009138 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009139 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
9140 DTN->getQualifier(),
9141 DTN->getIdentifier(),
9142 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009143
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009144 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00009145 TypeLocBuilder Builder;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009146 DependentTemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009147 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009148 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
9149 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00009150 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00009151 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009152 SpecTL.setLAngleLoc(LAngleLoc);
9153 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009154 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9155 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009156 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00009157 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009158
Richard Smith74f02342017-01-19 21:00:13 +00009159 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009160 if (T.isNull())
9161 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009162
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009163 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00009164 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009165 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009166 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009167 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00009168 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009169 SpecTL.setLAngleLoc(LAngleLoc);
9170 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009171 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9172 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009173
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009174 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
9175 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009176 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009177 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Simon Pilgrim6905d222016-12-30 22:55:33 +00009178
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009179 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
9180 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00009181}
9182
Douglas Gregorb09518c2011-02-27 22:46:49 +00009183
Richard Smith6f8d2c62012-05-09 05:17:00 +00009184/// Determine whether this failed name lookup should be treated as being
9185/// disabled by a usage of std::enable_if.
9186static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
9187 SourceRange &CondRange) {
9188 // We must be looking for a ::type...
9189 if (!II.isStr("type"))
9190 return false;
9191
9192 // ... within an explicitly-written template specialization...
9193 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
9194 return false;
9195 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00009196 TemplateSpecializationTypeLoc EnableIfTSTLoc =
9197 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
9198 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00009199 return false;
9200 const TemplateSpecializationType *EnableIfTST =
David Blaikie6adc78e2013-02-18 22:06:02 +00009201 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
Richard Smith6f8d2c62012-05-09 05:17:00 +00009202
9203 // ... which names a complete class template declaration...
9204 const TemplateDecl *EnableIfDecl =
9205 EnableIfTST->getTemplateName().getAsTemplateDecl();
9206 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
9207 return false;
9208
9209 // ... called "enable_if".
9210 const IdentifierInfo *EnableIfII =
9211 EnableIfDecl->getDeclName().getAsIdentifierInfo();
9212 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
9213 return false;
9214
9215 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00009216 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009217 return true;
9218}
9219
Douglas Gregor333489b2009-03-27 23:10:48 +00009220/// \brief Build the type that describes a C++ typename specifier,
9221/// e.g., "typename T::type".
9222QualType
Simon Pilgrim6905d222016-12-30 22:55:33 +00009223Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009224 SourceLocation KeywordLoc,
Simon Pilgrim6905d222016-12-30 22:55:33 +00009225 NestedNameSpecifierLoc QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009226 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00009227 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00009228 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009229 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00009230
John McCall0b66eb32010-05-01 00:40:08 +00009231 DeclContext *Ctx = computeDeclContext(SS);
9232 if (!Ctx) {
9233 // If the nested-name-specifier is dependent and couldn't be
9234 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009235 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009236 return Context.getDependentNameType(Keyword,
9237 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009238 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00009239 }
Douglas Gregor333489b2009-03-27 23:10:48 +00009240
John McCall0b66eb32010-05-01 00:40:08 +00009241 // If the nested-name-specifier refers to the current instantiation,
9242 // the "typename" keyword itself is superfluous. In C++03, the
9243 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
9244 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00009245 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00009246
John McCall0b66eb32010-05-01 00:40:08 +00009247 if (RequireCompleteDeclContext(SS, Ctx))
9248 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00009249
9250 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00009251 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00009252 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00009253 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00009254 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00009255 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00009256 case LookupResult::NotFound: {
9257 // If we're looking up 'type' within a template named 'enable_if', produce
9258 // a more specific diagnostic.
9259 SourceRange CondRange;
9260 if (isEnableIf(QualifierLoc, II, CondRange)) {
9261 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
9262 << Ctx << CondRange;
9263 return QualType();
9264 }
9265
Douglas Gregore40876a2009-10-13 21:16:44 +00009266 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00009267 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009268 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009269
9270 case LookupResult::FoundUnresolvedValue: {
9271 // We found a using declaration that is a value. Most likely, the using
9272 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009273 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009274 IILoc);
9275 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
9276 << Name << Ctx << FullRange;
9277 if (UnresolvedUsingValueDecl *Using
9278 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009279 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009280 Diag(Loc, diag::note_using_value_decl_missing_typename)
9281 << FixItHint::CreateInsertion(Loc, "typename ");
9282 }
9283 }
9284 // Fall through to create a dependent typename type, from which we can recover
9285 // better.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009286
Douglas Gregord0d2ee02010-01-15 01:44:47 +00009287 case LookupResult::NotFoundInCurrentInstantiation:
9288 // Okay, it's a member of an unknown instantiation.
Simon Pilgrim6905d222016-12-30 22:55:33 +00009289 return Context.getDependentNameType(Keyword,
9290 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009291 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00009292
9293 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009294 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Richard Smith74f02342017-01-19 21:00:13 +00009295 // C++ [class.qual]p2:
9296 // In a lookup in which function names are not ignored and the
9297 // nested-name-specifier nominates a class C, if the name specified
9298 // after the nested-name-specifier, when looked up in C, is the
9299 // injected-class-name of C [...] then the name is instead considered
9300 // to name the constructor of class C.
9301 //
9302 // Unlike in an elaborated-type-specifier, function names are not ignored
9303 // in typename-specifier lookup. However, they are ignored in all the
9304 // contexts where we form a typename type with no keyword (that is, in
9305 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
9306 //
9307 // FIXME: That's not strictly true: mem-initializer-id lookup does not
9308 // ignore functions, but that appears to be an oversight.
9309 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
9310 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
9311 if (Keyword == ETK_Typename && LookupRD && FoundRD &&
9312 FoundRD->isInjectedClassName() &&
9313 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
9314 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
9315 << &II << 1 << 0 /*'typename' keyword used*/;
9316
Abramo Bagnara6150c882010-05-11 21:36:43 +00009317 // We found a type. Build an ElaboratedType, since the
9318 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00009319 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Richard Smith74f02342017-01-19 21:00:13 +00009320 return Context.getElaboratedType(Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009321 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00009322 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00009323 }
9324
Richard Smithee579842017-01-30 20:39:26 +00009325 // C++ [dcl.type.simple]p2:
9326 // A type-specifier of the form
9327 // typename[opt] nested-name-specifier[opt] template-name
9328 // is a placeholder for a deduced class type [...].
9329 if (getLangOpts().CPlusPlus1z) {
9330 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
9331 return Context.getElaboratedType(
9332 Keyword, QualifierLoc.getNestedNameSpecifier(),
9333 Context.getDeducedTemplateSpecializationType(TemplateName(TD),
9334 QualType(), false));
9335 }
9336 }
Richard Smith600b5262017-01-26 20:40:47 +00009337
Douglas Gregor333489b2009-03-27 23:10:48 +00009338 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00009339 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00009340 break;
9341
9342 case LookupResult::FoundOverloaded:
9343 DiagID = diag::err_typename_nested_not_type;
9344 Referenced = *Result.begin();
9345 break;
9346
John McCall6538c932009-10-10 05:48:19 +00009347 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00009348 return QualType();
9349 }
9350
9351 // If we get here, it's because name lookup did not find a
9352 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009353 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00009354 IILoc);
9355 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00009356 if (Referenced)
9357 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
9358 << Name;
9359 return QualType();
9360}
Douglas Gregor15acfb92009-08-06 16:20:37 +00009361
9362namespace {
9363 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00009364 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00009365 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00009366 SourceLocation Loc;
9367 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00009368
Douglas Gregor15acfb92009-08-06 16:20:37 +00009369 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00009370 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009371
Mike Stump11289f42009-09-09 15:08:12 +00009372 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00009373 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00009374 DeclarationName Entity)
9375 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00009376 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00009377
9378 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00009379 /// transformed.
9380 ///
9381 /// For the purposes of type reconstruction, a type has already been
9382 /// transformed if it is NULL or if it is not dependent.
9383 bool AlreadyTransformed(QualType T) {
9384 return T.isNull() || !T->isDependentType();
9385 }
Mike Stump11289f42009-09-09 15:08:12 +00009386
9387 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00009388 /// rebuilt.
9389 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00009390
Douglas Gregor15acfb92009-08-06 16:20:37 +00009391 /// \brief Returns the name of the entity whose type is being rebuilt.
9392 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00009393
Douglas Gregoref6ab412009-10-27 06:26:26 +00009394 /// \brief Sets the "base" location and entity when that
9395 /// information is known based on another transformation.
9396 void setBase(SourceLocation Loc, DeclarationName Entity) {
9397 this->Loc = Loc;
9398 this->Entity = Entity;
9399 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009400
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00009401 ExprResult TransformLambdaExpr(LambdaExpr *E) {
9402 // Lambdas never need to be transformed.
9403 return E;
9404 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00009405 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009406} // end anonymous namespace
Douglas Gregor15acfb92009-08-06 16:20:37 +00009407
Douglas Gregor15acfb92009-08-06 16:20:37 +00009408/// \brief Rebuilds a type within the context of the current instantiation.
9409///
Mike Stump11289f42009-09-09 15:08:12 +00009410/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00009411/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00009412/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00009413/// partial specialization thereof). This routine will rebuild that type now
9414/// that we have entered the declarator's scope, which may produce different
9415/// canonical types, e.g.,
9416///
9417/// \code
9418/// template<typename T>
9419/// struct X {
9420/// typedef T* pointer;
9421/// pointer data();
9422/// };
9423///
9424/// template<typename T>
9425/// typename X<T>::pointer X<T>::data() { ... }
9426/// \endcode
9427///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00009428/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00009429/// since we do not know that we can look into X<T> when we parsed the type.
9430/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00009431/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00009432/// as the canonical type of T*, allowing the return types of the out-of-line
9433/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00009434TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
9435 SourceLocation Loc,
9436 DeclarationName Name) {
9437 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00009438 return T;
Mike Stump11289f42009-09-09 15:08:12 +00009439
Douglas Gregor15acfb92009-08-06 16:20:37 +00009440 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
9441 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00009442}
Douglas Gregorbe999392009-09-15 16:23:51 +00009443
John McCalldadc5752010-08-24 06:29:42 +00009444ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00009445 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
9446 DeclarationName());
9447 return Rebuilder.TransformExpr(E);
9448}
9449
John McCall99b2fe52010-04-29 23:50:39 +00009450bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00009451 if (SS.isInvalid())
Douglas Gregor10176412011-02-25 16:07:42 +00009452 return true;
John McCall2408e322010-04-27 00:57:59 +00009453
Douglas Gregor10176412011-02-25 16:07:42 +00009454 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00009455 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
9456 DeclarationName());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009457 NestedNameSpecifierLoc Rebuilt
Douglas Gregor10176412011-02-25 16:07:42 +00009458 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009459 if (!Rebuilt)
Douglas Gregor10176412011-02-25 16:07:42 +00009460 return true;
John McCall99b2fe52010-04-29 23:50:39 +00009461
Douglas Gregor10176412011-02-25 16:07:42 +00009462 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00009463 return false;
John McCall2408e322010-04-27 00:57:59 +00009464}
9465
Douglas Gregor041b0842011-10-14 15:31:12 +00009466/// \brief Rebuild the template parameters now that we know we're in a current
9467/// instantiation.
9468bool Sema::RebuildTemplateParamsInCurrentInstantiation(
9469 TemplateParameterList *Params) {
9470 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
9471 Decl *Param = Params->getParam(I);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009472
Douglas Gregor041b0842011-10-14 15:31:12 +00009473 // There is nothing to rebuild in a type parameter.
9474 if (isa<TemplateTypeParmDecl>(Param))
9475 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009476
Douglas Gregor041b0842011-10-14 15:31:12 +00009477 // Rebuild the template parameter list of a template template parameter.
Simon Pilgrim6905d222016-12-30 22:55:33 +00009478 if (TemplateTemplateParmDecl *TTP
Douglas Gregor041b0842011-10-14 15:31:12 +00009479 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
9480 if (RebuildTemplateParamsInCurrentInstantiation(
9481 TTP->getTemplateParameters()))
9482 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009483
Douglas Gregor041b0842011-10-14 15:31:12 +00009484 continue;
9485 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009486
Douglas Gregor041b0842011-10-14 15:31:12 +00009487 // Rebuild the type of a non-type template parameter.
9488 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009489 TypeSourceInfo *NewTSI
9490 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
9491 NTTP->getLocation(),
Douglas Gregor041b0842011-10-14 15:31:12 +00009492 NTTP->getDeclName());
9493 if (!NewTSI)
9494 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009495
Douglas Gregor041b0842011-10-14 15:31:12 +00009496 if (NewTSI != NTTP->getTypeSourceInfo()) {
9497 NTTP->setTypeSourceInfo(NewTSI);
9498 NTTP->setType(NewTSI->getType());
9499 }
9500 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009501
Douglas Gregor041b0842011-10-14 15:31:12 +00009502 return false;
9503}
9504
Douglas Gregorbe999392009-09-15 16:23:51 +00009505/// \brief Produces a formatted string that describes the binding of
9506/// template parameters to template arguments.
9507std::string
9508Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9509 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009510 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00009511}
9512
9513std::string
9514Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9515 const TemplateArgument *Args,
9516 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009517 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +00009518 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +00009519
Douglas Gregore62e6a02009-11-11 19:13:48 +00009520 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00009521 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009522
Douglas Gregorbe999392009-09-15 16:23:51 +00009523 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00009524 if (I >= NumArgs)
9525 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009526
Douglas Gregorbe999392009-09-15 16:23:51 +00009527 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00009528 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +00009529 else
Douglas Gregor0192c232010-12-20 16:52:59 +00009530 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009531
Douglas Gregorbe999392009-09-15 16:23:51 +00009532 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +00009533 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +00009534 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +00009535 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +00009536 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009537
Douglas Gregor0192c232010-12-20 16:52:59 +00009538 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +00009539 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +00009540 }
Douglas Gregor0192c232010-12-20 16:52:59 +00009541
9542 Out << ']';
9543 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +00009544}
Francois Pichet1c229c02011-04-22 22:18:13 +00009545
Richard Smithe40f2ba2013-08-07 21:41:30 +00009546void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
9547 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +00009548 if (!FD)
9549 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +00009550
Justin Lebar28f09c52016-10-10 16:26:08 +00009551 auto LPT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00009552
9553 // Take tokens to avoid allocations
9554 LPT->Toks.swap(Toks);
9555 LPT->D = FnD;
Justin Lebar28f09c52016-10-10 16:26:08 +00009556 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00009557
9558 FD->setLateTemplateParsed(true);
9559}
9560
9561void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
9562 if (!FD)
9563 return;
9564 FD->setLateTemplateParsed(false);
9565}
Francois Pichet1c229c02011-04-22 22:18:13 +00009566
9567bool Sema::IsInsideALocalClassWithinATemplateFunction() {
9568 DeclContext *DC = CurContext;
9569
9570 while (DC) {
9571 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
9572 const FunctionDecl *FD = RD->isLocalClass();
9573 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
9574 } else if (DC->isTranslationUnit() || DC->isNamespace())
9575 return false;
9576
9577 DC = DC->getParent();
9578 }
9579 return false;
9580}
Richard Smith6739a102016-05-05 00:56:12 +00009581
Benjamin Kramera0a13c32016-08-06 11:21:04 +00009582namespace {
Richard Smith6739a102016-05-05 00:56:12 +00009583/// \brief Walk the path from which a declaration was instantiated, and check
9584/// that every explicit specialization along that path is visible. This enforces
9585/// C++ [temp.expl.spec]/6:
9586///
9587/// If a template, a member template or a member of a class template is
9588/// explicitly specialized then that specialization shall be declared before
9589/// the first use of that specialization that would cause an implicit
9590/// instantiation to take place, in every translation unit in which such a
9591/// use occurs; no diagnostic is required.
9592///
9593/// and also C++ [temp.class.spec]/1:
9594///
9595/// A partial specialization shall be declared before the first use of a
9596/// class template specialization that would make use of the partial
9597/// specialization as the result of an implicit or explicit instantiation
9598/// in every translation unit in which such a use occurs; no diagnostic is
9599/// required.
9600class ExplicitSpecializationVisibilityChecker {
9601 Sema &S;
9602 SourceLocation Loc;
9603 llvm::SmallVector<Module *, 8> Modules;
9604
9605public:
9606 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
9607 : S(S), Loc(Loc) {}
9608
9609 void check(NamedDecl *ND) {
9610 if (auto *FD = dyn_cast<FunctionDecl>(ND))
9611 return checkImpl(FD);
9612 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
9613 return checkImpl(RD);
9614 if (auto *VD = dyn_cast<VarDecl>(ND))
9615 return checkImpl(VD);
9616 if (auto *ED = dyn_cast<EnumDecl>(ND))
9617 return checkImpl(ED);
9618 }
9619
9620private:
9621 void diagnose(NamedDecl *D, bool IsPartialSpec) {
9622 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
9623 : Sema::MissingImportKind::ExplicitSpecialization;
9624 const bool Recover = true;
9625
9626 // If we got a custom set of modules (because only a subset of the
9627 // declarations are interesting), use them, otherwise let
9628 // diagnoseMissingImport intelligently pick some.
9629 if (Modules.empty())
9630 S.diagnoseMissingImport(Loc, D, Kind, Recover);
9631 else
9632 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
9633 }
9634
9635 // Check a specific declaration. There are three problematic cases:
9636 //
9637 // 1) The declaration is an explicit specialization of a template
9638 // specialization.
9639 // 2) The declaration is an explicit specialization of a member of an
9640 // templated class.
9641 // 3) The declaration is an instantiation of a template, and that template
9642 // is an explicit specialization of a member of a templated class.
9643 //
9644 // We don't need to go any deeper than that, as the instantiation of the
9645 // surrounding class / etc is not triggered by whatever triggered this
9646 // instantiation, and thus should be checked elsewhere.
9647 template<typename SpecDecl>
9648 void checkImpl(SpecDecl *Spec) {
9649 bool IsHiddenExplicitSpecialization = false;
9650 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
9651 IsHiddenExplicitSpecialization =
9652 Spec->getMemberSpecializationInfo()
9653 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
9654 : !S.hasVisibleDeclaration(Spec);
9655 } else {
9656 checkInstantiated(Spec);
9657 }
9658
9659 if (IsHiddenExplicitSpecialization)
9660 diagnose(Spec->getMostRecentDecl(), false);
9661 }
9662
9663 void checkInstantiated(FunctionDecl *FD) {
9664 if (auto *TD = FD->getPrimaryTemplate())
9665 checkTemplate(TD);
9666 }
9667
9668 void checkInstantiated(CXXRecordDecl *RD) {
9669 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
9670 if (!SD)
9671 return;
9672
9673 auto From = SD->getSpecializedTemplateOrPartial();
9674 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
9675 checkTemplate(TD);
9676 else if (auto *TD =
9677 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
9678 if (!S.hasVisibleDeclaration(TD))
9679 diagnose(TD, true);
9680 checkTemplate(TD);
9681 }
9682 }
9683
9684 void checkInstantiated(VarDecl *RD) {
9685 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
9686 if (!SD)
9687 return;
9688
9689 auto From = SD->getSpecializedTemplateOrPartial();
9690 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
9691 checkTemplate(TD);
9692 else if (auto *TD =
9693 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
9694 if (!S.hasVisibleDeclaration(TD))
9695 diagnose(TD, true);
9696 checkTemplate(TD);
9697 }
9698 }
9699
9700 void checkInstantiated(EnumDecl *FD) {}
9701
9702 template<typename TemplDecl>
9703 void checkTemplate(TemplDecl *TD) {
9704 if (TD->isMemberSpecialization()) {
9705 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
9706 diagnose(TD->getMostRecentDecl(), false);
9707 }
9708 }
9709};
Benjamin Kramera0a13c32016-08-06 11:21:04 +00009710} // end anonymous namespace
Richard Smith6739a102016-05-05 00:56:12 +00009711
9712void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
9713 if (!getLangOpts().Modules)
9714 return;
9715
9716 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
9717}
9718
9719/// \brief Check whether a template partial specialization that we've discovered
9720/// is hidden, and produce suitable diagnostics if so.
9721void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
9722 NamedDecl *Spec) {
9723 llvm::SmallVector<Module *, 8> Modules;
9724 if (!hasVisibleDeclaration(Spec, &Modules))
9725 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
9726 MissingImportKind::PartialSpecialization,
9727 /*Recover*/true);
9728}