blob: 788eaca674006b1a74d66a563d0a395db74bb70d [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()) {
Faisal Vali2ab8c152017-12-30 04:15:27 +0000172 case UnqualifiedIdKind::IK_Identifier:
Douglas Gregor3cf81312009-11-03 23:16:33 +0000173 TName = DeclarationName(Name.Identifier);
174 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000175
Faisal Vali2ab8c152017-12-30 04:15:27 +0000176 case UnqualifiedIdKind::IK_OperatorFunctionId:
Douglas Gregor3cf81312009-11-03 23:16:33 +0000177 TName = Context.DeclarationNames.getCXXOperatorName(
178 Name.OperatorFunctionId.Operator);
179 break;
180
Faisal Vali2ab8c152017-12-30 04:15:27 +0000181 case UnqualifiedIdKind::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) ||
Faisal Valia534f072018-04-26 00:42:40 +0000235 isa<BuiltinTemplateDecl>(TD));
Larisse Voufo39a1e502013-08-06 01:03:05 +0000236 TemplateKind =
Faisal Valia534f072018-04-26 00:42:40 +0000237 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
Richard Smith42bc73a2017-05-10 02:30:28 +0000458void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
459 SourceLocation Less,
460 SourceLocation Greater) {
461 if (TemplateName.isInvalid())
462 return;
463
464 DeclarationNameInfo NameInfo;
465 CXXScopeSpec SS;
466 LookupNameKind LookupKind;
467
468 DeclContext *LookupCtx = nullptr;
469 NamedDecl *Found = nullptr;
470
471 // Figure out what name we looked up.
472 if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
473 NameInfo = ME->getMemberNameInfo();
474 SS.Adopt(ME->getQualifierLoc());
475 LookupKind = LookupMemberName;
476 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
477 Found = ME->getMemberDecl();
478 } else {
479 auto *DRE = cast<DeclRefExpr>(TemplateName.get());
480 NameInfo = DRE->getNameInfo();
481 SS.Adopt(DRE->getQualifierLoc());
482 LookupKind = LookupOrdinaryName;
483 Found = DRE->getFoundDecl();
484 }
485
486 // Try to correct the name by looking for templates and C++ named casts.
487 struct TemplateCandidateFilter : CorrectionCandidateCallback {
488 TemplateCandidateFilter() {
489 WantTypeSpecifiers = false;
490 WantExpressionKeywords = false;
491 WantRemainingKeywords = false;
492 WantCXXNamedCasts = true;
493 };
494 bool ValidateCandidate(const TypoCorrection &Candidate) override {
495 if (auto *ND = Candidate.getCorrectionDecl())
496 return isAcceptableTemplateName(ND->getASTContext(), ND, true);
497 return Candidate.isKeyword();
498 }
499 };
500
501 DeclarationName Name = NameInfo.getName();
502 if (TypoCorrection Corrected =
503 CorrectTypo(NameInfo, LookupKind, S, &SS,
504 llvm::make_unique<TemplateCandidateFilter>(),
505 CTK_ErrorRecovery, LookupCtx)) {
506 auto *ND = Corrected.getFoundDecl();
507 if (ND)
508 ND = isAcceptableTemplateName(Context, ND,
509 /*AllowFunctionTemplates*/ true);
510 if (ND || Corrected.isKeyword()) {
511 if (LookupCtx) {
512 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
513 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
514 Name.getAsString() == CorrectedStr;
515 diagnoseTypo(Corrected,
516 PDiag(diag::err_non_template_in_member_template_id_suggest)
517 << Name << LookupCtx << DroppedSpecifier
Richard Smith52f8d192017-05-10 21:32:16 +0000518 << SS.getRange(), false);
Richard Smith42bc73a2017-05-10 02:30:28 +0000519 } else {
520 diagnoseTypo(Corrected,
521 PDiag(diag::err_non_template_in_template_id_suggest)
Richard Smith52f8d192017-05-10 21:32:16 +0000522 << Name, false);
Richard Smith42bc73a2017-05-10 02:30:28 +0000523 }
524 if (Found)
525 Diag(Found->getLocation(),
526 diag::note_non_template_in_template_id_found);
527 return;
528 }
529 }
530
531 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
532 << Name << SourceRange(Less, Greater);
533 if (Found)
534 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
535}
536
John McCallcd4b4772009-12-02 03:53:29 +0000537/// ActOnDependentIdExpression - Handle a dependent id-expression that
538/// was just parsed. This is only possible with an explicit scope
539/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000540ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000541Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000542 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000543 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000544 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000545 const TemplateArgumentListInfo *TemplateArgs) {
John McCall87fe5d52010-05-20 01:18:31 +0000546 DeclContext *DC = getFunctionLevelDeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000547
Reid Kleckner1af391df2016-03-11 18:59:12 +0000548 // C++11 [expr.prim.general]p12:
549 // An id-expression that denotes a non-static data member or non-static
550 // member function of a class can only be used:
551 // (...)
552 // - if that id-expression denotes a non-static data member and it
553 // appears in an unevaluated operand.
554 //
555 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
556 // CXXDependentScopeMemberExpr. The former can instantiate to either
557 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
558 // always a MemberExpr.
559 bool MightBeCxx11UnevalField =
560 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
561
Akira Hatanakad644e022016-12-16 03:19:41 +0000562 // Check if the nested name specifier is an enum type.
563 bool IsEnum = false;
564 if (NestedNameSpecifier *NNS = SS.getScopeRep())
565 IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
566
567 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
Reid Kleckner1af391df2016-03-11 18:59:12 +0000568 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
John McCall87fe5d52010-05-20 01:18:31 +0000569 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000570
John McCalle66edc12009-11-24 19:00:30 +0000571 // Since the 'this' expression is synthesized, we don't need to
572 // perform the double-lookup check.
Craig Topperc3ec1492014-05-26 06:22:03 +0000573 NamedDecl *FirstQualifierInScope = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000574
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000575 return CXXDependentScopeMemberExpr::Create(
576 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
577 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
578 FirstQualifierInScope, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000579 }
580
Abramo Bagnara7945c982012-01-27 09:46:47 +0000581 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000582}
583
John McCalldadc5752010-08-24 06:29:42 +0000584ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000585Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000586 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000587 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000588 const TemplateArgumentListInfo *TemplateArgs) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000589 return DependentScopeDeclRefExpr::Create(
590 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
591 TemplateArgs);
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000592}
593
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000594
595/// Determine whether we would be unable to instantiate this template (because
596/// it either has no definition, or is in the process of being instantiated).
597bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
598 NamedDecl *Instantiation,
599 bool InstantiatedFromMember,
600 const NamedDecl *Pattern,
601 const NamedDecl *PatternDef,
602 TemplateSpecializationKind TSK,
603 bool Complain /*= true*/) {
Richard Smithedbc6e92016-10-14 21:41:24 +0000604 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
605 isa<VarDecl>(Instantiation));
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000606
Richard Smithedbc6e92016-10-14 21:41:24 +0000607 bool IsEntityBeingDefined = false;
608 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
609 IsEntityBeingDefined = TD->isBeingDefined();
610
611 if (PatternDef && !IsEntityBeingDefined) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000612 NamedDecl *SuggestedDef = nullptr;
613 if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
614 /*OnlyNeedComplete*/false)) {
615 // If we're allowed to diagnose this and recover, do so.
616 bool Recover = Complain && !isSFINAEContext();
617 if (Complain)
618 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
619 Sema::MissingImportKind::Definition, Recover);
620 return !Recover;
621 }
622 return false;
623 }
624
Richard Smith6f4e2e02016-08-23 19:41:39 +0000625 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
626 return true;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000627
Richard Smithedbc6e92016-10-14 21:41:24 +0000628 llvm::Optional<unsigned> Note;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000629 QualType InstantiationTy;
630 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
631 InstantiationTy = Context.getTypeDeclType(TD);
Richard Smith6f4e2e02016-08-23 19:41:39 +0000632 if (PatternDef) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000633 Diag(PointOfInstantiation,
634 diag::err_template_instantiate_within_definition)
Richard Smithedbc6e92016-10-14 21:41:24 +0000635 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000636 << InstantiationTy;
637 // Not much point in noting the template declaration here, since
638 // we're lexically inside it.
639 Instantiation->setInvalidDecl();
640 } else if (InstantiatedFromMember) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000641 if (isa<FunctionDecl>(Instantiation)) {
642 Diag(PointOfInstantiation,
643 diag::err_explicit_instantiation_undefined_member)
Richard Smithedbc6e92016-10-14 21:41:24 +0000644 << /*member function*/ 1 << Instantiation->getDeclName()
645 << Instantiation->getDeclContext();
646 Note = diag::note_explicit_instantiation_here;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000647 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000648 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
Richard Smith6f4e2e02016-08-23 19:41:39 +0000649 Diag(PointOfInstantiation,
650 diag::err_implicit_instantiate_member_undefined)
651 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000652 Note = diag::note_member_declared_at;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000653 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000654 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000655 if (isa<FunctionDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000656 Diag(PointOfInstantiation,
657 diag::err_explicit_instantiation_undefined_func_template)
658 << Pattern;
Richard Smithedbc6e92016-10-14 21:41:24 +0000659 Note = diag::note_explicit_instantiation_here;
660 } else if (isa<TagDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000661 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
662 << (TSK != TSK_ImplicitInstantiation)
663 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000664 Note = diag::note_template_decl_here;
665 } else {
666 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
667 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
668 Diag(PointOfInstantiation,
669 diag::err_explicit_instantiation_undefined_var_template)
670 << Instantiation;
671 Instantiation->setInvalidDecl();
672 } else
673 Diag(PointOfInstantiation,
674 diag::err_explicit_instantiation_undefined_member)
675 << /*static data member*/ 2 << Instantiation->getDeclName()
676 << Instantiation->getDeclContext();
677 Note = diag::note_explicit_instantiation_here;
678 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000679 }
Richard Smithedbc6e92016-10-14 21:41:24 +0000680 if (Note) // Diagnostics were emitted.
681 Diag(Pattern->getLocation(), Note.getValue());
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000682
683 // In general, Instantiation isn't marked invalid to get more than one
684 // error for multiple undefined instantiations. But the code that does
685 // explicit declaration -> explicit definition conversion can't handle
686 // invalid declarations, so mark as invalid in that case.
687 if (TSK == TSK_ExplicitInstantiationDeclaration)
688 Instantiation->setInvalidDecl();
689 return true;
690}
691
Douglas Gregor5101c242008-12-05 18:15:24 +0000692/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
693/// that the template parameter 'PrevDecl' is being shadowed by a new
694/// declaration at location Loc. Returns true to indicate that this is
695/// an error, and false otherwise.
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000696void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000697 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000698
699 // Microsoft Visual C++ permits template parameters to be shadowed.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000700 if (getLangOpts().MicrosoftExt)
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000701 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000702
703 // C++ [temp.local]p4:
704 // A template-parameter shall not be redeclared within its
705 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000706 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000707 << cast<NamedDecl>(PrevDecl)->getDeclName();
708 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregor5101c242008-12-05 18:15:24 +0000709}
710
Douglas Gregor463421d2009-03-03 04:44:36 +0000711/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000712/// the parameter D to reference the templated declaration and return a pointer
713/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000714TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
715 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
716 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000717 return Temp;
718 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000719 return nullptr;
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000720}
721
Douglas Gregoreb29d182011-01-05 17:40:24 +0000722ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
723 SourceLocation EllipsisLoc) const {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000724 assert(Kind == Template &&
Douglas Gregoreb29d182011-01-05 17:40:24 +0000725 "Only template template arguments can be pack expansions here");
726 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
727 "Template template argument pack expansion without packs");
728 ParsedTemplateArgument Result(*this);
729 Result.EllipsisLoc = EllipsisLoc;
730 return Result;
731}
732
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000733static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
734 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000735
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000736 switch (Arg.getKind()) {
737 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000738 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000739 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000740 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000741 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000742 return TemplateArgumentLoc(TemplateArgument(T), DI);
743 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000744
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000745 case ParsedTemplateArgument::NonType: {
746 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
747 return TemplateArgumentLoc(TemplateArgument(E), E);
748 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000749
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000750 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000751 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregore1d60df2011-01-14 23:41:42 +0000752 TemplateArgument TArg;
753 if (Arg.getEllipsisLoc().isValid())
David Blaikie05785d12013-02-20 22:23:23 +0000754 TArg = TemplateArgument(Template, Optional<unsigned int>());
Douglas Gregore1d60df2011-01-14 23:41:42 +0000755 else
756 TArg = Template;
757 return TemplateArgumentLoc(TArg,
Douglas Gregor9d802122011-03-02 17:09:35 +0000758 Arg.getScopeSpec().getWithLocInContext(
759 SemaRef.Context),
Douglas Gregoreb29d182011-01-05 17:40:24 +0000760 Arg.getLocation(),
761 Arg.getEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000762 }
763 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000764
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000765 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000766}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000767
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000768/// \brief Translates template arguments as provided by the parser
769/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000770void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
771 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000772 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000773 TemplateArgs.addArgument(translateTemplateArgument(*this,
774 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000775}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000776
Richard Smithb80d5402013-06-25 22:21:36 +0000777static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
778 SourceLocation Loc,
779 IdentifierInfo *Name) {
780 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
Richard Smithbecb92d2017-10-10 22:33:17 +0000781 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
Richard Smithb80d5402013-06-25 22:21:36 +0000782 if (PrevDecl && PrevDecl->isTemplateParameter())
783 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
784}
785
Richard Smith77a9c602018-02-28 03:02:23 +0000786/// Convert a parsed type into a parsed template argument. This is mostly
787/// trivial, except that we may have parsed a C++17 deduced class template
788/// specialization type, in which case we should form a template template
789/// argument instead of a type template argument.
790ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
791 TypeSourceInfo *TInfo;
792 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
793 if (T.isNull())
794 return ParsedTemplateArgument();
795 assert(TInfo && "template argument with no location");
796
797 // If we might have formed a deduced template specialization type, convert
798 // it to a template template argument.
799 if (getLangOpts().CPlusPlus17) {
800 TypeLoc TL = TInfo->getTypeLoc();
801 SourceLocation EllipsisLoc;
802 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
803 EllipsisLoc = PET.getEllipsisLoc();
804 TL = PET.getPatternLoc();
805 }
806
807 CXXScopeSpec SS;
808 if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
809 SS.Adopt(ET.getQualifierLoc());
810 TL = ET.getNamedTypeLoc();
811 }
812
813 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
814 TemplateName Name = DTST.getTypePtr()->getTemplateName();
815 if (SS.isSet())
816 Name = Context.getQualifiedTemplateName(SS.getScopeRep(),
817 /*HasTemplateKeyword*/ false,
818 Name.getAsTemplateDecl());
819 ParsedTemplateArgument Result(SS, TemplateTy::make(Name),
820 DTST.getTemplateNameLoc());
821 if (EllipsisLoc.isValid())
822 Result = Result.getTemplatePackExpansion(EllipsisLoc);
823 return Result;
824 }
825 }
826
827 // This is a normal type template argument. Note, if the type template
828 // argument is an injected-class-name for a template, it has a dual nature
829 // and can be used as either a type or a template. We handle that in
830 // convertTypeTemplateArgumentToTemplate.
831 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
832 ParsedType.get().getAsOpaquePtr(),
833 TInfo->getTypeLoc().getLocStart());
834}
835
Douglas Gregor5101c242008-12-05 18:15:24 +0000836/// ActOnTypeParameter - Called when a C++ template type parameter
837/// (e.g., "typename T") has been parsed. Typename specifies whether
838/// the keyword "typename" was used to declare the type parameter
839/// (otherwise, "class" was used), and KeyLoc is the location of the
840/// "class" or "typename" keyword. ParamName is the name of the
841/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth08836322011-05-01 00:51:33 +0000842/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000843/// If the type parameter has a default argument, it will be added
844/// later via ActOnTypeParameterDefault.
Faisal Valibe294032017-12-23 18:56:34 +0000845NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
John McCall48871652010-08-21 09:40:31 +0000846 SourceLocation EllipsisLoc,
847 SourceLocation KeyLoc,
848 IdentifierInfo *ParamName,
849 SourceLocation ParamNameLoc,
850 unsigned Depth, unsigned Position,
851 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000852 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000853 assert(S->isTemplateParamScope() &&
854 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000855
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000856 SourceLocation Loc = ParamNameLoc;
857 if (!ParamName)
858 Loc = KeyLoc;
859
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000860 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregor5101c242008-12-05 18:15:24 +0000861 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000862 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000863 KeyLoc, Loc, Depth, Position, ParamName,
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000864 Typename, IsParameterPack);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000865 Param->setAccess(AS_public);
Douglas Gregor5101c242008-12-05 18:15:24 +0000866
867 if (ParamName) {
Richard Smithb80d5402013-06-25 22:21:36 +0000868 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
869
Douglas Gregor5101c242008-12-05 18:15:24 +0000870 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000871 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000872 IdResolver.AddDecl(Param);
873 }
874
Douglas Gregorf5500772011-01-05 15:48:55 +0000875 // C++0x [temp.param]p9:
876 // A default template-argument may be specified for any kind of
877 // template-parameter that is not a template parameter pack.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000878 if (DefaultArg && IsParameterPack) {
Douglas Gregorf5500772011-01-05 15:48:55 +0000879 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
David Blaikieefdccaa2016-01-15 23:43:34 +0000880 DefaultArg = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000881 }
882
Douglas Gregordc13ded2010-07-01 00:00:45 +0000883 // Handle the default argument, if provided.
884 if (DefaultArg) {
885 TypeSourceInfo *DefaultTInfo;
886 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000887
Douglas Gregordc13ded2010-07-01 00:00:45 +0000888 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000889
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000890 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000891 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000892 UPPC_DefaultArgument))
893 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000894
Douglas Gregordc13ded2010-07-01 00:00:45 +0000895 // Check the template argument itself.
896 if (CheckTemplateArgument(Param, DefaultTInfo)) {
897 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000898 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000899 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000900
Richard Smith1469b912015-06-10 00:29:03 +0000901 Param->setDefaultArgument(DefaultTInfo);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000902 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000903
John McCall48871652010-08-21 09:40:31 +0000904 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000905}
906
Douglas Gregor463421d2009-03-03 04:44:36 +0000907/// \brief Check that the type of a non-type template parameter is
908/// well-formed.
909///
910/// \returns the (possibly-promoted) parameter type if valid;
911/// otherwise, produces a diagnostic and returns a NULL type.
Richard Smith15361a22016-12-28 06:27:18 +0000912QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
913 SourceLocation Loc) {
914 if (TSI->getType()->isUndeducedType()) {
915 // C++1z [temp.dep.expr]p3:
916 // An id-expression is type-dependent if it contains
917 // - an identifier associated by name lookup with a non-type
918 // template-parameter declared with a type that contains a
919 // placeholder type (7.1.7.4),
920 TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
921 }
922
923 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
924}
925
926QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
927 SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000928 // We don't allow variably-modified types as the type of non-type template
929 // parameters.
930 if (T->isVariablyModifiedType()) {
931 Diag(Loc, diag::err_variably_modified_nontype_template_param)
932 << T;
933 return QualType();
934 }
935
Douglas Gregor463421d2009-03-03 04:44:36 +0000936 // C++ [temp.param]p4:
937 //
938 // A non-type template-parameter shall have one of the following
939 // (optionally cv-qualified) types:
940 //
941 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000942 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000943 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000944 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000945 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000946 T->isReferenceType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000947 // -- pointer to member,
Douglas Gregor463421d2009-03-03 04:44:36 +0000948 T->isMemberPointerType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000949 // -- std::nullptr_t.
950 T->isNullPtrType() ||
Douglas Gregor463421d2009-03-03 04:44:36 +0000951 // If T is a dependent type, we can't do the check now, so we
952 // assume that it is well-formed.
Richard Smith5f274382016-09-28 23:55:27 +0000953 T->isDependentType() ||
954 // Allow use of auto in template parameter declarations.
955 T->isUndeducedType()) {
Richard Smithd0e1c952012-03-13 07:21:50 +0000956 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
957 // are ignored when determining its type.
958 return T.getUnqualifiedType();
959 }
960
Douglas Gregor463421d2009-03-03 04:44:36 +0000961 // C++ [temp.param]p8:
962 //
963 // A non-type template-parameter of type "array of T" or
964 // "function returning T" is adjusted to be of type "pointer to
965 // T" or "pointer to function returning T", respectively.
Richard Smithd663fdd2014-12-17 20:42:37 +0000966 else if (T->isArrayType() || T->isFunctionType())
967 return Context.getDecayedType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000968
Douglas Gregor463421d2009-03-03 04:44:36 +0000969 Diag(Loc, diag::err_template_nontype_parm_bad_type)
970 << T;
971
972 return QualType();
973}
974
Faisal Valibe294032017-12-23 18:56:34 +0000975NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
John McCall48871652010-08-21 09:40:31 +0000976 unsigned Depth,
977 unsigned Position,
978 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000979 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000980 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Richard Smith15361a22016-12-28 06:27:18 +0000981
Faisal Valia223d1c2017-12-22 03:50:55 +0000982 // Check that we have valid decl-specifiers specified.
983 auto CheckValidDeclSpecifiers = [this, &D] {
984 // C++ [temp.param]
985 // p1
Malcolm Parsonsfab36802018-04-16 08:31:08 +0000986 // template-parameter:
987 // ...
988 // parameter-declaration
Faisal Valia223d1c2017-12-22 03:50:55 +0000989 // p2
990 // ... A storage class shall not be specified in a template-parameter
991 // declaration.
992 // [dcl.typedef]p1:
993 // The typedef specifier [...] shall not be used in the decl-specifier-seq
994 // of a parameter-declaration
995 const DeclSpec &DS = D.getDeclSpec();
996 auto EmitDiag = [this](SourceLocation Loc) {
997 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
998 << FixItHint::CreateRemoval(Loc);
999 };
1000 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1001 EmitDiag(DS.getStorageClassSpecLoc());
1002
Sam McCall1371cba2017-12-22 07:09:51 +00001003 if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
Faisal Valia223d1c2017-12-22 03:50:55 +00001004 EmitDiag(DS.getThreadStorageClassSpecLoc());
1005
1006 // [dcl.inline]p1:
1007 // The inline specifier can be applied only to the declaration or
1008 // definition of a variable or function.
1009
1010 if (DS.isInlineSpecified())
1011 EmitDiag(DS.getInlineSpecLoc());
1012
1013 // [dcl.constexpr]p1:
1014 // The constexpr specifier shall be applied only to the definition of a
1015 // variable or variable template or the declaration of a function or
1016 // function template.
1017
1018 if (DS.isConstexprSpecified())
1019 EmitDiag(DS.getConstexprSpecLoc());
1020
1021 // [dcl.fct.spec]p1:
1022 // Function-specifiers can be used only in function declarations.
1023
1024 if (DS.isVirtualSpecified())
1025 EmitDiag(DS.getVirtualSpecLoc());
1026
1027 if (DS.isExplicitSpecified())
1028 EmitDiag(DS.getExplicitSpecLoc());
1029
1030 if (DS.isNoreturnSpecified())
1031 EmitDiag(DS.getNoreturnSpecLoc());
1032 };
1033
1034 CheckValidDeclSpecifiers();
1035
Richard Smith15361a22016-12-28 06:27:18 +00001036 if (TInfo->getType()->isUndeducedType()) {
1037 Diag(D.getIdentifierLoc(),
1038 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1039 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1040 }
Douglas Gregor5101c242008-12-05 18:15:24 +00001041
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001042 assert(S->isTemplateParamScope() &&
1043 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +00001044 bool Invalid = false;
1045
Richard Smith15361a22016-12-28 06:27:18 +00001046 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001047 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001048 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +00001049 Invalid = true;
1050 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001051
Richard Smithb80d5402013-06-25 22:21:36 +00001052 IdentifierInfo *ParamName = D.getIdentifier();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +00001053 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor5101c242008-12-05 18:15:24 +00001054 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +00001055 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001056 D.getLocStart(),
John McCallf7b2fb52010-01-22 00:28:27 +00001057 D.getIdentifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001058 Depth, Position, ParamName, T,
Douglas Gregorda3cc0d2010-12-23 23:51:58 +00001059 IsParameterPack, TInfo);
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001060 Param->setAccess(AS_public);
Richard Smithb80d5402013-06-25 22:21:36 +00001061
Douglas Gregor5101c242008-12-05 18:15:24 +00001062 if (Invalid)
1063 Param->setInvalidDecl();
1064
Richard Smithb80d5402013-06-25 22:21:36 +00001065 if (ParamName) {
1066 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1067 ParamName);
1068
Douglas Gregor5101c242008-12-05 18:15:24 +00001069 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +00001070 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +00001071 IdResolver.AddDecl(Param);
1072 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001073
Douglas Gregorf5500772011-01-05 15:48:55 +00001074 // C++0x [temp.param]p9:
1075 // A default template-argument may be specified for any kind of
1076 // template-parameter that is not a template parameter pack.
1077 if (Default && IsParameterPack) {
1078 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
Craig Topperc3ec1492014-05-26 06:22:03 +00001079 Default = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +00001080 }
1081
Douglas Gregordc13ded2010-07-01 00:00:45 +00001082 // Check the well-formedness of the default template argument, if provided.
Douglas Gregorda3cc0d2010-12-23 23:51:58 +00001083 if (Default) {
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001084 // Check for unexpanded parameter packs.
1085 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
1086 return Param;
1087
Douglas Gregordc13ded2010-07-01 00:00:45 +00001088 TemplateArgument Converted;
Richard Smithd663fdd2014-12-17 20:42:37 +00001089 ExprResult DefaultRes =
1090 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
John Wiegley01296292011-04-08 18:41:53 +00001091 if (DefaultRes.isInvalid()) {
Douglas Gregordc13ded2010-07-01 00:00:45 +00001092 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +00001093 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +00001094 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001095 Default = DefaultRes.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001096
Richard Smith1469b912015-06-10 00:29:03 +00001097 Param->setDefaultArgument(Default);
Douglas Gregordc13ded2010-07-01 00:00:45 +00001098 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001099
John McCall48871652010-08-21 09:40:31 +00001100 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +00001101}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001102
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001103/// ActOnTemplateTemplateParameter - Called when a C++ template template
James Dennett2a4d13c2012-06-15 07:13:21 +00001104/// parameter (e.g. T in template <template \<typename> class T> class array)
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001105/// has been parsed. S is the current scope.
Faisal Valibe294032017-12-23 18:56:34 +00001106NamedDecl *Sema::ActOnTemplateTemplateParameter(Scope* S,
John McCall48871652010-08-21 09:40:31 +00001107 SourceLocation TmpLoc,
Richard Trieu9becef62011-09-09 03:18:59 +00001108 TemplateParameterList *Params,
Douglas Gregorf5500772011-01-05 15:48:55 +00001109 SourceLocation EllipsisLoc,
John McCall48871652010-08-21 09:40:31 +00001110 IdentifierInfo *Name,
1111 SourceLocation NameLoc,
1112 unsigned Depth,
1113 unsigned Position,
1114 SourceLocation EqualLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +00001115 ParsedTemplateArgument Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001116 assert(S->isTemplateParamScope() &&
1117 "Template template parameter not in template parameter scope!");
1118
1119 // Construct the parameter object.
Douglas Gregorf5500772011-01-05 15:48:55 +00001120 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001121 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +00001122 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001123 NameLoc.isInvalid()? TmpLoc : NameLoc,
1124 Depth, Position, IsParameterPack,
Douglas Gregorf5500772011-01-05 15:48:55 +00001125 Name, Params);
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001126 Param->setAccess(AS_public);
Simon Pilgrim6905d222016-12-30 22:55:33 +00001127
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001128 // If the template template parameter has a name, then link the identifier
Douglas Gregordc13ded2010-07-01 00:00:45 +00001129 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001130 if (Name) {
Richard Smithb80d5402013-06-25 22:21:36 +00001131 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1132
John McCall48871652010-08-21 09:40:31 +00001133 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001134 IdResolver.AddDecl(Param);
1135 }
1136
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001137 if (Params->size() == 0) {
1138 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1139 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1140 Param->setInvalidDecl();
1141 }
1142
Douglas Gregorf5500772011-01-05 15:48:55 +00001143 // C++0x [temp.param]p9:
1144 // A default template-argument may be specified for any kind of
1145 // template-parameter that is not a template parameter pack.
1146 if (IsParameterPack && !Default.isInvalid()) {
1147 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1148 Default = ParsedTemplateArgument();
1149 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001150
Douglas Gregordc13ded2010-07-01 00:00:45 +00001151 if (!Default.isInvalid()) {
1152 // Check only that we have a template template argument. We don't want to
1153 // try to check well-formedness now, because our template template parameter
1154 // might have dependent types in its template parameters, which we wouldn't
1155 // be able to match now.
1156 //
1157 // If none of the template template parameter's template arguments mention
1158 // other template parameters, we could actually perform more checking here.
1159 // However, it isn't worth doing.
1160 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1161 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
Faisal Valib8b04f82016-03-26 20:46:45 +00001162 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
Douglas Gregordc13ded2010-07-01 00:00:45 +00001163 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00001164 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +00001165 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001166
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001167 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001168 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001169 DefaultArg.getArgument().getAsTemplate(),
1170 UPPC_DefaultArgument))
1171 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001172
Richard Smith1469b912015-06-10 00:29:03 +00001173 Param->setDefaultArgument(Context, DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +00001174 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001175
John McCall48871652010-08-21 09:40:31 +00001176 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +00001177}
1178
Hubert Tongf608c052016-04-29 18:05:37 +00001179/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1180/// constrained by RequiresClause, that contains the template parameters in
1181/// Params.
Richard Trieu9becef62011-09-09 03:18:59 +00001182TemplateParameterList *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001183Sema::ActOnTemplateParameterList(unsigned Depth,
1184 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001185 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001186 SourceLocation LAngleLoc,
Faisal Valif241b0d2017-08-25 18:24:20 +00001187 ArrayRef<NamedDecl *> Params,
Hubert Tongf608c052016-04-29 18:05:37 +00001188 SourceLocation RAngleLoc,
1189 Expr *RequiresClause) {
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001190 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001191 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001192
David Majnemer902f8c62015-12-27 07:16:27 +00001193 return TemplateParameterList::Create(
1194 Context, TemplateLoc, LAngleLoc,
Faisal Valif241b0d2017-08-25 18:24:20 +00001195 llvm::makeArrayRef(Params.data(), Params.size()),
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00001196 RAngleLoc, RequiresClause);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001197}
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001198
John McCall3e11ebe2010-03-15 10:12:16 +00001199static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
1200 if (SS.isSet())
Douglas Gregor14454802011-02-25 02:25:35 +00001201 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +00001202}
1203
John McCallfaf5fb42010-08-26 23:41:50 +00001204DeclResult
Faisal Vali090da2d2018-01-01 18:23:28 +00001205Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001206 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001207 IdentifierInfo *Name, SourceLocation NameLoc,
1208 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001209 TemplateParameterList *TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00001210 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001211 SourceLocation FriendLoc,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001212 unsigned NumOuterTemplateParamLists,
Richard Smithbe3980b2015-03-27 00:41:57 +00001213 TemplateParameterList** OuterTemplateParamLists,
Richard Smithd9ba2242015-05-07 03:54:19 +00001214 SkipBodyInfo *SkipBody) {
Mike Stump11289f42009-09-09 15:08:12 +00001215 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001216 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +00001217 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +00001218 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001219
1220 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001221 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001222 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001223
Abramo Bagnara6150c882010-05-11 21:36:43 +00001224 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1225 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001226
1227 // There is no such thing as an unnamed class template.
1228 if (!Name) {
1229 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001230 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001231 }
1232
Richard Smith6483d222012-04-21 01:27:54 +00001233 // Find any previous declaration with this name. For a friend with no
1234 // scope explicitly specified, we only look for tag declarations (per
1235 // C++11 [basic.lookup.elab]p2).
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001236 DeclContext *SemanticContext;
Richard Smith6483d222012-04-21 01:27:54 +00001237 LookupResult Previous(*this, Name, NameLoc,
1238 (SS.isEmpty() && TUK == TUK_Friend)
1239 ? LookupTagName : LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00001240 forRedeclarationInCurContext());
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001241 if (SS.isNotEmpty() && !SS.isInvalid()) {
1242 SemanticContext = computeDeclContext(SS, true);
1243 if (!SemanticContext) {
Douglas Gregor67daacb2012-03-30 16:20:47 +00001244 // FIXME: Horrible, horrible hack! We can't currently represent this
1245 // in the AST, and historically we have just ignored such friend
1246 // class templates, so don't complain here.
Richard Smithcd556eb2013-11-08 18:59:56 +00001247 Diag(NameLoc, TUK == TUK_Friend
1248 ? diag::warn_template_qualified_friend_ignored
1249 : diag::err_template_qualified_declarator_no_match)
Douglas Gregor67daacb2012-03-30 16:20:47 +00001250 << SS.getScopeRep() << SS.getRange();
Richard Smithcd556eb2013-11-08 18:59:56 +00001251 return TUK != TUK_Friend;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001252 }
Mike Stump11289f42009-09-09 15:08:12 +00001253
John McCall0b66eb32010-05-01 00:40:08 +00001254 if (RequireCompleteDeclContext(SS, SemanticContext))
1255 return true;
1256
Simon Pilgrim6905d222016-12-30 22:55:33 +00001257 // If we're adding a template to a dependent context, we may need to
1258 // rebuilding some of the types used within the template parameter list,
Douglas Gregor041b0842011-10-14 15:31:12 +00001259 // now that we know what the current instantiation is.
1260 if (SemanticContext->isDependentContext()) {
1261 ContextRAII SavedContext(*this, SemanticContext);
1262 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1263 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00001264 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
Richard Smithc660c8f2018-03-16 13:36:56 +00001265 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc, false);
Richard Smith6483d222012-04-21 01:27:54 +00001266
John McCall27b18f82009-11-17 02:14:36 +00001267 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001268 } else {
1269 SemanticContext = CurContext;
Richard Smith88fe69c2015-07-06 01:45:27 +00001270
1271 // C++14 [class.mem]p14:
1272 // If T is the name of a class, then each of the following shall have a
1273 // name different from T:
1274 // -- every member template of class T
1275 if (TUK != TUK_Friend &&
1276 DiagnoseClassNameShadow(SemanticContext,
1277 DeclarationNameInfo(Name, NameLoc)))
1278 return true;
1279
John McCall27b18f82009-11-17 02:14:36 +00001280 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001281 }
Mike Stump11289f42009-09-09 15:08:12 +00001282
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001283 if (Previous.isAmbiguous())
1284 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001285
Craig Topperc3ec1492014-05-26 06:22:03 +00001286 NamedDecl *PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001287 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001288 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001289
Serge Pavlove50bf752016-06-10 04:39:07 +00001290 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1291 // Maybe we will complain about the shadowed template parameter.
1292 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1293 // Just pretend that we didn't see the previous declaration.
1294 PrevDecl = nullptr;
1295 }
1296
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001297 // If there is a previous declaration with the same name, check
1298 // whether this is a valid redeclaration.
Richard Smithbecb92d2017-10-10 22:33:17 +00001299 ClassTemplateDecl *PrevClassTemplate =
1300 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001301
1302 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001303 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001304 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001305 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001306 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1307 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001308 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001309 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1310 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1311 PrevClassTemplate
1312 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1313 ->getSpecializedTemplate();
1314 }
1315 }
1316
John McCalld43784f2009-12-18 11:25:59 +00001317 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +00001318 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001319 // [...] When looking for a prior declaration of a class or a function
1320 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +00001321 // function is neither a qualified name nor a template-id, scopes outside
1322 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +00001323 if (!SS.isSet()) {
1324 DeclContext *OutermostContext = CurContext;
1325 while (!OutermostContext->isFileContext())
1326 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +00001327
Richard Smith61e582f2012-04-20 07:12:26 +00001328 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +00001329 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1330 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1331 SemanticContext = PrevDecl->getDeclContext();
1332 } else {
1333 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001334 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +00001335 // declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00001336 PrevDecl = PrevClassTemplate = nullptr;
Douglas Gregorb74b1032010-04-18 17:37:40 +00001337 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +00001338
1339 // Check that the chosen semantic context doesn't already contain a
1340 // declaration of this name as a non-tag type.
Richard Smithfc805ca2015-07-06 04:43:58 +00001341 Previous.clear(LookupOrdinaryName);
Richard Smith6483d222012-04-21 01:27:54 +00001342 DeclContext *LookupContext = SemanticContext;
1343 while (LookupContext->isTransparentContext())
1344 LookupContext = LookupContext->getLookupParent();
1345 LookupQualifiedName(Previous, LookupContext);
1346
1347 if (Previous.isAmbiguous())
1348 return true;
1349
1350 if (Previous.begin() != Previous.end())
1351 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +00001352 }
John McCall90d3bb92009-12-17 23:21:11 +00001353 }
Richard Smith72bcaec2013-12-05 04:30:04 +00001354 } else if (PrevDecl &&
Richard Smithfc805ca2015-07-06 04:43:58 +00001355 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1356 S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +00001357 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001358
Richard Smithfc805ca2015-07-06 04:43:58 +00001359 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1360 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1361 if (SS.isEmpty() &&
1362 !(PrevClassTemplate &&
1363 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1364 SemanticContext->getRedeclContext()))) {
1365 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1366 Diag(Shadow->getTargetDecl()->getLocation(),
1367 diag::note_using_decl_target);
1368 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1369 // Recover by ignoring the old declaration.
1370 PrevDecl = PrevClassTemplate = nullptr;
1371 }
1372 }
1373
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001374 // TODO Memory management; associated constraints are not always stored.
1375 Expr *const CurAC = formAssociatedConstraints(TemplateParams, nullptr);
1376
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001377 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +00001378 // Ensure that the template parameter lists are compatible. Skip this check
1379 // for a friend in a dependent context: the template parameter list itself
1380 // could be dependent.
1381 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1382 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001383 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001384 /*Complain=*/true,
1385 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001386 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001387
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001388 // Check for matching associated constraints on redeclarations.
1389 const Expr *const PrevAC = PrevClassTemplate->getAssociatedConstraints();
1390 const bool RedeclACMismatch = [&] {
1391 if (!(CurAC || PrevAC))
1392 return false; // Nothing to check; no mismatch.
1393 if (CurAC && PrevAC) {
1394 llvm::FoldingSetNodeID CurACInfo, PrevACInfo;
1395 CurAC->Profile(CurACInfo, Context, /*Canonical=*/true);
1396 PrevAC->Profile(PrevACInfo, Context, /*Canonical=*/true);
1397 if (CurACInfo == PrevACInfo)
1398 return false; // All good; no mismatch.
1399 }
1400 return true;
1401 }();
1402
1403 if (RedeclACMismatch) {
1404 Diag(CurAC ? CurAC->getLocStart() : NameLoc,
1405 diag::err_template_different_associated_constraints);
1406 Diag(PrevAC ? PrevAC->getLocStart() : PrevClassTemplate->getLocation(),
1407 diag::note_template_prev_declaration) << /*declaration*/0;
1408 return true;
1409 }
1410
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001411 // C++ [temp.class]p4:
1412 // In a redeclaration, partial specialization, explicit
1413 // specialization or explicit instantiation of a class template,
1414 // the class-key shall agree in kind with the original class
1415 // template declaration (7.1.5.3).
1416 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +00001417 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001418 TUK == TUK_Definition, KWLoc, Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00001419 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00001420 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00001421 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001422 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00001423 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001424 }
1425
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001426 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +00001427 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001428 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001429 // If we have a prior definition that is not visible, treat this as
1430 // simply making that previous definition visible.
1431 NamedDecl *Hidden = nullptr;
1432 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
Richard Smithd9ba2242015-05-07 03:54:19 +00001433 SkipBody->ShouldSkip = true;
Richard Smithbe3980b2015-03-27 00:41:57 +00001434 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1435 assert(Tmpl && "original definition of a class template is not a "
1436 "class template?");
Richard Smith858e0e02017-05-11 23:11:16 +00001437 makeMergedDefinitionVisible(Hidden);
1438 makeMergedDefinitionVisible(Tmpl);
Richard Smithbe3980b2015-03-27 00:41:57 +00001439 return Def;
1440 }
1441
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001442 Diag(NameLoc, diag::err_redefinition) << Name;
1443 Diag(Def->getLocation(), diag::note_previous_definition);
1444 // FIXME: Would it make sense to try to "forget" the previous
1445 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +00001446 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001447 }
Serge Pavlove50bf752016-06-10 04:39:07 +00001448 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001449 } else if (PrevDecl) {
1450 // C++ [temp]p5:
1451 // A class template shall not have the same name as any other
1452 // template, class, function, object, enumeration, enumerator,
1453 // namespace, or type in the same scope (3.3), except as specified
1454 // in (14.5.4).
1455 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1456 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001457 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001458 }
1459
Douglas Gregordba32632009-02-10 19:49:53 +00001460 // Check the template parameter list of this declaration, possibly
1461 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001462 // template declaration. Skip this check for a friend in a dependent
1463 // context, because the template parameter list might be dependent.
1464 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001465 CheckTemplateParameterList(
1466 TemplateParams,
Craig Topperc3ec1492014-05-26 06:22:03 +00001467 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1468 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001469 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1470 SemanticContext->isDependentContext())
1471 ? TPC_ClassTemplateMember
1472 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1473 : TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +00001474 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001475
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001476 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001477 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001478 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001479 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1480 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001481 : diag::err_member_decl_does_not_match)
1482 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001483 Invalid = true;
1484 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001485 }
1486
Vassil Vassilev352e4412017-01-12 09:16:26 +00001487 // If this is a templated friend in a dependent context we should not put it
1488 // on the redecl chain. In some cases, the templated friend can be the most
1489 // recent declaration tricking the template instantiator to make substitutions
1490 // there.
1491 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1492 bool ShouldAddRedecl
1493 = !(TUK == TUK_Friend && CurContext->isDependentContext());
1494
Mike Stump11289f42009-09-09 15:08:12 +00001495 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001496 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Vassil Vassilev352e4412017-01-12 09:16:26 +00001497 PrevClassTemplate && ShouldAddRedecl ?
Craig Topperc3ec1492014-05-26 06:22:03 +00001498 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001499 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +00001500 SetNestedNameSpecifier(NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001501 if (NumOuterTemplateParamLists > 0)
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001502 NewClass->setTemplateParameterListsInfo(
1503 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1504 NumOuterTemplateParamLists));
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001505
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001506 // Add alignment attributes if necessary; these attributes are checked when
1507 // the ASTContext lays out the structure.
Eli Friedman0415f3e12012-08-08 21:08:34 +00001508 if (TUK == TUK_Definition) {
1509 AddAlignmentAttributesForRecord(NewClass);
1510 AddMsStructLayoutForRecord(NewClass);
1511 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001512
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001513 // Attach the associated constraints when the declaration will not be part of
1514 // a decl chain.
1515 Expr *const ACtoAttach =
1516 PrevClassTemplate && ShouldAddRedecl ? nullptr : CurAC;
1517
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001518 ClassTemplateDecl *NewTemplate
1519 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1520 DeclarationName(Name), TemplateParams,
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001521 NewClass, ACtoAttach);
Vassil Vassilev352e4412017-01-12 09:16:26 +00001522
1523 if (ShouldAddRedecl)
1524 NewTemplate->setPreviousDecl(PrevClassTemplate);
1525
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001526 NewClass->setDescribedClassTemplate(NewTemplate);
Simon Pilgrim6905d222016-12-30 22:55:33 +00001527
Douglas Gregor21823bf2011-12-20 18:11:52 +00001528 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001529 NewTemplate->setModulePrivate();
Simon Pilgrim6905d222016-12-30 22:55:33 +00001530
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001531 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001532 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001533 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001534 assert(T->isDependentType() && "Class template type is not dependent?");
1535 (void)T;
1536
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001537 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001538 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001539 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001540 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1541 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001542
Anders Carlsson137108d2009-03-26 01:24:28 +00001543 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001544 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001545 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001546
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001547 // Set the lexical context of these templates
1548 NewClass->setLexicalDeclContext(CurContext);
1549 NewTemplate->setLexicalDeclContext(CurContext);
1550
John McCall9bb74a52009-07-31 02:45:11 +00001551 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001552 NewClass->startDefinition();
1553
1554 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00001555 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001556
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001557 if (PrevClassTemplate)
1558 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1559
Rafael Espindola385c0422012-07-13 18:04:45 +00001560 AddPushedVisibilityAttribute(NewClass);
1561
Richard Smith234ff472014-08-23 00:49:01 +00001562 if (TUK != TUK_Friend) {
1563 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1564 Scope *Outer = S;
1565 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1566 Outer = Outer->getParent();
1567 PushOnScopeChains(NewTemplate, Outer);
1568 } else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001569 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001570 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001571 NewClass->setAccess(PrevClassTemplate->getAccess());
1572 }
John McCall27b5c252009-09-14 21:59:20 +00001573
Richard Smith64017682013-07-17 23:53:16 +00001574 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001575
John McCall27b5c252009-09-14 21:59:20 +00001576 // Friend templates are visible in fairly strange ways.
1577 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001578 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001579 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001580 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1581 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001582 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001583 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001584
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001585 FriendDecl *Friend = FriendDecl::Create(
1586 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
Douglas Gregor3dad8422009-09-26 06:47:28 +00001587 Friend->setAccess(AS_public);
1588 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001589 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001590
Richard Smithbecb92d2017-10-10 22:33:17 +00001591 if (PrevClassTemplate)
1592 CheckRedeclarationModuleOwnership(NewTemplate, PrevClassTemplate);
1593
Douglas Gregordba32632009-02-10 19:49:53 +00001594 if (Invalid) {
1595 NewTemplate->setInvalidDecl();
1596 NewClass->setInvalidDecl();
1597 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001598
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001599 ActOnDocumentableDecl(NewTemplate);
1600
John McCall48871652010-08-21 09:40:31 +00001601 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001602}
1603
Richard Smith32918772017-02-14 00:25:28 +00001604namespace {
1605/// Transform to convert portions of a constructor declaration into the
1606/// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
1607struct ConvertConstructorToDeductionGuideTransform {
1608 ConvertConstructorToDeductionGuideTransform(Sema &S,
1609 ClassTemplateDecl *Template)
1610 : SemaRef(S), Template(Template) {}
1611
1612 Sema &SemaRef;
1613 ClassTemplateDecl *Template;
1614
1615 DeclContext *DC = Template->getDeclContext();
1616 CXXRecordDecl *Primary = Template->getTemplatedDecl();
1617 DeclarationName DeductionGuideName =
1618 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
1619
1620 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
1621
1622 // Index adjustment to apply to convert depth-1 template parameters into
1623 // depth-0 template parameters.
1624 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
1625
1626 /// Transform a constructor declaration into a deduction guide.
Richard Smithbc491202017-02-17 20:05:37 +00001627 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
1628 CXXConstructorDecl *CD) {
Richard Smith32918772017-02-14 00:25:28 +00001629 SmallVector<TemplateArgument, 16> SubstArgs;
1630
Richard Smithb4f96252017-02-21 06:30:38 +00001631 LocalInstantiationScope Scope(SemaRef);
1632
Richard Smith32918772017-02-14 00:25:28 +00001633 // C++ [over.match.class.deduct]p1:
1634 // -- For each constructor of the class template designated by the
1635 // template-name, a function template with the following properties:
1636
1637 // -- The template parameters are the template parameters of the class
1638 // template followed by the template parameters (including default
1639 // template arguments) of the constructor, if any.
1640 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
1641 if (FTD) {
1642 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
1643 SmallVector<NamedDecl *, 16> AllParams;
1644 AllParams.reserve(TemplateParams->size() + InnerParams->size());
1645 AllParams.insert(AllParams.begin(),
1646 TemplateParams->begin(), TemplateParams->end());
1647 SubstArgs.reserve(InnerParams->size());
1648
1649 // Later template parameters could refer to earlier ones, so build up
1650 // a list of substituted template arguments as we go.
1651 for (NamedDecl *Param : *InnerParams) {
1652 MultiLevelTemplateArgumentList Args;
1653 Args.addOuterTemplateArguments(SubstArgs);
Richard Smithb4f96252017-02-21 06:30:38 +00001654 Args.addOuterRetainedLevel();
Richard Smith32918772017-02-14 00:25:28 +00001655 NamedDecl *NewParam = transformTemplateParameter(Param, Args);
1656 if (!NewParam)
1657 return nullptr;
1658 AllParams.push_back(NewParam);
1659 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
1660 SemaRef.Context.getInjectedTemplateArg(NewParam)));
1661 }
1662 TemplateParams = TemplateParameterList::Create(
1663 SemaRef.Context, InnerParams->getTemplateLoc(),
1664 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
1665 /*FIXME: RequiresClause*/ nullptr);
1666 }
1667
1668 // If we built a new template-parameter-list, track that we need to
1669 // substitute references to the old parameters into references to the
1670 // new ones.
1671 MultiLevelTemplateArgumentList Args;
1672 if (FTD) {
1673 Args.addOuterTemplateArguments(SubstArgs);
Richard Smithb4f96252017-02-21 06:30:38 +00001674 Args.addOuterRetainedLevel();
Richard Smith32918772017-02-14 00:25:28 +00001675 }
1676
Richard Smithbc491202017-02-17 20:05:37 +00001677 FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
Richard Smith32918772017-02-14 00:25:28 +00001678 .getAsAdjusted<FunctionProtoTypeLoc>();
1679 assert(FPTL && "no prototype for constructor declaration");
1680
1681 // Transform the type of the function, adjusting the return type and
1682 // replacing references to the old parameters with references to the
1683 // new ones.
1684 TypeLocBuilder TLB;
1685 SmallVector<ParmVarDecl*, 8> Params;
1686 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args);
1687 if (NewType.isNull())
1688 return nullptr;
1689 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
1690
Richard Smithbc491202017-02-17 20:05:37 +00001691 return buildDeductionGuide(TemplateParams, CD->isExplicit(), NewTInfo,
1692 CD->getLocStart(), CD->getLocation(),
1693 CD->getLocEnd());
Richard Smith32918772017-02-14 00:25:28 +00001694 }
1695
1696 /// Build a deduction guide with the specified parameter types.
1697 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
1698 SourceLocation Loc = Template->getLocation();
1699
1700 // Build the requested type.
1701 FunctionProtoType::ExtProtoInfo EPI;
1702 EPI.HasTrailingReturn = true;
1703 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
1704 DeductionGuideName, EPI);
1705 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
1706
1707 FunctionProtoTypeLoc FPTL =
1708 TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
1709
1710 // Build the parameters, needed during deduction / substitution.
1711 SmallVector<ParmVarDecl*, 4> Params;
1712 for (auto T : ParamTypes) {
1713 ParmVarDecl *NewParam = ParmVarDecl::Create(
1714 SemaRef.Context, DC, Loc, Loc, nullptr, T,
1715 SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
1716 NewParam->setScopeInfo(0, Params.size());
1717 FPTL.setParam(Params.size(), NewParam);
1718 Params.push_back(NewParam);
1719 }
1720
1721 return buildDeductionGuide(Template->getTemplateParameters(), false, TSI,
1722 Loc, Loc, Loc);
1723 }
1724
1725private:
1726 /// Transform a constructor template parameter into a deduction guide template
1727 /// parameter, rebuilding any internal references to earlier parameters and
1728 /// renumbering as we go.
1729 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
1730 MultiLevelTemplateArgumentList &Args) {
1731 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
1732 // TemplateTypeParmDecl's index cannot be changed after creation, so
1733 // substitute it directly.
1734 auto *NewTTP = TemplateTypeParmDecl::Create(
1735 SemaRef.Context, DC, TTP->getLocStart(), TTP->getLocation(),
1736 /*Depth*/0, Depth1IndexAdjustment + TTP->getIndex(),
1737 TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
1738 TTP->isParameterPack());
1739 if (TTP->hasDefaultArgument()) {
1740 TypeSourceInfo *InstantiatedDefaultArg =
1741 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
1742 TTP->getDefaultArgumentLoc(), TTP->getDeclName());
1743 if (InstantiatedDefaultArg)
1744 NewTTP->setDefaultArgument(InstantiatedDefaultArg);
1745 }
Richard Smithb4f96252017-02-21 06:30:38 +00001746 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
1747 NewTTP);
Richard Smith32918772017-02-14 00:25:28 +00001748 return NewTTP;
1749 }
1750
1751 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
1752 return transformTemplateParameterImpl(TTP, Args);
1753
1754 return transformTemplateParameterImpl(
1755 cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
1756 }
1757 template<typename TemplateParmDecl>
1758 TemplateParmDecl *
1759 transformTemplateParameterImpl(TemplateParmDecl *OldParam,
1760 MultiLevelTemplateArgumentList &Args) {
1761 // Ask the template instantiator to do the heavy lifting for us, then adjust
1762 // the index of the parameter once it's done.
1763 auto *NewParam =
1764 cast_or_null<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
1765 assert(NewParam->getDepth() == 0 && "unexpected template param depth");
1766 NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
1767 return NewParam;
1768 }
1769
1770 QualType transformFunctionProtoType(TypeLocBuilder &TLB,
1771 FunctionProtoTypeLoc TL,
1772 SmallVectorImpl<ParmVarDecl*> &Params,
1773 MultiLevelTemplateArgumentList &Args) {
1774 SmallVector<QualType, 4> ParamTypes;
1775 const FunctionProtoType *T = TL.getTypePtr();
1776
1777 // -- The types of the function parameters are those of the constructor.
1778 for (auto *OldParam : TL.getParams()) {
Richard Smithc27b3d72017-02-14 01:49:59 +00001779 ParmVarDecl *NewParam = transformFunctionTypeParam(OldParam, Args);
Richard Smith32918772017-02-14 00:25:28 +00001780 if (!NewParam)
1781 return QualType();
1782 ParamTypes.push_back(NewParam->getType());
1783 Params.push_back(NewParam);
1784 }
1785
1786 // -- The return type is the class template specialization designated by
1787 // the template-name and template arguments corresponding to the
1788 // template parameters obtained from the class template.
1789 //
1790 // We use the injected-class-name type of the primary template instead.
1791 // This has the convenient property that it is different from any type that
1792 // the user can write in a deduction-guide (because they cannot enter the
1793 // context of the template), so implicit deduction guides can never collide
1794 // with explicit ones.
1795 QualType ReturnType = DeducedType;
1796 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
1797
1798 // Resolving a wording defect, we also inherit the variadicness of the
1799 // constructor.
1800 FunctionProtoType::ExtProtoInfo EPI;
1801 EPI.Variadic = T->isVariadic();
1802 EPI.HasTrailingReturn = true;
1803
1804 QualType Result = SemaRef.BuildFunctionType(
1805 ReturnType, ParamTypes, TL.getLocStart(), DeductionGuideName, EPI);
1806 if (Result.isNull())
1807 return QualType();
1808
1809 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
1810 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
1811 NewTL.setLParenLoc(TL.getLParenLoc());
1812 NewTL.setRParenLoc(TL.getRParenLoc());
1813 NewTL.setExceptionSpecRange(SourceRange());
1814 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
1815 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
1816 NewTL.setParam(I, Params[I]);
1817
1818 return Result;
1819 }
1820
1821 ParmVarDecl *
1822 transformFunctionTypeParam(ParmVarDecl *OldParam,
1823 MultiLevelTemplateArgumentList &Args) {
1824 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
Richard Smith479ba8e2017-04-20 01:15:31 +00001825 TypeSourceInfo *NewDI;
1826 if (!Args.getNumLevels())
1827 NewDI = OldDI;
1828 else if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
1829 // Expand out the one and only element in each inner pack.
1830 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
1831 NewDI =
1832 SemaRef.SubstType(PackTL.getPatternLoc(), Args,
1833 OldParam->getLocation(), OldParam->getDeclName());
1834 if (!NewDI) return nullptr;
1835 NewDI =
1836 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
1837 PackTL.getTypePtr()->getNumExpansions());
1838 } else
1839 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
1840 OldParam->getDeclName());
Richard Smith32918772017-02-14 00:25:28 +00001841 if (!NewDI)
1842 return nullptr;
1843
Richard Smithc27b3d72017-02-14 01:49:59 +00001844 // Canonicalize the type. This (for instance) replaces references to
1845 // typedef members of the current instantiations with the definitions of
1846 // those typedefs, avoiding triggering instantiation of the deduced type
1847 // during deduction.
1848 // FIXME: It would be preferable to retain type sugar and source
1849 // information here (and handle this in substitution instead).
1850 NewDI = SemaRef.Context.getTrivialTypeSourceInfo(
1851 SemaRef.Context.getCanonicalType(NewDI->getType()),
1852 OldParam->getLocation());
1853
Richard Smith32918772017-02-14 00:25:28 +00001854 // Resolving a wording defect, we also inherit default arguments from the
1855 // constructor.
1856 ExprResult NewDefArg;
1857 if (OldParam->hasDefaultArg()) {
Richard Smithc27b3d72017-02-14 01:49:59 +00001858 NewDefArg = Args.getNumLevels()
1859 ? SemaRef.SubstExpr(OldParam->getDefaultArg(), Args)
1860 : OldParam->getDefaultArg();
Richard Smith32918772017-02-14 00:25:28 +00001861 if (NewDefArg.isInvalid())
1862 return nullptr;
1863 }
1864
1865 ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
1866 OldParam->getInnerLocStart(),
1867 OldParam->getLocation(),
1868 OldParam->getIdentifier(),
1869 NewDI->getType(),
1870 NewDI,
1871 OldParam->getStorageClass(),
1872 NewDefArg.get());
1873 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
1874 OldParam->getFunctionScopeIndex());
1875 return NewParam;
1876 }
1877
1878 NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams,
1879 bool Explicit, TypeSourceInfo *TInfo,
1880 SourceLocation LocStart, SourceLocation Loc,
1881 SourceLocation LocEnd) {
Richard Smithbc491202017-02-17 20:05:37 +00001882 DeclarationNameInfo Name(DeductionGuideName, Loc);
Richard Smithefa919a2017-02-16 21:29:21 +00001883 ArrayRef<ParmVarDecl *> Params =
1884 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
1885
Richard Smith32918772017-02-14 00:25:28 +00001886 // Build the implicit deduction guide template.
Richard Smithbc491202017-02-17 20:05:37 +00001887 auto *Guide =
1888 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, Explicit,
1889 Name, TInfo->getType(), TInfo, LocEnd);
Richard Smith32918772017-02-14 00:25:28 +00001890 Guide->setImplicit();
Richard Smithefa919a2017-02-16 21:29:21 +00001891 Guide->setParams(Params);
1892
1893 for (auto *Param : Params)
1894 Param->setDeclContext(Guide);
Richard Smith32918772017-02-14 00:25:28 +00001895
1896 auto *GuideTemplate = FunctionTemplateDecl::Create(
1897 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
1898 GuideTemplate->setImplicit();
1899 Guide->setDescribedFunctionTemplate(GuideTemplate);
1900
1901 if (isa<CXXRecordDecl>(DC)) {
1902 Guide->setAccess(AS_public);
1903 GuideTemplate->setAccess(AS_public);
1904 }
1905
1906 DC->addDecl(GuideTemplate);
1907 return GuideTemplate;
1908 }
1909};
1910}
1911
1912void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
1913 SourceLocation Loc) {
1914 DeclContext *DC = Template->getDeclContext();
1915 if (DC->isDependentContext())
1916 return;
1917
1918 ConvertConstructorToDeductionGuideTransform Transform(
1919 *this, cast<ClassTemplateDecl>(Template));
1920 if (!isCompleteType(Loc, Transform.DeducedType))
1921 return;
1922
1923 // Check whether we've already declared deduction guides for this template.
1924 // FIXME: Consider storing a flag on the template to indicate this.
1925 auto Existing = DC->lookup(Transform.DeductionGuideName);
1926 for (auto *D : Existing)
1927 if (D->isImplicit())
1928 return;
1929
1930 // In case we were expanding a pack when we attempted to declare deduction
1931 // guides, turn off pack expansion for everything we're about to do.
1932 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1933 // Create a template instantiation record to track the "instantiation" of
1934 // constructors into deduction guides.
1935 // FIXME: Add a kind for this to give more meaningful diagnostics. But can
1936 // this substitution process actually fail?
1937 InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
1938
1939 // Convert declared constructors into deduction guide templates.
1940 // FIXME: Skip constructors for which deduction must necessarily fail (those
1941 // for which some class template parameter without a default argument never
1942 // appears in a deduced context).
1943 bool AddedAny = false;
Richard Smith32918772017-02-14 00:25:28 +00001944 for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
1945 D = D->getUnderlyingDecl();
1946 if (D->isInvalidDecl() || D->isImplicit())
1947 continue;
1948 D = cast<NamedDecl>(D->getCanonicalDecl());
1949
1950 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
Richard Smithbc491202017-02-17 20:05:37 +00001951 auto *CD =
1952 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
Richard Smith32918772017-02-14 00:25:28 +00001953 // Class-scope explicit specializations (MS extension) do not result in
1954 // deduction guides.
Richard Smithbc491202017-02-17 20:05:37 +00001955 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
Richard Smith32918772017-02-14 00:25:28 +00001956 continue;
1957
Richard Smithbc491202017-02-17 20:05:37 +00001958 Transform.transformConstructor(FTD, CD);
Richard Smith32918772017-02-14 00:25:28 +00001959 AddedAny = true;
Richard Smith32918772017-02-14 00:25:28 +00001960 }
1961
Faisal Vali81b756e2017-10-22 14:45:08 +00001962 // C++17 [over.match.class.deduct]
1963 // -- If C is not defined or does not declare any constructors, an
1964 // additional function template derived as above from a hypothetical
1965 // constructor C().
Richard Smith32918772017-02-14 00:25:28 +00001966 if (!AddedAny)
1967 Transform.buildSimpleDeductionGuide(None);
1968
Faisal Vali81b756e2017-10-22 14:45:08 +00001969 // -- An additional function template derived as above from a hypothetical
1970 // constructor C(C), called the copy deduction candidate.
1971 cast<CXXDeductionGuideDecl>(
1972 cast<FunctionTemplateDecl>(
1973 Transform.buildSimpleDeductionGuide(Transform.DeducedType))
1974 ->getTemplatedDecl())
1975 ->setIsCopyDeductionCandidate();
Richard Smith32918772017-02-14 00:25:28 +00001976}
1977
Douglas Gregored5731f2009-11-25 17:50:39 +00001978/// \brief Diagnose the presence of a default template argument on a
1979/// template parameter, which is ill-formed in certain contexts.
1980///
1981/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001982static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00001983 Sema::TemplateParamListContext TPC,
1984 SourceLocation ParamLoc,
1985 SourceRange DefArgRange) {
1986 switch (TPC) {
1987 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00001988 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00001989 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001990 return false;
1991
1992 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001993 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001994 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00001995 // A default template-argument shall not be specified in a
1996 // function template declaration or a function template
1997 // definition [...]
Simon Pilgrim6905d222016-12-30 22:55:33 +00001998 // If a friend function template declaration specifies a default
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001999 // template-argument, that declaration shall be a definition and shall be
2000 // the only declaration of the function template in the translation unit.
2001 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002002 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002003 diag::warn_cxx98_compat_template_parameter_default_in_function_template
2004 : diag::ext_template_parameter_default_in_function_template)
2005 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00002006 return false;
2007
2008 case Sema::TPC_ClassTemplateMember:
2009 // C++0x [temp.param]p9:
2010 // A default template-argument shall not be specified in the
2011 // template-parameter-lists of the definition of a member of a
2012 // class template that appears outside of the member's class.
2013 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2014 << DefArgRange;
2015 return true;
2016
David Majnemerba8f17a2013-06-25 22:08:55 +00002017 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00002018 case Sema::TPC_FriendFunctionTemplate:
2019 // C++ [temp.param]p9:
2020 // A default template-argument shall not be specified in a
2021 // friend template declaration.
2022 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2023 << DefArgRange;
2024 return true;
2025
2026 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2027 // for friend function templates if there is only a single
2028 // declaration (and it is a definition). Strange!
2029 }
2030
David Blaikie8a40f702012-01-17 06:56:22 +00002031 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00002032}
2033
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002034/// \brief Check for unexpanded parameter packs within the template parameters
2035/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00002036static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2037 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00002038 // A template template parameter which is a parameter pack is also a pack
2039 // expansion.
2040 if (TTP->isParameterPack())
2041 return false;
2042
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002043 TemplateParameterList *Params = TTP->getTemplateParameters();
2044 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2045 NamedDecl *P = Params->getParam(I);
2046 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00002047 if (!NTTP->isParameterPack() &&
2048 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002049 NTTP->getTypeSourceInfo(),
2050 Sema::UPPC_NonTypeTemplateParameterType))
2051 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002052
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002053 continue;
2054 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002055
2056 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002057 = dyn_cast<TemplateTemplateParmDecl>(P))
2058 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2059 return true;
2060 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002061
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002062 return false;
2063}
2064
Douglas Gregordba32632009-02-10 19:49:53 +00002065/// \brief Checks the validity of a template parameter list, possibly
2066/// considering the template parameter list from a previous
2067/// declaration.
2068///
2069/// If an "old" template parameter list is provided, it must be
2070/// equivalent (per TemplateParameterListsAreEqual) to the "new"
2071/// template parameter list.
2072///
2073/// \param NewParams Template parameter list for a new template
2074/// declaration. This template parameter list will be updated with any
2075/// default arguments that are carried through from the previous
2076/// template parameter list.
2077///
2078/// \param OldParams If provided, template parameter list from a
2079/// previous declaration of the same template. Default template
2080/// arguments will be merged from the old template parameter list to
2081/// the new template parameter list.
2082///
Douglas Gregored5731f2009-11-25 17:50:39 +00002083/// \param TPC Describes the context in which we are checking the given
2084/// template parameter list.
2085///
Douglas Gregordba32632009-02-10 19:49:53 +00002086/// \returns true if an error occurred, false otherwise.
2087bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00002088 TemplateParameterList *OldParams,
2089 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00002090 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00002091
Douglas Gregordba32632009-02-10 19:49:53 +00002092 // C++ [temp.param]p10:
2093 // The set of default template-arguments available for use with a
2094 // template declaration or definition is obtained by merging the
2095 // default arguments from the definition (if in scope) and all
2096 // declarations in scope in the same way default function
2097 // arguments are (8.3.6).
2098 bool SawDefaultArgument = false;
2099 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00002100
Mike Stumpc89c8e32009-02-11 23:03:27 +00002101 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00002102 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00002103 if (OldParams)
2104 OldParam = OldParams->begin();
2105
Douglas Gregor0693def2011-01-27 01:40:17 +00002106 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00002107 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2108 NewParamEnd = NewParams->end();
2109 NewParam != NewParamEnd; ++NewParam) {
2110 // Variables used to diagnose redundant default arguments
2111 bool RedundantDefaultArg = false;
2112 SourceLocation OldDefaultLoc;
2113 SourceLocation NewDefaultLoc;
2114
David Blaikie651c73c2011-10-19 05:19:50 +00002115 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00002116 bool MissingDefaultArg = false;
2117
David Blaikie651c73c2011-10-19 05:19:50 +00002118 // Variable used to diagnose non-final parameter packs
2119 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00002120
Douglas Gregordba32632009-02-10 19:49:53 +00002121 if (TemplateTypeParmDecl *NewTypeParm
2122 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00002123 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002124 if (NewTypeParm->hasDefaultArgument() &&
2125 DiagnoseDefaultTemplateArgument(*this, TPC,
2126 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002127 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002128 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00002129 NewTypeParm->removeDefaultArgument();
2130
2131 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00002132 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002133 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Anders Carlsson327865d2009-06-12 23:20:15 +00002134 if (NewTypeParm->isParameterPack()) {
2135 assert(!NewTypeParm->hasDefaultArgument() &&
2136 "Parameter packs can't have a default argument!");
2137 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002138 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
John McCall0ad16662009-10-29 08:12:44 +00002139 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00002140 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2141 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2142 SawDefaultArgument = true;
2143 RedundantDefaultArg = true;
2144 PreviousDefaultArgLoc = NewDefaultLoc;
2145 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2146 // Merge the default argument from the old declaration to the
2147 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002148 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00002149 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2150 } else if (NewTypeParm->hasDefaultArgument()) {
2151 SawDefaultArgument = true;
2152 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2153 } else if (SawDefaultArgument)
2154 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00002155 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00002156 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002157 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002158 if (!NewNonTypeParm->isParameterPack() &&
2159 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002160 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002161 UPPC_NonTypeTemplateParameterType)) {
2162 Invalid = true;
2163 continue;
2164 }
2165
Douglas Gregored5731f2009-11-25 17:50:39 +00002166 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002167 if (NewNonTypeParm->hasDefaultArgument() &&
2168 DiagnoseDefaultTemplateArgument(*this, TPC,
2169 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002170 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00002171 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00002172 }
2173
Mike Stump12b8ce12009-08-04 21:02:39 +00002174 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00002175 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002176 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00002177 if (NewNonTypeParm->isParameterPack()) {
2178 assert(!NewNonTypeParm->hasDefaultArgument() &&
2179 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00002180 if (!NewNonTypeParm->isPackExpansion())
2181 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002182 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
Richard Smith35828f12013-07-22 03:31:14 +00002183 NewNonTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00002184 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2185 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2186 SawDefaultArgument = true;
2187 RedundantDefaultArg = true;
2188 PreviousDefaultArgLoc = NewDefaultLoc;
2189 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2190 // Merge the default argument from the old declaration to the
2191 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002192 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00002193 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2194 } else if (NewNonTypeParm->hasDefaultArgument()) {
2195 SawDefaultArgument = true;
2196 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2197 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002198 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00002199 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00002200 TemplateTemplateParmDecl *NewTemplateParm
2201 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002202
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002203 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00002204 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002205 Invalid = true;
2206 continue;
2207 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002208
David Blaikie651c73c2011-10-19 05:19:50 +00002209 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002210 if (NewTemplateParm->hasDefaultArgument() &&
2211 DiagnoseDefaultTemplateArgument(*this, TPC,
2212 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002213 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00002214 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00002215
2216 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00002217 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002218 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00002219 if (NewTemplateParm->isParameterPack()) {
2220 assert(!NewTemplateParm->hasDefaultArgument() &&
2221 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00002222 if (!NewTemplateParm->isPackExpansion())
2223 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002224 } else if (OldTemplateParm &&
2225 hasVisibleDefaultArgument(OldTemplateParm) &&
2226 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002227 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2228 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002229 SawDefaultArgument = true;
2230 RedundantDefaultArg = true;
2231 PreviousDefaultArgLoc = NewDefaultLoc;
2232 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2233 // Merge the default argument from the old declaration to the
2234 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002235 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002236 PreviousDefaultArgLoc
2237 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002238 } else if (NewTemplateParm->hasDefaultArgument()) {
2239 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002240 PreviousDefaultArgLoc
2241 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002242 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002243 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00002244 }
2245
Richard Smith1fde8ec2012-09-07 02:06:42 +00002246 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00002247 // If a template parameter of a primary class template or alias template
2248 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002249 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00002250 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2251 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00002252 Diag((*NewParam)->getLocation(),
2253 diag::err_template_param_pack_must_be_last_template_parameter);
2254 Invalid = true;
2255 }
2256
Douglas Gregordba32632009-02-10 19:49:53 +00002257 if (RedundantDefaultArg) {
2258 // C++ [temp.param]p12:
2259 // A template-parameter shall not be given default arguments
2260 // by two different declarations in the same scope.
2261 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2262 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2263 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00002264 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00002265 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002266 // If a template-parameter of a class template has a default
2267 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00002268 // have a default template-argument supplied or be a template parameter
2269 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00002270 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00002271 diag::err_template_param_default_arg_missing);
2272 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2273 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00002274 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00002275 }
2276
2277 // If we have an old template parameter list that we're merging
2278 // in, move on to the next parameter.
2279 if (OldParams)
2280 ++OldParam;
2281 }
2282
Douglas Gregor0693def2011-01-27 01:40:17 +00002283 // We were missing some default arguments at the end of the list, so remove
2284 // all of the default arguments.
2285 if (RemoveDefaultArguments) {
2286 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2287 NewParamEnd = NewParams->end();
2288 NewParam != NewParamEnd; ++NewParam) {
2289 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2290 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002291 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00002292 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2293 NTTP->removeDefaultArgument();
2294 else
2295 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2296 }
2297 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002298
Douglas Gregordba32632009-02-10 19:49:53 +00002299 return Invalid;
2300}
Douglas Gregord32e0282009-02-09 23:23:08 +00002301
John McCalla020a012010-10-20 05:44:58 +00002302namespace {
2303
2304/// A class which looks for a use of a certain level of template
2305/// parameter.
2306struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2307 typedef RecursiveASTVisitor<DependencyChecker> super;
2308
2309 unsigned Depth;
Richard Smith57aae072016-12-28 02:37:25 +00002310
2311 // Whether we're looking for a use of a template parameter that makes the
2312 // overall construct type-dependent / a dependent type. This is strictly
2313 // best-effort for now; we may fail to match at all for a dependent type
2314 // in some cases if this is set.
2315 bool IgnoreNonTypeDependent;
2316
John McCalla020a012010-10-20 05:44:58 +00002317 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00002318 SourceLocation MatchLoc;
2319
Richard Smith13894182017-04-13 21:37:24 +00002320 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2321 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2322 Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00002323
Richard Smith57aae072016-12-28 02:37:25 +00002324 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
Richard Smith13894182017-04-13 21:37:24 +00002325 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2326 NamedDecl *ND = Params->getParam(0);
2327 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2328 Depth = PD->getDepth();
2329 } else if (NonTypeTemplateParmDecl *PD =
2330 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2331 Depth = PD->getDepth();
2332 } else {
2333 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2334 }
2335 }
John McCalla020a012010-10-20 05:44:58 +00002336
Richard Smith6056d5e2014-02-09 00:54:43 +00002337 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
Richard Smith13894182017-04-13 21:37:24 +00002338 if (ParmDepth >= Depth) {
John McCalla020a012010-10-20 05:44:58 +00002339 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00002340 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00002341 return true;
2342 }
2343 return false;
2344 }
2345
Richard Smith57aae072016-12-28 02:37:25 +00002346 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2347 // Prune out non-type-dependent expressions if requested. This can
2348 // sometimes result in us failing to find a template parameter reference
2349 // (if a value-dependent expression creates a dependent type), but this
2350 // mode is best-effort only.
2351 if (auto *E = dyn_cast_or_null<Expr>(S))
2352 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2353 return true;
2354 return super::TraverseStmt(S, Q);
2355 }
2356
2357 bool TraverseTypeLoc(TypeLoc TL) {
2358 if (IgnoreNonTypeDependent && !TL.isNull() &&
2359 !TL.getType()->isDependentType())
2360 return true;
2361 return super::TraverseTypeLoc(TL);
2362 }
2363
Richard Smith6056d5e2014-02-09 00:54:43 +00002364 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2365 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2366 }
2367
John McCalla020a012010-10-20 05:44:58 +00002368 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
Richard Smith57aae072016-12-28 02:37:25 +00002369 // For a best-effort search, keep looking until we find a location.
2370 return IgnoreNonTypeDependent || !Matches(T->getDepth());
John McCalla020a012010-10-20 05:44:58 +00002371 }
2372
2373 bool TraverseTemplateName(TemplateName N) {
2374 if (TemplateTemplateParmDecl *PD =
2375 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00002376 if (Matches(PD->getDepth()))
2377 return false;
John McCalla020a012010-10-20 05:44:58 +00002378 return super::TraverseTemplateName(N);
2379 }
2380
2381 bool VisitDeclRefExpr(DeclRefExpr *E) {
2382 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00002383 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2384 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00002385 return false;
John McCalla020a012010-10-20 05:44:58 +00002386 return super::VisitDeclRefExpr(E);
2387 }
Richard Smith6056d5e2014-02-09 00:54:43 +00002388
2389 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2390 return TraverseType(T->getReplacementType());
2391 }
2392
2393 bool
2394 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2395 return TraverseTemplateArgument(T->getArgumentPack());
2396 }
2397
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00002398 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2399 return TraverseType(T->getInjectedSpecializationType());
2400 }
John McCalla020a012010-10-20 05:44:58 +00002401};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002402} // end anonymous namespace
John McCalla020a012010-10-20 05:44:58 +00002403
Douglas Gregor972fe532011-05-10 18:27:06 +00002404/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00002405/// list.
2406static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00002407DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
Richard Smith57aae072016-12-28 02:37:25 +00002408 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
Douglas Gregor972fe532011-05-10 18:27:06 +00002409 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00002410 return Checker.Match;
2411}
2412
Douglas Gregor972fe532011-05-10 18:27:06 +00002413// Find the source range corresponding to the named type in the given
2414// nested-name-specifier, if any.
2415static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2416 QualType T,
2417 const CXXScopeSpec &SS) {
2418 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2419 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2420 if (const Type *CurType = NNS->getAsType()) {
2421 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2422 return NNSLoc.getTypeLoc().getSourceRange();
2423 } else
2424 break;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002425
Douglas Gregor972fe532011-05-10 18:27:06 +00002426 NNSLoc = NNSLoc.getPrefix();
2427 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002428
Douglas Gregor972fe532011-05-10 18:27:06 +00002429 return SourceRange();
2430}
2431
Mike Stump11289f42009-09-09 15:08:12 +00002432/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00002433/// specifier, returning the template parameter list that applies to the
2434/// name.
2435///
2436/// \param DeclStartLoc the start of the declaration that has a scope
2437/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00002438///
Douglas Gregor972fe532011-05-10 18:27:06 +00002439/// \param DeclLoc The location of the declaration itself.
2440///
Douglas Gregord8d297c2009-07-21 23:53:31 +00002441/// \param SS the scope specifier that will be matched to the given template
2442/// parameter lists. This scope specifier precedes a qualified name that is
2443/// being declared.
2444///
Richard Smith4b55a9c2014-04-17 03:29:33 +00002445/// \param TemplateId The template-id following the scope specifier, if there
2446/// is one. Used to check for a missing 'template<>'.
2447///
Douglas Gregord8d297c2009-07-21 23:53:31 +00002448/// \param ParamLists the template parameter lists, from the outermost to the
2449/// innermost template parameter lists.
2450///
John McCalle820e5e2010-04-13 20:37:33 +00002451/// \param IsFriend Whether to apply the slightly different rules for
2452/// matching template parameters to scope specifiers in friend
2453/// declarations.
2454///
Richard Smithf445f192017-02-09 21:04:43 +00002455/// \param IsMemberSpecialization will be set true if the scope specifier
2456/// denotes a fully-specialized type, and therefore this is a declaration of
2457/// a member specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002458///
Mike Stump11289f42009-09-09 15:08:12 +00002459/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00002460/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00002461/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00002462/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00002463/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00002464/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002465TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2466 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00002467 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002468 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
Richard Smithf445f192017-02-09 21:04:43 +00002469 bool &IsMemberSpecialization, bool &Invalid) {
2470 IsMemberSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00002471 Invalid = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002472
Douglas Gregor972fe532011-05-10 18:27:06 +00002473 // The sequence of nested types to which we will match up the template
2474 // parameter lists. We first build this list by starting with the type named
2475 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002476 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00002477 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00002478 if (SS.getScopeRep()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002479 if (CXXRecordDecl *Record
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00002480 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2481 T = Context.getTypeDeclType(Record);
2482 else
2483 T = QualType(SS.getScopeRep()->getAsType(), 0);
2484 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002485
Douglas Gregor972fe532011-05-10 18:27:06 +00002486 // If we found an explicit specialization that prevents us from needing
2487 // 'template<>' headers, this will be set to the location of that
2488 // explicit specialization.
2489 SourceLocation ExplicitSpecLoc;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002490
Douglas Gregor972fe532011-05-10 18:27:06 +00002491 while (!T.isNull()) {
2492 NestedTypes.push_back(T);
Simon Pilgrim6905d222016-12-30 22:55:33 +00002493
Douglas Gregor972fe532011-05-10 18:27:06 +00002494 // Retrieve the parent of a record type.
2495 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2496 // If this type is an explicit specialization, we're done.
2497 if (ClassTemplateSpecializationDecl *Spec
2498 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002499 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002500 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2501 ExplicitSpecLoc = Spec->getLocation();
2502 break;
Douglas Gregor65911492009-11-23 12:11:45 +00002503 }
Douglas Gregor972fe532011-05-10 18:27:06 +00002504 } else if (Record->getTemplateSpecializationKind()
2505 == TSK_ExplicitSpecialization) {
2506 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00002507 break;
2508 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002509
Douglas Gregor972fe532011-05-10 18:27:06 +00002510 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2511 T = Context.getTypeDeclType(Parent);
2512 else
2513 T = QualType();
2514 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002515 }
2516
Douglas Gregor972fe532011-05-10 18:27:06 +00002517 if (const TemplateSpecializationType *TST
2518 = T->getAs<TemplateSpecializationType>()) {
2519 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2520 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2521 T = Context.getTypeDeclType(Parent);
2522 else
2523 T = QualType();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002524 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002525 }
Douglas Gregor972fe532011-05-10 18:27:06 +00002526 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002527
Douglas Gregor972fe532011-05-10 18:27:06 +00002528 // Look one step prior in a dependent template specialization type.
2529 if (const DependentTemplateSpecializationType *DependentTST
2530 = T->getAs<DependentTemplateSpecializationType>()) {
2531 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2532 T = QualType(NNS->getAsType(), 0);
2533 else
2534 T = QualType();
2535 continue;
2536 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002537
Douglas Gregor972fe532011-05-10 18:27:06 +00002538 // Look one step prior in a dependent name type.
2539 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2540 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2541 T = QualType(NNS->getAsType(), 0);
2542 else
2543 T = QualType();
2544 continue;
2545 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002546
Douglas Gregor972fe532011-05-10 18:27:06 +00002547 // Retrieve the parent of an enumeration type.
2548 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2549 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2550 // check here.
2551 EnumDecl *Enum = EnumT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002552
Douglas Gregor972fe532011-05-10 18:27:06 +00002553 // Get to the parent type.
2554 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2555 T = Context.getTypeDeclType(Parent);
2556 else
Simon Pilgrim6905d222016-12-30 22:55:33 +00002557 T = QualType();
Douglas Gregor972fe532011-05-10 18:27:06 +00002558 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002559 }
Mike Stump11289f42009-09-09 15:08:12 +00002560
Douglas Gregor972fe532011-05-10 18:27:06 +00002561 T = QualType();
2562 }
2563 // Reverse the nested types list, since we want to traverse from the outermost
2564 // to the innermost while checking template-parameter-lists.
2565 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00002566
Douglas Gregor972fe532011-05-10 18:27:06 +00002567 // C++0x [temp.expl.spec]p17:
2568 // A member or a member template may be nested within many
2569 // enclosing class templates. In an explicit specialization for
2570 // such a member, the member declaration shall be preceded by a
2571 // template<> for each enclosing class template that is
2572 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002573 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00002574
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002575 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00002576 if (SawNonEmptyTemplateParameterList) {
2577 Diag(DeclLoc, diag::err_specialize_member_of_template)
2578 << !Recovery << Range;
2579 Invalid = true;
Richard Smithf445f192017-02-09 21:04:43 +00002580 IsMemberSpecialization = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00002581 return true;
2582 }
2583
2584 return false;
2585 };
2586
2587 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2588 // Check that we can have an explicit specialization here.
2589 if (CheckExplicitSpecialization(Range, true))
2590 return true;
2591
2592 // We don't have a template header, but we should.
2593 SourceLocation ExpectedTemplateLoc;
2594 if (!ParamLists.empty())
2595 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2596 else
2597 ExpectedTemplateLoc = DeclStartLoc;
2598
2599 Diag(DeclLoc, diag::err_template_spec_needs_header)
2600 << Range
2601 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2602 return false;
2603 };
2604
Douglas Gregor972fe532011-05-10 18:27:06 +00002605 unsigned ParamIdx = 0;
2606 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2607 ++TypeIdx) {
2608 T = NestedTypes[TypeIdx];
Simon Pilgrim6905d222016-12-30 22:55:33 +00002609
Douglas Gregor972fe532011-05-10 18:27:06 +00002610 // Whether we expect a 'template<>' header.
2611 bool NeedEmptyTemplateHeader = false;
2612
2613 // Whether we expect a template header with parameters.
2614 bool NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002615
Douglas Gregor972fe532011-05-10 18:27:06 +00002616 // For a dependent type, the set of template parameters that we
2617 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00002618 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002619
Douglas Gregor373af9b2011-05-11 23:26:17 +00002620 // C++0x [temp.expl.spec]p15:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002621 // A member or a member template may be nested within many enclosing
2622 // class templates. In an explicit specialization for such a member, the
2623 // member declaration shall be preceded by a template<> for each
Douglas Gregor373af9b2011-05-11 23:26:17 +00002624 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00002625 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2626 if (ClassTemplatePartialSpecializationDecl *Partial
2627 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2628 ExpectedTemplateParams = Partial->getTemplateParameters();
2629 NeedNonemptyTemplateHeader = true;
2630 } else if (Record->isDependentType()) {
2631 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00002632 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00002633 ->getTemplateParameters();
2634 NeedNonemptyTemplateHeader = true;
2635 }
2636 } else if (ClassTemplateSpecializationDecl *Spec
2637 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2638 // C++0x [temp.expl.spec]p4:
2639 // Members of an explicitly specialized class template are defined
Simon Pilgrim6905d222016-12-30 22:55:33 +00002640 // in the same manner as members of normal classes, and not using
2641 // the template<> syntax.
Douglas Gregor972fe532011-05-10 18:27:06 +00002642 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2643 NeedEmptyTemplateHeader = true;
2644 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00002645 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002646 } else if (Record->getTemplateSpecializationKind()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002647 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00002648 != TSK_ExplicitSpecialization &&
2649 TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002650 IsMemberSpecialization = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002651
Douglas Gregor373af9b2011-05-11 23:26:17 +00002652 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002653 }
2654 } else if (const TemplateSpecializationType *TST
2655 = T->getAs<TemplateSpecializationType>()) {
Nico Weber28900612015-01-30 02:35:21 +00002656 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002657 ExpectedTemplateParams = Template->getTemplateParameters();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002658 NeedNonemptyTemplateHeader = true;
Douglas Gregor972fe532011-05-10 18:27:06 +00002659 }
2660 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2661 // FIXME: We actually could/should check the template arguments here
2662 // against the corresponding template parameter list.
2663 NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002664 }
2665
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002666 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002667 // In an explicit specialization declaration for a member of a class
2668 // template or a member template that ap- pears in namespace scope, the
2669 // member template and some of its enclosing class templates may remain
2670 // unspecialized, except that the declaration shall not explicitly
2671 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002672 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002673 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002674 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002675 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2676 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002677 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002678 } else
2679 SawNonEmptyTemplateParameterList = true;
2680 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002681
Douglas Gregor972fe532011-05-10 18:27:06 +00002682 if (NeedEmptyTemplateHeader) {
2683 // If we're on the last of the types, and we need a 'template<>' header
Richard Smithf445f192017-02-09 21:04:43 +00002684 // here, then it's a member specialization.
Douglas Gregor972fe532011-05-10 18:27:06 +00002685 if (TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002686 IsMemberSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002687
2688 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002689 if (ParamLists[ParamIdx]->size() > 0) {
2690 // The header has template parameters when it shouldn't. Complain.
Simon Pilgrim6905d222016-12-30 22:55:33 +00002691 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregor972fe532011-05-10 18:27:06 +00002692 diag::err_template_param_list_matches_nontemplate)
2693 << T
2694 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2695 ParamLists[ParamIdx]->getRAngleLoc())
2696 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2697 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002698 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002699 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002700
Douglas Gregor972fe532011-05-10 18:27:06 +00002701 // Consume this template header.
2702 ++ParamIdx;
2703 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002704 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002705
2706 if (!IsFriend)
2707 if (DiagnoseMissingExplicitSpecialization(
2708 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00002709 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002710
Douglas Gregor972fe532011-05-10 18:27:06 +00002711 continue;
2712 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002713
Douglas Gregor972fe532011-05-10 18:27:06 +00002714 if (NeedNonemptyTemplateHeader) {
2715 // In friend declarations we can have template-ids which don't
2716 // depend on the corresponding template parameter lists. But
2717 // assume that empty parameter lists are supposed to match this
2718 // template-id.
2719 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002720 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002721 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00002722 ExpectedTemplateParams = nullptr;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002723 else
Douglas Gregor972fe532011-05-10 18:27:06 +00002724 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002725 }
Douglas Gregored5731f2009-11-25 17:50:39 +00002726
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002727 if (ParamIdx < ParamLists.size()) {
2728 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00002729 if (ExpectedTemplateParams &&
2730 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2731 ExpectedTemplateParams,
2732 true, TPL_TemplateMatch))
2733 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002734
Douglas Gregor972fe532011-05-10 18:27:06 +00002735 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00002736 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00002737 TPC_ClassTemplateMember))
2738 Invalid = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002739
Douglas Gregor972fe532011-05-10 18:27:06 +00002740 ++ParamIdx;
2741 continue;
2742 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002743
Douglas Gregor972fe532011-05-10 18:27:06 +00002744 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2745 << T
2746 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2747 Invalid = true;
2748 continue;
2749 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00002750 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00002751
Douglas Gregord8d297c2009-07-21 23:53:31 +00002752 // If there were at least as many template-ids as there were template
2753 // parameter lists, then there are no template parameter lists remaining for
2754 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00002755 if (ParamIdx >= ParamLists.size()) {
2756 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00002757 // We don't have a template header for the declaration itself, but we
2758 // should.
Richard Smith11a80dc2014-04-17 03:52:20 +00002759 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2760 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00002761
2762 // Fabricate an empty template parameter list for the invented header.
2763 return TemplateParameterList::Create(Context, SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +00002764 SourceLocation(), None,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00002765 SourceLocation(), nullptr);
Richard Smith4b55a9c2014-04-17 03:29:33 +00002766 }
2767
Craig Topperc3ec1492014-05-26 06:22:03 +00002768 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002769 }
Mike Stump11289f42009-09-09 15:08:12 +00002770
Douglas Gregord8d297c2009-07-21 23:53:31 +00002771 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002772 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002773 bool HasAnyExplicitSpecHeader = false;
2774 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002775 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002776 if (ParamLists[I]->size() == 0)
2777 HasAnyExplicitSpecHeader = true;
2778 else
2779 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002780 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002781
Douglas Gregor972fe532011-05-10 18:27:06 +00002782 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002783 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2784 : diag::err_template_spec_extra_headers)
2785 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2786 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00002787
2788 // If there was a specialization somewhere, such that 'template<>' is
2789 // not required, and there were any 'template<>' headers, note where the
2790 // specialization occurred.
2791 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
Simon Pilgrim6905d222016-12-30 22:55:33 +00002792 Diag(ExplicitSpecLoc,
Douglas Gregor972fe532011-05-10 18:27:06 +00002793 diag::note_explicit_template_spec_does_not_need_header)
2794 << NestedTypes.back();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002795
Douglas Gregor972fe532011-05-10 18:27:06 +00002796 // We have a template parameter list with no corresponding scope, which
2797 // means that the resulting template declaration can't be instantiated
2798 // properly (we'll end up with dependent nodes when we shouldn't).
2799 if (!AllExplicitSpecHeaders)
2800 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002801 }
Mike Stump11289f42009-09-09 15:08:12 +00002802
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002803 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002804 // In an explicit specialization declaration for a member of a class
2805 // template or a member template that ap- pears in namespace scope, the
2806 // member template and some of its enclosing class templates may remain
2807 // unspecialized, except that the declaration shall not explicitly
2808 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002809 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00002810 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002811 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2812 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002813 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002814
Douglas Gregord8d297c2009-07-21 23:53:31 +00002815 // Return the last template parameter list, which corresponds to the
2816 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002817 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00002818}
2819
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002820void Sema::NoteAllFoundTemplates(TemplateName Name) {
2821 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2822 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002823 << (isa<FunctionTemplateDecl>(Template)
2824 ? 0
2825 : isa<ClassTemplateDecl>(Template)
2826 ? 1
2827 : isa<VarTemplateDecl>(Template)
2828 ? 2
2829 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2830 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002831 return;
2832 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002833
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002834 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002835 for (OverloadedTemplateStorage::iterator I = OST->begin(),
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002836 IEnd = OST->end();
2837 I != IEnd; ++I)
2838 Diag((*I)->getLocation(), diag::note_template_declared_here)
2839 << 0 << (*I)->getDeclName();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002840
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002841 return;
2842 }
2843}
2844
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002845static QualType
2846checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2847 const SmallVectorImpl<TemplateArgument> &Converted,
2848 SourceLocation TemplateLoc,
2849 TemplateArgumentListInfo &TemplateArgs) {
2850 ASTContext &Context = SemaRef.getASTContext();
2851 switch (BTD->getBuiltinTemplateKind()) {
Eric Fiselier6ad68552016-07-01 01:24:09 +00002852 case BTK__make_integer_seq: {
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002853 // Specializations of __make_integer_seq<S, T, N> are treated like
2854 // S<T, 0, ..., N-1>.
2855
2856 // C++14 [inteseq.intseq]p1:
2857 // T shall be an integer type.
2858 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2859 SemaRef.Diag(TemplateArgs[1].getLocation(),
2860 diag::err_integer_sequence_integral_element_type);
2861 return QualType();
2862 }
2863
2864 // C++14 [inteseq.make]p1:
2865 // If N is negative the program is ill-formed.
2866 TemplateArgument NumArgsArg = Converted[2];
2867 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2868 if (NumArgs < 0) {
2869 SemaRef.Diag(TemplateArgs[2].getLocation(),
2870 diag::err_integer_sequence_negative_length);
2871 return QualType();
2872 }
2873
2874 QualType ArgTy = NumArgsArg.getIntegralType();
2875 TemplateArgumentListInfo SyntheticTemplateArgs;
2876 // The type argument gets reused as the first template argument in the
2877 // synthetic template argument list.
2878 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2879 // Expand N into 0 ... N-1.
2880 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2881 I < NumArgs; ++I) {
2882 TemplateArgument TA(Context, I, ArgTy);
Richard Smith7873de02016-08-11 22:25:46 +00002883 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
2884 TA, ArgTy, TemplateArgs[2].getLocation()));
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002885 }
2886 // The first template argument will be reused as the template decl that
2887 // our synthetic template arguments will be applied to.
2888 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2889 TemplateLoc, SyntheticTemplateArgs);
2890 }
Eric Fiselier6ad68552016-07-01 01:24:09 +00002891
2892 case BTK__type_pack_element:
2893 // Specializations of
2894 // __type_pack_element<Index, T_1, ..., T_N>
2895 // are treated like T_Index.
2896 assert(Converted.size() == 2 &&
2897 "__type_pack_element should be given an index and a parameter pack");
2898
2899 // If the Index is out of bounds, the program is ill-formed.
2900 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
2901 llvm::APSInt Index = IndexArg.getAsIntegral();
2902 assert(Index >= 0 && "the index used with __type_pack_element should be of "
2903 "type std::size_t, and hence be non-negative");
2904 if (Index >= Ts.pack_size()) {
2905 SemaRef.Diag(TemplateArgs[0].getLocation(),
2906 diag::err_type_pack_element_out_of_bounds);
2907 return QualType();
2908 }
2909
2910 // We simply return the type at index `Index`.
2911 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
2912 return Nth->getAsType();
2913 }
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002914 llvm_unreachable("unexpected BuiltinTemplateDecl!");
2915}
2916
Douglas Gregor00fa10b2017-07-05 20:20:14 +00002917/// Determine whether this alias template is "enable_if_t".
2918static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
2919 return AliasTemplate->getName().equals("enable_if_t");
2920}
2921
2922/// Collect all of the separable terms in the given condition, which
2923/// might be a conjunction.
2924///
2925/// FIXME: The right answer is to convert the logical expression into
2926/// disjunctive normal form, so we can find the first failed term
2927/// within each possible clause.
2928static void collectConjunctionTerms(Expr *Clause,
2929 SmallVectorImpl<Expr *> &Terms) {
2930 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
2931 if (BinOp->getOpcode() == BO_LAnd) {
2932 collectConjunctionTerms(BinOp->getLHS(), Terms);
2933 collectConjunctionTerms(BinOp->getRHS(), Terms);
2934 }
2935
2936 return;
2937 }
2938
2939 Terms.push_back(Clause);
2940}
2941
Douglas Gregorbb33f572017-07-05 20:20:15 +00002942// The ranges-v3 library uses an odd pattern of a top-level "||" with
2943// a left-hand side that is value-dependent but never true. Identify
2944// the idiom and ignore that term.
2945static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
2946 // Top-level '||'.
2947 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
2948 if (!BinOp) return Cond;
2949
2950 if (BinOp->getOpcode() != BO_LOr) return Cond;
2951
2952 // With an inner '==' that has a literal on the right-hand side.
2953 Expr *LHS = BinOp->getLHS();
Douglas Gregorc0fe1f22017-07-05 21:12:37 +00002954 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
Douglas Gregorbb33f572017-07-05 20:20:15 +00002955 if (!InnerBinOp) return Cond;
2956
2957 if (InnerBinOp->getOpcode() != BO_EQ ||
2958 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
2959 return Cond;
2960
2961 // If the inner binary operation came from a macro expansion named
2962 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
2963 // of the '||', which is the real, user-provided condition.
Douglas Gregorc0fe1f22017-07-05 21:12:37 +00002964 SourceLocation Loc = InnerBinOp->getExprLoc();
Douglas Gregorbb33f572017-07-05 20:20:15 +00002965 if (!Loc.isMacroID()) return Cond;
2966
2967 StringRef MacroName = PP.getImmediateMacroName(Loc);
2968 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
2969 return BinOp->getRHS();
2970
2971 return Cond;
2972}
2973
Douglas Gregor672281a2017-09-14 23:38:42 +00002974std::pair<Expr *, std::string>
2975Sema::findFailedBooleanCondition(Expr *Cond, bool AllowTopLevelCond) {
2976 Cond = lookThroughRangesV3Condition(PP, Cond);
Douglas Gregorbb33f572017-07-05 20:20:15 +00002977
Douglas Gregor00fa10b2017-07-05 20:20:14 +00002978 // Separate out all of the terms in a conjunction.
2979 SmallVector<Expr *, 4> Terms;
2980 collectConjunctionTerms(Cond, Terms);
2981
2982 // Determine which term failed.
2983 Expr *FailedCond = nullptr;
2984 for (Expr *Term : Terms) {
Douglas Gregor672281a2017-09-14 23:38:42 +00002985 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
2986
2987 // Literals are uninteresting.
2988 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
2989 isa<IntegerLiteral>(TermAsWritten))
2990 continue;
2991
Douglas Gregor00fa10b2017-07-05 20:20:14 +00002992 // The initialization of the parameter from the argument is
2993 // a constant-evaluated context.
2994 EnterExpressionEvaluationContext ConstantEvaluated(
Douglas Gregor672281a2017-09-14 23:38:42 +00002995 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Douglas Gregor00fa10b2017-07-05 20:20:14 +00002996
2997 bool Succeeded;
Douglas Gregor672281a2017-09-14 23:38:42 +00002998 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
Douglas Gregor00fa10b2017-07-05 20:20:14 +00002999 !Succeeded) {
Douglas Gregor672281a2017-09-14 23:38:42 +00003000 FailedCond = TermAsWritten;
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003001 break;
3002 }
3003 }
3004
Douglas Gregor672281a2017-09-14 23:38:42 +00003005 if (!FailedCond) {
3006 if (!AllowTopLevelCond)
3007 return { nullptr, "" };
3008
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003009 FailedCond = Cond->IgnoreParenImpCasts();
Douglas Gregor672281a2017-09-14 23:38:42 +00003010 }
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003011
3012 std::string Description;
3013 {
3014 llvm::raw_string_ostream Out(Description);
Douglas Gregor672281a2017-09-14 23:38:42 +00003015 FailedCond->printPretty(Out, nullptr, getPrintingPolicy());
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003016 }
3017 return { FailedCond, Description };
3018}
3019
Douglas Gregordc572a32009-03-30 22:58:21 +00003020QualType Sema::CheckTemplateIdType(TemplateName Name,
3021 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003022 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00003023 DependentTemplateName *DTN
3024 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00003025 if (DTN && DTN->isIdentifier())
3026 // When building a template-id where the template-name is dependent,
3027 // assume the template is a type template. Either our assumption is
3028 // correct, or the code is ill-formed and will be diagnosed when the
3029 // dependent name is substituted.
3030 return Context.getDependentTemplateSpecializationType(ETK_None,
3031 DTN->getQualifier(),
3032 DTN->getIdentifier(),
3033 TemplateArgs);
3034
Douglas Gregordc572a32009-03-30 22:58:21 +00003035 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00003036 if (!Template || isa<FunctionTemplateDecl>(Template) ||
Faisal Valia534f072018-04-26 00:42:40 +00003037 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00003038 // We might have a substituted template template parameter pack. If so,
3039 // build a template specialization type for it.
3040 if (Name.getAsSubstTemplateTemplateParmPack())
3041 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003042
Douglas Gregor8b6070b2011-03-04 21:37:14 +00003043 Diag(TemplateLoc, diag::err_template_id_not_a_type)
3044 << Name;
3045 NoteAllFoundTemplates(Name);
3046 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00003047 }
Douglas Gregordc572a32009-03-30 22:58:21 +00003048
Douglas Gregorc40290e2009-03-09 23:48:35 +00003049 // Check that the template argument list is well-formed for this
3050 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003051 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00003052 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00003053 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00003054 return QualType();
3055
Douglas Gregorc40290e2009-03-09 23:48:35 +00003056 QualType CanonType;
3057
Douglas Gregor678d76c2011-07-01 01:22:09 +00003058 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00003059 if (TypeAliasTemplateDecl *AliasTemplate =
3060 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00003061 // Find the canonical type for this type alias template specialization.
3062 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3063 if (Pattern->isInvalidDecl())
3064 return QualType();
3065
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003066 TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack,
3067 Converted);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003068
3069 // Only substitute for the innermost template argument list.
3070 MultiLevelTemplateArgumentList TemplateArgLists;
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003071 TemplateArgLists.addOuterTemplateArguments(&StackTemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00003072 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
3073 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00003074 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003075
Richard Smith802c4b72012-08-23 06:16:52 +00003076 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003077 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003078 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003079 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00003080
Richard Smith3f1b5d02011-05-05 21:57:07 +00003081 CanonType = SubstType(Pattern->getUnderlyingType(),
3082 TemplateArgLists, AliasTemplate->getLocation(),
3083 AliasTemplate->getDeclName());
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003084 if (CanonType.isNull()) {
3085 // If this was enable_if and we failed to find the nested type
3086 // within enable_if in a SFINAE context, dig out the specific
3087 // enable_if condition that failed and present that instead.
3088 if (isEnableIfAliasTemplate(AliasTemplate)) {
3089 if (auto DeductionInfo = isSFINAEContext()) {
3090 if (*DeductionInfo &&
3091 (*DeductionInfo)->hasSFINAEDiagnostic() &&
3092 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3093 diag::err_typename_nested_not_found_enable_if &&
3094 TemplateArgs[0].getArgument().getKind()
3095 == TemplateArgument::Expression) {
3096 Expr *FailedCond;
3097 std::string FailedDescription;
3098 std::tie(FailedCond, FailedDescription) =
Douglas Gregor672281a2017-09-14 23:38:42 +00003099 findFailedBooleanCondition(
3100 TemplateArgs[0].getSourceExpression(),
3101 /*AllowTopLevelCond=*/true);
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003102
3103 // Remove the old SFINAE diagnostic.
3104 PartialDiagnosticAt OldDiag =
3105 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3106 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3107
3108 // Add a new SFINAE diagnostic specifying which condition
3109 // failed.
3110 (*DeductionInfo)->addSFINAEDiagnostic(
3111 OldDiag.first,
3112 PDiag(diag::err_typename_nested_not_found_requirement)
3113 << FailedDescription
3114 << FailedCond->getSourceRange());
3115 }
3116 }
3117 }
3118
Richard Smith3f1b5d02011-05-05 21:57:07 +00003119 return QualType();
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003120 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00003121 } else if (Name.isDependent() ||
3122 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00003123 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00003124 // This class template specialization is a dependent
3125 // type. Therefore, its canonical type is another class template
3126 // specialization type that contains all of the converted
3127 // arguments in canonical form. This ensures that, e.g., A<T> and
3128 // A<T, T> have identical types when A is declared as:
3129 //
3130 // template<typename T, typename U = T> struct A;
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00003131 CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
John McCall2408e322010-04-27 00:57:59 +00003132
3133 // This might work out to be a current instantiation, in which
3134 // case the canonical type needs to be the InjectedClassNameType.
3135 //
3136 // TODO: in theory this could be a simple hashtable lookup; most
3137 // changes to CurContext don't change the set of current
3138 // instantiations.
3139 if (isa<ClassTemplateDecl>(Template)) {
3140 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3141 // If we get out to a namespace, we're done.
3142 if (Ctx->isFileContext()) break;
3143
3144 // If this isn't a record, keep looking.
3145 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3146 if (!Record) continue;
3147
3148 // Look for one of the two cases with InjectedClassNameTypes
3149 // and check whether it's the same template.
3150 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3151 !Record->getDescribedClassTemplate())
3152 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003153
John McCall2408e322010-04-27 00:57:59 +00003154 // Fetch the injected class name type and check whether its
3155 // injected type is equal to the type we just built.
3156 QualType ICNT = Context.getTypeDeclType(Record);
3157 QualType Injected = cast<InjectedClassNameType>(ICNT)
3158 ->getInjectedSpecializationType();
3159
3160 if (CanonType != Injected->getCanonicalTypeInternal())
3161 continue;
3162
3163 // If so, the canonical type of this TST is the injected
3164 // class name type of the record we just found.
3165 assert(ICNT.isCanonical());
3166 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00003167 break;
3168 }
3169 }
Mike Stump11289f42009-09-09 15:08:12 +00003170 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00003171 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00003172 // Find the class template specialization declaration that
3173 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00003174 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00003175 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00003176 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003177 if (!Decl) {
3178 // This is the first time we have referenced this class template
3179 // specialization. Create the canonical declaration and add it to
3180 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00003181 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00003182 ClassTemplate->getTemplatedDecl()->getTagKind(),
3183 ClassTemplate->getDeclContext(),
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00003184 ClassTemplate->getTemplatedDecl()->getLocStart(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003185 ClassTemplate->getLocation(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003186 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00003187 Converted, nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003188 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00003189 if (ClassTemplate->isOutOfLine())
3190 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00003191 }
3192
Erich Keanea32910d2017-03-23 18:51:54 +00003193 if (Decl->getSpecializationKind() == TSK_Undeclared) {
3194 MultiLevelTemplateArgumentList TemplateArgLists;
3195 TemplateArgLists.addOuterTemplateArguments(Converted);
3196 InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(),
3197 Decl);
3198 }
3199
Chandler Carruth2acfb222013-09-27 22:14:40 +00003200 // Diagnose uses of this specialization.
3201 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3202
Douglas Gregorc40290e2009-03-09 23:48:35 +00003203 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00003204 assert(isa<RecordType>(CanonType) &&
3205 "type of non-dependent specialization is not a RecordType");
David Majnemerd9b1a4f2015-11-04 03:40:30 +00003206 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3207 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
3208 TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003209 }
Mike Stump11289f42009-09-09 15:08:12 +00003210
Douglas Gregorc40290e2009-03-09 23:48:35 +00003211 // Build the fully-sugared type for this class template
3212 // specialization, which refers back to the class template
3213 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00003214 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003215}
3216
John McCallfaf5fb42010-08-26 23:41:50 +00003217TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003218Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Richard Smith74f02342017-01-19 21:00:13 +00003219 TemplateTy TemplateD, IdentifierInfo *TemplateII,
3220 SourceLocation TemplateIILoc,
Mike Stump11289f42009-09-09 15:08:12 +00003221 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00003222 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnara4244b432012-01-27 08:46:19 +00003223 SourceLocation RAngleLoc,
Richard Smith62559bd2017-02-01 21:36:38 +00003224 bool IsCtorOrDtorName, bool IsClassName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00003225 if (SS.isInvalid())
3226 return true;
3227
Richard Smith62559bd2017-02-01 21:36:38 +00003228 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3229 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3230
3231 // C++ [temp.res]p3:
3232 // A qualified-id that refers to a type and in which the
3233 // nested-name-specifier depends on a template-parameter (14.6.2)
3234 // shall be prefixed by the keyword typename to indicate that the
3235 // qualified-id denotes a type, forming an
3236 // elaborated-type-specifier (7.1.5.3).
3237 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
Richard Smith3411fbf2017-02-01 21:41:18 +00003238 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
Richard Smith62559bd2017-02-01 21:36:38 +00003239 << SS.getScopeRep() << TemplateII->getName();
3240 // Recover as if 'typename' were specified.
3241 // FIXME: This is not quite correct recovery as we don't transform SS
3242 // into the corresponding dependent form (and we don't diagnose missing
3243 // 'template' keywords within SS as a result).
3244 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3245 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3246 TemplateArgsIn, RAngleLoc);
3247 }
3248
3249 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3250 // it's not actually allowed to be used as a type in most cases. Because
3251 // we annotate it before we know whether it's valid, we have to check for
3252 // this case here.
3253 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
Richard Smith74f02342017-01-19 21:00:13 +00003254 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3255 Diag(TemplateIILoc,
3256 TemplateKWLoc.isInvalid()
3257 ? diag::err_out_of_line_qualified_id_type_names_constructor
3258 : diag::ext_out_of_line_qualified_id_type_names_constructor)
3259 << TemplateII << 0 /*injected-class-name used as template name*/
3260 << 1 /*if any keyword was present, it was 'template'*/;
3261 }
3262 }
3263
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003264 TemplateName Template = TemplateD.get();
Douglas Gregor8bf42052009-02-09 18:46:07 +00003265
Douglas Gregorc40290e2009-03-09 23:48:35 +00003266 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003267 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003268 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00003269
Douglas Gregor5a064722011-02-28 17:23:35 +00003270 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00003271 QualType T
3272 = Context.getDependentTemplateSpecializationType(ETK_None,
3273 DTN->getQualifier(),
3274 DTN->getIdentifier(),
3275 TemplateArgs);
3276 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00003277 TypeLocBuilder TLB;
3278 DependentTemplateSpecializationTypeLoc SpecTL
3279 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003280 SpecTL.setElaboratedKeywordLoc(SourceLocation());
3281 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00003282 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00003283 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00003284 SpecTL.setLAngleLoc(LAngleLoc);
3285 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00003286 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3287 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3288 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3289 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003290
Richard Smith74f02342017-01-19 21:00:13 +00003291 QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003292 if (Result.isNull())
3293 return true;
3294
Douglas Gregore7c20652011-03-02 00:47:37 +00003295 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003296 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00003297 TemplateSpecializationTypeLoc SpecTL
3298 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003299 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00003300 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003301 SpecTL.setLAngleLoc(LAngleLoc);
3302 SpecTL.setRAngleLoc(RAngleLoc);
3303 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3304 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00003305
Abramo Bagnara4244b432012-01-27 08:46:19 +00003306 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
3307 // constructor or destructor name (in such a case, the scope specifier
3308 // will be attached to the enclosing Decl or Expr node).
3309 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00003310 // Create an elaborated-type-specifier containing the nested-name-specifier.
3311 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
3312 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00003313 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00003314 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3315 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003316
Douglas Gregore7c20652011-03-02 00:47:37 +00003317 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00003318}
John McCall06f6fe8d2009-09-04 01:14:41 +00003319
Douglas Gregore7c20652011-03-02 00:47:37 +00003320TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00003321 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00003322 SourceLocation TagLoc,
3323 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003324 SourceLocation TemplateKWLoc,
3325 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00003326 SourceLocation TemplateLoc,
3327 SourceLocation LAngleLoc,
3328 ASTTemplateArgsPtr TemplateArgsIn,
3329 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003330 TemplateName Template = TemplateD.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00003331
Douglas Gregore7c20652011-03-02 00:47:37 +00003332 // Translate the parser's template argument list in our AST format.
3333 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3334 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003335
Douglas Gregore7c20652011-03-02 00:47:37 +00003336 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00003337 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00003338 ElaboratedTypeKeyword Keyword
3339 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00003340
Douglas Gregore7c20652011-03-02 00:47:37 +00003341 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3342 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
Simon Pilgrim6905d222016-12-30 22:55:33 +00003343 DTN->getQualifier(),
3344 DTN->getIdentifier(),
Douglas Gregore7c20652011-03-02 00:47:37 +00003345 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003346
3347 // Build type-source information.
Douglas Gregore7c20652011-03-02 00:47:37 +00003348 TypeLocBuilder TLB;
3349 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003350 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3351 SpecTL.setElaboratedKeywordLoc(TagLoc);
3352 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00003353 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003354 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003355 SpecTL.setLAngleLoc(LAngleLoc);
3356 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003357 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3358 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3359 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3360 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00003361
3362 if (TypeAliasTemplateDecl *TAT =
3363 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3364 // C++0x [dcl.type.elab]p2:
3365 // If the identifier resolves to a typedef-name or the simple-template-id
3366 // resolves to an alias template specialization, the
3367 // elaborated-type-specifier is ill-formed.
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00003368 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3369 << TAT << NTK_TypeAliasTemplate << TagKind;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003370 Diag(TAT->getLocation(), diag::note_declared_at);
3371 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003372
Douglas Gregore7c20652011-03-02 00:47:37 +00003373 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3374 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00003375 return TypeResult(true);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003376
Douglas Gregore7c20652011-03-02 00:47:37 +00003377 // Check the tag kind
3378 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00003379 RecordDecl *D = RT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00003380
John McCalld8fe9af2009-09-08 17:47:29 +00003381 IdentifierInfo *Id = D->getIdentifier();
3382 assert(Id && "templated class must have an identifier");
Simon Pilgrim6905d222016-12-30 22:55:33 +00003383
Richard Trieucaa33d32011-06-10 03:11:26 +00003384 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00003385 TagLoc, Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00003386 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00003387 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00003388 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00003389 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00003390 }
3391 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003392
Douglas Gregore7c20652011-03-02 00:47:37 +00003393 // Provide source-location information for the template specialization.
3394 TypeLocBuilder TLB;
3395 TemplateSpecializationTypeLoc SpecTL
3396 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003397 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003398 SpecTL.setTemplateNameLoc(TemplateLoc);
3399 SpecTL.setLAngleLoc(LAngleLoc);
3400 SpecTL.setRAngleLoc(RAngleLoc);
3401 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3402 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00003403
Douglas Gregore7c20652011-03-02 00:47:37 +00003404 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003405 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00003406 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3407 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00003408 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003409 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3410 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003411}
3412
Larisse Voufo39a1e502013-08-06 01:03:05 +00003413static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3414 NamedDecl *PrevDecl,
3415 SourceLocation Loc,
3416 bool IsPartialSpecialization);
3417
3418static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003419
Richard Smith300e0c32013-09-24 04:49:23 +00003420static bool isTemplateArgumentTemplateParameter(
3421 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3422 switch (Arg.getKind()) {
3423 case TemplateArgument::Null:
3424 case TemplateArgument::NullPtr:
3425 case TemplateArgument::Integral:
3426 case TemplateArgument::Declaration:
3427 case TemplateArgument::Pack:
3428 case TemplateArgument::TemplateExpansion:
3429 return false;
3430
3431 case TemplateArgument::Type: {
3432 QualType Type = Arg.getAsType();
3433 const TemplateTypeParmType *TPT =
3434 Arg.getAsType()->getAs<TemplateTypeParmType>();
3435 return TPT && !Type.hasQualifiers() &&
3436 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3437 }
3438
3439 case TemplateArgument::Expression: {
3440 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3441 if (!DRE || !DRE->getDecl())
3442 return false;
3443 const NonTypeTemplateParmDecl *NTTP =
3444 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3445 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3446 }
3447
3448 case TemplateArgument::Template:
3449 const TemplateTemplateParmDecl *TTP =
3450 dyn_cast_or_null<TemplateTemplateParmDecl>(
3451 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
3452 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3453 }
3454 llvm_unreachable("unexpected kind of template argument");
3455}
3456
3457static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
3458 ArrayRef<TemplateArgument> Args) {
3459 if (Params->size() != Args.size())
3460 return false;
3461
3462 unsigned Depth = Params->getDepth();
3463
3464 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3465 TemplateArgument Arg = Args[I];
3466
3467 // If the parameter is a pack expansion, the argument must be a pack
3468 // whose only element is a pack expansion.
3469 if (Params->getParam(I)->isParameterPack()) {
3470 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3471 !Arg.pack_begin()->isPackExpansion())
3472 return false;
3473 Arg = Arg.pack_begin()->getPackExpansionPattern();
3474 }
3475
3476 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3477 return false;
3478 }
3479
3480 return true;
3481}
3482
Richard Smith4b55a9c2014-04-17 03:29:33 +00003483/// Convert the parser's template argument list representation into our form.
3484static TemplateArgumentListInfo
3485makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
3486 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
3487 TemplateId.RAngleLoc);
3488 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
3489 TemplateId.NumArgs);
3490 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
3491 return TemplateArgs;
3492}
3493
Richard Smith0e617ec2016-12-27 07:56:27 +00003494template<typename PartialSpecDecl>
3495static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3496 if (Partial->getDeclContext()->isDependentContext())
3497 return;
3498
3499 // FIXME: Get the TDK from deduction in order to provide better diagnostics
3500 // for non-substitution-failure issues?
3501 TemplateDeductionInfo Info(Partial->getLocation());
3502 if (S.isMoreSpecializedThanPrimary(Partial, Info))
3503 return;
3504
3505 auto *Template = Partial->getSpecializedTemplate();
3506 S.Diag(Partial->getLocation(),
Richard Smithfa4a09d2016-12-27 20:03:09 +00003507 diag::ext_partial_spec_not_more_specialized_than_primary)
3508 << isa<VarTemplateDecl>(Template);
Richard Smith0e617ec2016-12-27 07:56:27 +00003509
3510 if (Info.hasSFINAEDiagnostic()) {
3511 PartialDiagnosticAt Diag = {SourceLocation(),
3512 PartialDiagnostic::NullDiagnostic()};
3513 Info.takeSFINAEDiagnostic(Diag);
3514 SmallString<128> SFINAEArgString;
3515 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3516 S.Diag(Diag.first,
3517 diag::note_partial_spec_not_more_specialized_than_primary)
3518 << SFINAEArgString;
3519 }
3520
3521 S.Diag(Template->getLocation(), diag::note_template_decl_here);
3522}
3523
Richard Smith4e05eaa2017-02-16 00:36:47 +00003524static void
3525noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
3526 const llvm::SmallBitVector &DeducibleParams) {
3527 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3528 if (!DeducibleParams[I]) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00003529 NamedDecl *Param = TemplateParams->getParam(I);
Richard Smith4e05eaa2017-02-16 00:36:47 +00003530 if (Param->getDeclName())
3531 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3532 << Param->getDeclName();
3533 else
3534 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3535 << "(anonymous)";
3536 }
3537 }
3538}
3539
3540
Richard Smith57aae072016-12-28 02:37:25 +00003541template<typename PartialSpecDecl>
3542static void checkTemplatePartialSpecialization(Sema &S,
3543 PartialSpecDecl *Partial) {
3544 // C++1z [temp.class.spec]p8: (DR1495)
3545 // - The specialization shall be more specialized than the primary
3546 // template (14.5.5.2).
3547 checkMoreSpecializedThanPrimary(S, Partial);
3548
3549 // C++ [temp.class.spec]p8: (DR1315)
3550 // - Each template-parameter shall appear at least once in the
3551 // template-id outside a non-deduced context.
3552 // C++1z [temp.class.spec.match]p3 (P0127R2)
3553 // If the template arguments of a partial specialization cannot be
3554 // deduced because of the structure of its template-parameter-list
3555 // and the template-id, the program is ill-formed.
3556 auto *TemplateParams = Partial->getTemplateParameters();
3557 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3558 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3559 TemplateParams->getDepth(), DeducibleParams);
3560
3561 if (!DeducibleParams.all()) {
3562 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3563 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3564 << isa<VarTemplatePartialSpecializationDecl>(Partial)
3565 << (NumNonDeducible > 1)
3566 << SourceRange(Partial->getLocation(),
3567 Partial->getTemplateArgsAsWritten()->RAngleLoc);
Richard Smith4e05eaa2017-02-16 00:36:47 +00003568 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
Richard Smith57aae072016-12-28 02:37:25 +00003569 }
3570}
3571
3572void Sema::CheckTemplatePartialSpecialization(
3573 ClassTemplatePartialSpecializationDecl *Partial) {
3574 checkTemplatePartialSpecialization(*this, Partial);
3575}
3576
3577void Sema::CheckTemplatePartialSpecialization(
3578 VarTemplatePartialSpecializationDecl *Partial) {
3579 checkTemplatePartialSpecialization(*this, Partial);
3580}
3581
Richard Smith4e05eaa2017-02-16 00:36:47 +00003582void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
3583 // C++1z [temp.param]p11:
3584 // A template parameter of a deduction guide template that does not have a
3585 // default-argument shall be deducible from the parameter-type-list of the
3586 // deduction guide template.
3587 auto *TemplateParams = TD->getTemplateParameters();
3588 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3589 MarkDeducedTemplateParameters(TD, DeducibleParams);
3590 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3591 // A parameter pack is deducible (to an empty pack).
3592 auto *Param = TemplateParams->getParam(I);
3593 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3594 DeducibleParams[I] = true;
3595 }
3596
3597 if (!DeducibleParams.all()) {
3598 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3599 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3600 << (NumNonDeducible > 1);
3601 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3602 }
3603}
3604
Larisse Voufo39a1e502013-08-06 01:03:05 +00003605DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00003606 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00003607 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00003608 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003609 // D must be variable template id.
Faisal Vali2ab8c152017-12-30 04:15:27 +00003610 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00003611 "Variable template specialization is declared with a template it.");
3612
3613 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00003614 TemplateArgumentListInfo TemplateArgs =
3615 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003616 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3617 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3618 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00003619
Richard Smithbeef3452014-01-16 23:39:20 +00003620 TemplateName Name = TemplateId->Template.get();
3621
3622 // The template-id must name a variable template.
3623 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00003624 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3625 if (!VarTemplate) {
3626 NamedDecl *FnTemplate;
3627 if (auto *OTS = Name.getAsOverloadedTemplate())
3628 FnTemplate = *OTS->begin();
3629 else
3630 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3631 if (FnTemplate)
3632 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3633 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00003634 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3635 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00003636 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003637
3638 // Check for unexpanded parameter packs in any of the template arguments.
3639 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3640 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3641 UPPC_PartialSpecialization))
3642 return true;
3643
3644 // Check that the template argument list is well-formed for this
3645 // template.
3646 SmallVector<TemplateArgument, 4> Converted;
3647 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
3648 false, Converted))
3649 return true;
3650
Larisse Voufo39a1e502013-08-06 01:03:05 +00003651 // Find the variable template (partial) specialization declaration that
3652 // corresponds to these arguments.
3653 if (IsPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00003654 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
3655 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00003656 return true;
3657
Richard Smith57aae072016-12-28 02:37:25 +00003658 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
3659 // also do them during instantiation.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003660 bool InstantiationDependent;
3661 if (!Name.isDependent() &&
3662 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00003663 TemplateArgs.arguments(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00003664 InstantiationDependent)) {
3665 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3666 << VarTemplate->getDeclName();
3667 IsPartialSpecialization = false;
3668 }
Richard Smith300e0c32013-09-24 04:49:23 +00003669
3670 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
3671 Converted)) {
3672 // C++ [temp.class.spec]p9b3:
3673 //
3674 // -- The argument list of the specialization shall not be identical
3675 // to the implicit argument list of the primary template.
3676 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3677 << /*variable template*/ 1
3678 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
3679 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
3680 // FIXME: Recover from this by treating the declaration as a redeclaration
3681 // of the primary template.
3682 return true;
3683 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003684 }
3685
Craig Topperc3ec1492014-05-26 06:22:03 +00003686 void *InsertPos = nullptr;
3687 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003688
3689 if (IsPartialSpecialization)
3690 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00003691 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003692 else
Craig Topper7e0daca2014-06-26 04:58:53 +00003693 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003694
Craig Topperc3ec1492014-05-26 06:22:03 +00003695 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003696
3697 // Check whether we can declare a variable template specialization in
3698 // the current scope.
3699 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
3700 TemplateNameLoc,
3701 IsPartialSpecialization))
3702 return true;
3703
3704 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3705 // Since the only prior variable template specialization with these
3706 // arguments was referenced but not declared, reuse that
3707 // declaration node as our own, updating its source location and
3708 // the list of outer template parameters to reflect our new declaration.
3709 Specialization = PrevDecl;
3710 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00003711 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003712 } else if (IsPartialSpecialization) {
3713 // Create a new class template partial specialization declaration node.
3714 VarTemplatePartialSpecializationDecl *PrevPartial =
3715 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003716 VarTemplatePartialSpecializationDecl *Partial =
3717 VarTemplatePartialSpecializationDecl::Create(
3718 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
3719 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
David Majnemer8b622692016-07-03 21:17:51 +00003720 Converted, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003721
3722 if (!PrevPartial)
3723 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
3724 Specialization = Partial;
3725
3726 // If we are providing an explicit specialization of a member variable
3727 // template specialization, make a note of that.
3728 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00003729 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00003730
Richard Smith57aae072016-12-28 02:37:25 +00003731 CheckTemplatePartialSpecialization(Partial);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003732 } else {
3733 // Create a new class template specialization declaration node for
3734 // this explicit specialization or friend declaration.
3735 Specialization = VarTemplateSpecializationDecl::Create(
3736 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
David Majnemer8b622692016-07-03 21:17:51 +00003737 VarTemplate, DI->getType(), DI, SC, Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003738 Specialization->setTemplateArgsInfo(TemplateArgs);
3739
3740 if (!PrevDecl)
3741 VarTemplate->AddSpecialization(Specialization, InsertPos);
3742 }
3743
3744 // C++ [temp.expl.spec]p6:
3745 // If a template, a member template or the member of a class template is
3746 // explicitly specialized then that specialization shall be declared
3747 // before the first use of that specialization that would cause an implicit
3748 // instantiation to take place, in every translation unit in which such a
3749 // use occurs; no diagnostic is required.
3750 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3751 bool Okay = false;
3752 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
3753 // Is there any previous explicit specialization declaration?
3754 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3755 Okay = true;
3756 break;
3757 }
3758 }
3759
3760 if (!Okay) {
3761 SourceRange Range(TemplateNameLoc, RAngleLoc);
3762 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3763 << Name << Range;
3764
3765 Diag(PrevDecl->getPointOfInstantiation(),
3766 diag::note_instantiation_required_here)
3767 << (PrevDecl->getTemplateSpecializationKind() !=
3768 TSK_ImplicitInstantiation);
3769 return true;
3770 }
3771 }
3772
3773 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
3774 Specialization->setLexicalDeclContext(CurContext);
3775
3776 // Add the specialization into its lexical context, so that it can
3777 // be seen when iterating through the list of declarations in that
3778 // context. However, specializations are not found by name lookup.
3779 CurContext->addDecl(Specialization);
3780
3781 // Note that this is an explicit specialization.
3782 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
3783
3784 if (PrevDecl) {
3785 // Check that this isn't a redefinition of this specialization,
3786 // merging with previous declarations.
3787 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00003788 forRedeclarationInCurContext());
Larisse Voufo39a1e502013-08-06 01:03:05 +00003789 PrevSpec.addDecl(PrevDecl);
3790 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00003791 } else if (Specialization->isStaticDataMember() &&
3792 Specialization->isOutOfLine()) {
3793 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00003794 }
3795
3796 // Link instantiations of static data members back to the template from
3797 // which they were instantiated.
3798 if (Specialization->isStaticDataMember())
3799 Specialization->setInstantiationOfStaticDataMember(
3800 VarTemplate->getTemplatedDecl(),
3801 Specialization->getSpecializationKind());
3802
3803 return Specialization;
3804}
3805
3806namespace {
3807/// \brief A partial specialization whose template arguments have matched
3808/// a given template-id.
3809struct PartialSpecMatchResult {
3810 VarTemplatePartialSpecializationDecl *Partial;
3811 TemplateArgumentList *Args;
3812};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003813} // end anonymous namespace
Larisse Voufo39a1e502013-08-06 01:03:05 +00003814
3815DeclResult
3816Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
3817 SourceLocation TemplateNameLoc,
3818 const TemplateArgumentListInfo &TemplateArgs) {
3819 assert(Template && "A variable template id without template?");
3820
3821 // Check that the template argument list is well-formed for this template.
3822 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003823 if (CheckTemplateArgumentList(
3824 Template, TemplateNameLoc,
3825 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00003826 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00003827 return true;
3828
3829 // Find the variable template specialization declaration that
3830 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00003831 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003832 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Richard Smith6739a102016-05-05 00:56:12 +00003833 Converted, InsertPos)) {
3834 checkSpecializationVisibility(TemplateNameLoc, Spec);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003835 // If we already have a variable template specialization, return it.
3836 return Spec;
Richard Smith6739a102016-05-05 00:56:12 +00003837 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003838
3839 // This is the first time we have referenced this variable template
3840 // specialization. Create the canonical declaration and add it to
3841 // the set of specializations, based on the closest partial specialization
3842 // that it represents. That is,
3843 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
3844 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00003845 Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003846 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
3847 bool AmbiguousPartialSpec = false;
3848 typedef PartialSpecMatchResult MatchResult;
3849 SmallVector<MatchResult, 4> Matched;
3850 SourceLocation PointOfInstantiation = TemplateNameLoc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003851 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
3852 /*ForTakingAddress=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003853
3854 // 1. Attempt to find the closest partial specialization that this
3855 // specializes, if any.
3856 // If any of the template arguments is dependent, then this is probably
3857 // a placeholder for an incomplete declarative context; which must be
3858 // complete by instantiation time. Thus, do not search through the partial
3859 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00003860 // TODO: Unify with InstantiateClassTemplateSpecialization()?
3861 // Perhaps better after unification of DeduceTemplateArguments() and
3862 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00003863 bool InstantiationDependent = false;
3864 if (!TemplateSpecializationType::anyDependentTemplateArguments(
3865 TemplateArgs, InstantiationDependent)) {
3866
3867 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3868 Template->getPartialSpecializations(PartialSpecs);
3869
3870 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3871 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3872 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3873
3874 if (TemplateDeductionResult Result =
3875 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
3876 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00003877 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00003878 FailedCandidates.addCandidate().set(
3879 DeclAccessPair::make(Template, AS_public), Partial,
3880 MakeDeductionFailureInfo(Context, Result, Info));
Larisse Voufo39a1e502013-08-06 01:03:05 +00003881 (void)Result;
3882 } else {
3883 Matched.push_back(PartialSpecMatchResult());
3884 Matched.back().Partial = Partial;
3885 Matched.back().Args = Info.take();
3886 }
3887 }
3888
Larisse Voufo39a1e502013-08-06 01:03:05 +00003889 if (Matched.size() >= 1) {
3890 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
3891 if (Matched.size() == 1) {
3892 // -- If exactly one matching specialization is found, the
3893 // instantiation is generated from that specialization.
3894 // We don't need to do anything for this.
3895 } else {
3896 // -- If more than one matching specialization is found, the
3897 // partial order rules (14.5.4.2) are used to determine
3898 // whether one of the specializations is more specialized
3899 // than the others. If none of the specializations is more
3900 // specialized than all of the other matching
3901 // specializations, then the use of the variable template is
3902 // ambiguous and the program is ill-formed.
3903 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
3904 PEnd = Matched.end();
3905 P != PEnd; ++P) {
3906 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
3907 PointOfInstantiation) ==
3908 P->Partial)
3909 Best = P;
3910 }
3911
3912 // Determine if the best partial specialization is more specialized than
3913 // the others.
3914 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
3915 PEnd = Matched.end();
3916 P != PEnd; ++P) {
3917 if (P != Best && getMoreSpecializedPartialSpecialization(
3918 P->Partial, Best->Partial,
3919 PointOfInstantiation) != Best->Partial) {
3920 AmbiguousPartialSpec = true;
3921 break;
3922 }
3923 }
3924 }
3925
3926 // Instantiate using the best variable template partial specialization.
3927 InstantiationPattern = Best->Partial;
3928 InstantiationArgs = Best->Args;
3929 } else {
3930 // -- If no match is found, the instantiation is generated
3931 // from the primary template.
3932 // InstantiationPattern = Template->getTemplatedDecl();
3933 }
3934 }
3935
Larisse Voufo39a1e502013-08-06 01:03:05 +00003936 // 2. Create the canonical declaration.
Richard Smith6739a102016-05-05 00:56:12 +00003937 // Note that we do not instantiate a definition until we see an odr-use
3938 // in DoMarkVarDeclReferenced().
Larisse Voufo39a1e502013-08-06 01:03:05 +00003939 // FIXME: LateAttrs et al.?
3940 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
3941 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
3942 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
3943 if (!Decl)
3944 return true;
3945
3946 if (AmbiguousPartialSpec) {
3947 // Partial ordering did not produce a clear winner. Complain.
3948 Decl->setInvalidDecl();
3949 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
3950 << Decl;
3951
3952 // Print the matching partial specializations.
Yaron Keren1cb81462016-11-16 13:45:34 +00003953 for (MatchResult P : Matched)
3954 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
3955 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
3956 *P.Args);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003957 return true;
3958 }
3959
3960 if (VarTemplatePartialSpecializationDecl *D =
3961 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
3962 Decl->setInstantiationOf(D, InstantiationArgs);
3963
Richard Smith6739a102016-05-05 00:56:12 +00003964 checkSpecializationVisibility(TemplateNameLoc, Decl);
3965
Larisse Voufo39a1e502013-08-06 01:03:05 +00003966 assert(Decl && "No variable template specialization?");
3967 return Decl;
3968}
3969
3970ExprResult
3971Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
3972 const DeclarationNameInfo &NameInfo,
3973 VarTemplateDecl *Template, SourceLocation TemplateLoc,
3974 const TemplateArgumentListInfo *TemplateArgs) {
3975
3976 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
3977 *TemplateArgs);
3978 if (Decl.isInvalid())
3979 return ExprError();
3980
3981 VarDecl *Var = cast<VarDecl>(Decl.get());
3982 if (!Var->getTemplateSpecializationKind())
3983 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
3984 NameInfo.getLoc());
3985
3986 // Build an ordinary singleton decl ref.
3987 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00003988 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003989}
3990
Richard Smithecad88d2018-04-26 01:08:00 +00003991void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
3992 SourceLocation Loc) {
3993 Diag(Loc, diag::err_template_missing_args)
3994 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
3995 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
3996 Diag(TD->getLocation(), diag::note_template_decl_here)
3997 << TD->getTemplateParameters()->getSourceRange();
3998 }
3999}
4000
John McCalldadc5752010-08-24 06:29:42 +00004001ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004002 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00004003 LookupResult &R,
4004 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00004005 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00004006 // FIXME: Can we do any checking at this point? I guess we could check the
4007 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00004008 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00004009 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00004010 // foo<int> could identify a single function unambiguously
4011 // This approach does NOT work, since f<int>(1);
4012 // gets resolved prior to resorting to overload resolution
4013 // i.e., template<class T> void f(double);
4014 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00004015
4016 // These should be filtered out by our callers.
4017 assert(!R.empty() && "empty lookup results when building templateid");
4018 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4019
Richard Smith04100942018-04-26 02:10:22 +00004020 // Non-function templates require a template argument list.
4021 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4022 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4023 diagnoseMissingTemplateArguments(TemplateName(TD), R.getNameLoc());
4024 return ExprError();
4025 }
4026 }
4027
Richard Smith0bf96f92018-04-25 22:58:55 +00004028 auto AnyDependentArguments = [&]() -> bool {
4029 bool InstantiationDependent;
4030 return TemplateArgs &&
4031 TemplateSpecializationType::anyDependentTemplateArguments(
4032 *TemplateArgs, InstantiationDependent);
4033 };
4034
Larisse Voufo39a1e502013-08-06 01:03:05 +00004035 // In C++1y, check variable template ids.
Richard Smith0bf96f92018-04-25 22:58:55 +00004036 if (R.getAsSingle<VarTemplateDecl>() && !AnyDependentArguments()) {
Richard Smithd7d11ef2014-02-03 20:09:56 +00004037 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
4038 R.getAsSingle<VarTemplateDecl>(),
4039 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004040 }
4041
John McCall58cc69d2010-01-27 01:50:18 +00004042 // We don't want lookup warnings at this point.
4043 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004044
John McCalle66edc12009-11-24 19:00:30 +00004045 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00004046 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00004047 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00004048 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004049 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004050 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00004051 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00004052
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004053 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00004054}
4055
John McCalle66edc12009-11-24 19:00:30 +00004056// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00004057ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004058Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004059 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004060 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00004061 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004062
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00004063 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00004064 DeclContext *DC;
4065 if (!(DC = computeDeclContext(SS, false)) ||
4066 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00004067 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00004068 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004069
Douglas Gregor786123d2010-05-21 23:18:07 +00004070 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004071 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Craig Topperc3ec1492014-05-26 06:22:03 +00004072 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
Douglas Gregor786123d2010-05-21 23:18:07 +00004073 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00004074
John McCalle66edc12009-11-24 19:00:30 +00004075 if (R.isAmbiguous())
4076 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004077
John McCalle66edc12009-11-24 19:00:30 +00004078 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004079 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
4080 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00004081 return ExprError();
4082 }
4083
4084 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004085 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00004086 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00004087 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00004088 Diag(Temp->getLocation(), diag::note_referenced_class_template);
4089 return ExprError();
4090 }
4091
Abramo Bagnara7945c982012-01-27 09:46:47 +00004092 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00004093}
4094
Douglas Gregorb67535d2009-03-31 00:43:58 +00004095/// \brief Form a dependent template name.
4096///
4097/// This action forms a dependent template name given the template
4098/// name and its (presumably dependent) scope specifier. For
4099/// example, given "MetaFun::template apply", the scope specifier \p
4100/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
4101/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004102TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00004103 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004104 SourceLocation TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00004105 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00004106 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00004107 bool EnteringContext,
Richard Smithfd3dae02017-01-20 00:20:39 +00004108 TemplateTy &Result,
4109 bool AllowInjectedClassName) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004110 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4111 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004112 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004113 diag::warn_cxx98_compat_template_outside_of_template :
4114 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004115 << FixItHint::CreateRemoval(TemplateKWLoc);
4116
Craig Topperc3ec1492014-05-26 06:22:03 +00004117 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00004118 if (SS.isSet())
4119 LookupCtx = computeDeclContext(SS, EnteringContext);
4120 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00004121 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00004122 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00004123 // C++0x [temp.names]p5:
4124 // If a name prefixed by the keyword template is not the name of
4125 // a template, the program is ill-formed. [Note: the keyword
4126 // template may not be applied to non-template members of class
4127 // templates. -end note ] [ Note: as is the case with the
4128 // typename prefix, the template prefix is allowed in cases
4129 // where it is not strictly necessary; i.e., when the
4130 // nested-name-specifier or the expression on the left of the ->
4131 // or . is not dependent on a template-parameter, or the use
4132 // does not appear in the scope of a template. -end note]
4133 //
4134 // Note: C++03 was more strict here, because it banned the use of
4135 // the "template" keyword prior to a template-name that was not a
4136 // dependent name. C++ DR468 relaxed this requirement (the
4137 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00004138 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00004139 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00004140 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00004141 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00004142 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00004143 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
4144 isa<CXXRecordDecl>(LookupCtx) &&
Douglas Gregor5ecbb1b2011-03-11 23:27:41 +00004145 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
4146 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
Douglas Gregorbb119652010-06-16 23:00:59 +00004147 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00004148 } else if (TNK == TNK_Non_template) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004149 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00004150 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004151 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00004152 << Name.getSourceRange()
4153 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00004154 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00004155 } else {
4156 // We found something; return it.
Richard Smithfd3dae02017-01-20 00:20:39 +00004157 auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
4158 if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
Faisal Vali2ab8c152017-12-30 04:15:27 +00004159 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4160 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
Richard Smithfd3dae02017-01-20 00:20:39 +00004161 // C++14 [class.qual]p2:
4162 // In a lookup in which function names are not ignored and the
4163 // nested-name-specifier nominates a class C, if the name specified
4164 // [...] is the injected-class-name of C, [...] the name is instead
4165 // considered to name the constructor
4166 //
4167 // We don't get here if naming the constructor would be valid, so we
4168 // just reject immediately and recover by treating the
4169 // injected-class-name as naming the template.
4170 Diag(Name.getLocStart(),
4171 diag::ext_out_of_line_qualified_id_type_names_constructor)
4172 << Name.Identifier << 0 /*injected-class-name used as template name*/
4173 << 1 /*'template' keyword was used*/;
4174 }
Douglas Gregorbb119652010-06-16 23:00:59 +00004175 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00004176 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00004177 }
4178
Aaron Ballman4a979672014-01-03 13:56:08 +00004179 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004180
Douglas Gregor3cf81312009-11-03 23:16:33 +00004181 switch (Name.getKind()) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00004182 case UnqualifiedIdKind::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004183 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00004184 Name.Identifier));
4185 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004186
Faisal Vali2ab8c152017-12-30 04:15:27 +00004187 case UnqualifiedIdKind::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00004188 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00004189 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00004190 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00004191
Faisal Vali2ab8c152017-12-30 04:15:27 +00004192 case UnqualifiedIdKind::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00004193 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00004194
Douglas Gregor3cf81312009-11-03 23:16:33 +00004195 default:
4196 break;
4197 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004198
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004199 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00004200 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004201 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00004202 << Name.getSourceRange()
4203 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00004204 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00004205}
4206
Mike Stump11289f42009-09-09 15:08:12 +00004207bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00004208 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004209 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00004210 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00004211 QualType ArgType;
4212 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00004213
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004214 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004215 switch(Arg.getKind()) {
4216 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004217 // C++ [temp.arg.type]p1:
4218 // A template-argument for a template-parameter which is a
4219 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00004220 ArgType = Arg.getAsType();
4221 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004222 break;
Richard Smith77a9c602018-02-28 03:02:23 +00004223 case TemplateArgument::Template:
4224 case TemplateArgument::TemplateExpansion: {
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004225 // We have a template type parameter but the template argument
4226 // is a template without any arguments.
4227 SourceRange SR = AL.getSourceRange();
Richard Smith77a9c602018-02-28 03:02:23 +00004228 TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
Richard Smithecad88d2018-04-26 01:08:00 +00004229 diagnoseMissingTemplateArguments(Name, SR.getEnd());
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004230 return true;
4231 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004232 case TemplateArgument::Expression: {
4233 // We have a template type parameter but the template argument is an
4234 // expression; see if maybe it is missing the "typename" keyword.
4235 CXXScopeSpec SS;
4236 DeclarationNameInfo NameInfo;
4237
4238 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
4239 SS.Adopt(ArgExpr->getQualifierLoc());
4240 NameInfo = ArgExpr->getNameInfo();
4241 } else if (DependentScopeDeclRefExpr *ArgExpr =
4242 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4243 SS.Adopt(ArgExpr->getQualifierLoc());
4244 NameInfo = ArgExpr->getNameInfo();
4245 } else if (CXXDependentScopeMemberExpr *ArgExpr =
4246 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00004247 if (ArgExpr->isImplicitAccess()) {
4248 SS.Adopt(ArgExpr->getQualifierLoc());
4249 NameInfo = ArgExpr->getMemberNameInfo();
4250 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004251 }
4252
Reid Kleckner377c1592014-06-10 23:29:48 +00004253 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004254 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4255 LookupParsedName(Result, CurScope, &SS);
4256
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00004257 if (Result.getAsSingle<TypeDecl>() ||
4258 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00004259 LookupResult::NotFoundInCurrentInstantiation) {
4260 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004261 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00004262 Diag(Loc, getLangOpts().MSVCCompat
4263 ? diag::ext_ms_template_type_arg_missing_typename
4264 : diag::err_template_arg_must_be_type_suggest)
4265 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004266 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00004267
4268 // Recover by synthesizing a type using the location information that we
4269 // already have.
4270 ArgType =
4271 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
4272 TypeLocBuilder TLB;
4273 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
4274 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4275 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4276 TL.setNameLoc(NameInfo.getLoc());
4277 TSI = TLB.getTypeSourceInfo(Context, ArgType);
4278
4279 // Overwrite our input TemplateArgumentLoc so that we can recover
4280 // properly.
4281 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
4282 TemplateArgumentLocInfo(TSI));
4283
4284 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004285 }
4286 }
4287 // fallthrough
Galina Kistanova3779cb32017-06-07 06:25:05 +00004288 LLVM_FALLTHROUGH;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004289 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004290 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004291 // We have a template type parameter but the template argument
4292 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00004293 SourceRange SR = AL.getSourceRange();
4294 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004295 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00004296
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004297 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004298 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004299 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004300
Reid Kleckner377c1592014-06-10 23:29:48 +00004301 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004302 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004303
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004304 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00004305 ArgType = Context.getCanonicalType(ArgType);
Simon Pilgrim6905d222016-12-30 22:55:33 +00004306
Douglas Gregore46db902011-06-17 22:11:49 +00004307 // Objective-C ARC:
4308 // If an explicitly-specified template argument type is a lifetime type
4309 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004310 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00004311 ArgType->isObjCLifetimeType() &&
4312 !ArgType.getObjCLifetime()) {
4313 Qualifiers Qs;
4314 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
4315 ArgType = Context.getQualifiedType(ArgType, Qs);
4316 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00004317
Douglas Gregore46db902011-06-17 22:11:49 +00004318 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004319 return false;
4320}
4321
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004322/// \brief Substitute template arguments into the default template argument for
4323/// the given template type parameter.
4324///
4325/// \param SemaRef the semantic analysis object for which we are performing
4326/// the substitution.
4327///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004328/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004329/// for.
4330///
4331/// \param TemplateLoc the location of the template name that started the
4332/// template-id we are checking.
4333///
4334/// \param RAngleLoc the location of the right angle bracket ('>') that
4335/// terminates the template-id.
4336///
4337/// \param Param the template template parameter whose default we are
4338/// substituting into.
4339///
4340/// \param Converted the list of template arguments provided for template
4341/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004342/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00004343static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004344SubstDefaultTemplateArgument(Sema &SemaRef,
4345 TemplateDecl *Template,
4346 SourceLocation TemplateLoc,
4347 SourceLocation RAngleLoc,
4348 TemplateTypeParmDecl *Param,
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00004349 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00004350 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004351
4352 // If the argument type is dependent, instantiate it now based
4353 // on the previously-computed template arguments.
4354 if (ArgType->getType()->isDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004355 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00004356 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004357 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004358 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00004359 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004360
David Majnemer8b622692016-07-03 21:17:51 +00004361 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004362
4363 // Only substitute for the innermost template argument list.
4364 MultiLevelTemplateArgumentList TemplateArgLists;
4365 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4366 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4367 TemplateArgLists.addOuterTemplateArguments(None);
4368
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00004369 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00004370 ArgType =
4371 SemaRef.SubstType(ArgType, TemplateArgLists,
4372 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004373 }
4374
4375 return ArgType;
4376}
4377
4378/// \brief Substitute template arguments into the default template argument for
4379/// the given non-type template parameter.
4380///
4381/// \param SemaRef the semantic analysis object for which we are performing
4382/// the substitution.
4383///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004384/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004385/// for.
4386///
4387/// \param TemplateLoc the location of the template name that started the
4388/// template-id we are checking.
4389///
4390/// \param RAngleLoc the location of the right angle bracket ('>') that
4391/// terminates the template-id.
4392///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004393/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004394/// substituting into.
4395///
4396/// \param Converted the list of template arguments provided for template
4397/// parameters that precede \p Param in the template parameter list.
4398///
4399/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00004400static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004401SubstDefaultTemplateArgument(Sema &SemaRef,
4402 TemplateDecl *Template,
4403 SourceLocation TemplateLoc,
4404 SourceLocation RAngleLoc,
4405 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004406 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004407 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00004408 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004409 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004410 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004411 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004412
David Majnemer8b622692016-07-03 21:17:51 +00004413 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004414
4415 // Only substitute for the innermost template argument list.
4416 MultiLevelTemplateArgumentList TemplateArgLists;
4417 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4418 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4419 TemplateArgLists.addOuterTemplateArguments(None);
4420
Faisal Valid143a0c2017-04-01 21:30:49 +00004421 EnterExpressionEvaluationContext ConstantEvaluated(
4422 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00004423 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004424}
4425
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004426/// \brief Substitute template arguments into the default template argument for
4427/// the given template template parameter.
4428///
4429/// \param SemaRef the semantic analysis object for which we are performing
4430/// the substitution.
4431///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004432/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004433/// for.
4434///
4435/// \param TemplateLoc the location of the template name that started the
4436/// template-id we are checking.
4437///
4438/// \param RAngleLoc the location of the right angle bracket ('>') that
4439/// terminates the template-id.
4440///
4441/// \param Param the template template parameter whose default we are
4442/// substituting into.
4443///
4444/// \param Converted the list of template arguments provided for template
4445/// parameters that precede \p Param in the template parameter list.
4446///
Simon Pilgrim6905d222016-12-30 22:55:33 +00004447/// \param QualifierLoc Will be set to the nested-name-specifier (with
Douglas Gregordf846d12011-03-02 18:46:51 +00004448/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00004449///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004450/// \returns the substituted template argument, or NULL if an error occurred.
4451static TemplateName
4452SubstDefaultTemplateArgument(Sema &SemaRef,
4453 TemplateDecl *Template,
4454 SourceLocation TemplateLoc,
4455 SourceLocation RAngleLoc,
4456 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004457 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00004458 NestedNameSpecifierLoc &QualifierLoc) {
Richard Smith54f18e82016-08-31 02:15:21 +00004459 Sema::InstantiatingTemplate Inst(
4460 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
4461 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004462 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004463 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004464
David Majnemer8b622692016-07-03 21:17:51 +00004465 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004466
4467 // Only substitute for the innermost template argument list.
4468 MultiLevelTemplateArgumentList TemplateArgLists;
4469 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4470 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4471 TemplateArgLists.addOuterTemplateArguments(None);
4472
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00004473 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00004474 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00004475 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00004476 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00004477 QualifierLoc =
4478 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00004479 if (!QualifierLoc)
4480 return TemplateName();
4481 }
David Majnemer89189202013-08-28 23:48:32 +00004482
4483 return SemaRef.SubstTemplateName(
4484 QualifierLoc,
4485 Param->getDefaultArgument().getArgument().getAsTemplate(),
4486 Param->getDefaultArgument().getTemplateNameLoc(),
4487 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004488}
4489
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004490/// \brief If the given template parameter has a default template
4491/// argument, substitute into that default template argument and
4492/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004493TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004494Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
4495 SourceLocation TemplateLoc,
4496 SourceLocation RAngleLoc,
4497 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00004498 SmallVectorImpl<TemplateArgument>
4499 &Converted,
4500 bool &HasDefaultArg) {
4501 HasDefaultArg = false;
4502
4503 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004504 if (!hasVisibleDefaultArgument(TypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004505 return TemplateArgumentLoc();
4506
Richard Smithc87b9382013-07-04 01:01:24 +00004507 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00004508 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004509 TemplateLoc,
4510 RAngleLoc,
4511 TypeParm,
4512 Converted);
4513 if (DI)
4514 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4515
4516 return TemplateArgumentLoc();
4517 }
4518
4519 if (NonTypeTemplateParmDecl *NonTypeParm
4520 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004521 if (!hasVisibleDefaultArgument(NonTypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004522 return TemplateArgumentLoc();
4523
Richard Smithc87b9382013-07-04 01:01:24 +00004524 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00004525 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00004526 TemplateLoc,
4527 RAngleLoc,
4528 NonTypeParm,
4529 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004530 if (Arg.isInvalid())
4531 return TemplateArgumentLoc();
4532
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004533 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004534 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
4535 }
4536
4537 TemplateTemplateParmDecl *TempTempParm
4538 = cast<TemplateTemplateParmDecl>(Param);
Richard Smith95d83952015-06-10 20:36:34 +00004539 if (!hasVisibleDefaultArgument(TempTempParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004540 return TemplateArgumentLoc();
4541
Richard Smithc87b9382013-07-04 01:01:24 +00004542 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00004543 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004544 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004545 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004546 RAngleLoc,
4547 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00004548 Converted,
4549 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004550 if (TName.isNull())
4551 return TemplateArgumentLoc();
4552
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004553 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00004554 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004555 TempTempParm->getDefaultArgument().getTemplateNameLoc());
4556}
4557
Richard Smith11255ec2017-01-18 19:19:22 +00004558/// Convert a template-argument that we parsed as a type into a template, if
4559/// possible. C++ permits injected-class-names to perform dual service as
4560/// template template arguments and as template type arguments.
4561static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
4562 // Extract and step over any surrounding nested-name-specifier.
4563 NestedNameSpecifierLoc QualLoc;
4564 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4565 if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
4566 return TemplateArgumentLoc();
4567
4568 QualLoc = ETLoc.getQualifierLoc();
4569 TLoc = ETLoc.getNamedTypeLoc();
4570 }
4571
4572 // If this type was written as an injected-class-name, it can be used as a
4573 // template template argument.
4574 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4575 return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
4576 QualLoc, InjLoc.getNameLoc());
4577
4578 // If this type was written as an injected-class-name, it may have been
4579 // converted to a RecordType during instantiation. If the RecordType is
4580 // *not* wrapped in a TemplateSpecializationType and denotes a class
4581 // template specialization, it must have come from an injected-class-name.
4582 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
4583 if (auto *CTSD =
4584 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
4585 return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
4586 QualLoc, RecLoc.getNameLoc());
4587
4588 return TemplateArgumentLoc();
4589}
4590
Douglas Gregorda0fb532009-11-11 19:31:23 +00004591/// \brief Check that the given template argument corresponds to the given
4592/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004593///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004594/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004595/// checked.
4596///
Richard Trieu15b66532015-01-24 02:48:32 +00004597/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004598///
4599/// \param Template The template in which the template argument resides.
4600///
4601/// \param TemplateLoc The location of the template name for the template
4602/// whose argument list we're matching.
4603///
4604/// \param RAngleLoc The location of the right angle bracket ('>') that closes
4605/// the template argument list.
4606///
4607/// \param ArgumentPackIndex The index into the argument pack where this
4608/// argument will be placed. Only valid if the parameter is a parameter pack.
4609///
4610/// \param Converted The checked, converted argument will be added to the
4611/// end of this small vector.
4612///
4613/// \param CTAK Describes how we arrived at this particular template argument:
4614/// explicitly written, deduced, etc.
4615///
4616/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004617bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00004618 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00004619 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004620 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004621 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004622 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004623 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00004624 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00004625 // Check template type parameters.
4626 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004627 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004628
Douglas Gregoreebed722009-11-11 19:41:09 +00004629 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004630 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004631 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00004632 // with the template arguments we've seen thus far. But if the
4633 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004634 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004635 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
4636 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004637
Richard Smith5d331022018-03-08 01:07:33 +00004638 // FIXME: Do we need to substitute into parameters here if they're
4639 // instantiation-dependent but not dependent?
Peter Collingbourne01687632010-12-10 17:08:53 +00004640 if (NTTPType->isDependentType() &&
4641 !isa<TemplateTemplateParmDecl>(Template) &&
4642 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004643 // Do substitution on the type of the non-type template parameter.
4644 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00004645 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004646 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004647 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004648 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004649
4650 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00004651 Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004652 NTTPType = SubstType(NTTPType,
4653 MultiLevelTemplateArgumentList(TemplateArgs),
4654 NTTP->getLocation(),
4655 NTTP->getDeclName());
4656 // If that worked, check the non-type template parameter type
4657 // for validity.
4658 if (!NTTPType.isNull())
4659 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
4660 NTTP->getLocation());
4661 if (NTTPType.isNull())
4662 return true;
4663 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004664
Douglas Gregorda0fb532009-11-11 19:31:23 +00004665 switch (Arg.getArgument().getKind()) {
4666 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00004667 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004668
Douglas Gregorda0fb532009-11-11 19:31:23 +00004669 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004670 TemplateArgument Result;
John Wiegley01296292011-04-08 18:41:53 +00004671 ExprResult Res =
4672 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
4673 Result, CTAK);
4674 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00004675 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004676
Richard Trieu15b66532015-01-24 02:48:32 +00004677 // If the resulting expression is new, then use it in place of the
4678 // old expression in the template argument.
4679 if (Res.get() != Arg.getArgument().getAsExpr()) {
4680 TemplateArgument TA(Res.get());
4681 Arg = TemplateArgumentLoc(TA, Res.get());
4682 }
4683
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004684 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004685 break;
4686 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004687
Douglas Gregorda0fb532009-11-11 19:31:23 +00004688 case TemplateArgument::Declaration:
4689 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00004690 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00004691 // We've already checked this template argument, so just copy
4692 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004693 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00004694 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004695
Douglas Gregorda0fb532009-11-11 19:31:23 +00004696 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004697 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00004698 // We were given a template template argument. It may not be ill-formed;
4699 // see below.
4700 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004701 = Arg.getArgument().getAsTemplateOrTemplatePattern()
4702 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004703 // We have a template argument such as \c T::template X, which we
4704 // parsed as a template template argument. However, since we now
4705 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004706 // template name into an expression.
4707
4708 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
4709 Arg.getTemplateNameLoc());
4710
Douglas Gregor3a43fd62011-02-25 20:49:16 +00004711 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00004712 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00004713 // FIXME: the template-template arg was a DependentTemplateName,
4714 // so it was provided with a template keyword. However, its source
4715 // location is not stored in the template argument structure.
4716 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004717 ExprResult E = DependentScopeDeclRefExpr::Create(
4718 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
4719 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004720
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004721 // If we parsed the template argument as a pack expansion, create a
4722 // pack expansion expression.
4723 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004724 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00004725 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004726 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004727 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004728
Douglas Gregorda0fb532009-11-11 19:31:23 +00004729 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004730 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00004731 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00004732 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004733
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004734 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004735 break;
4736 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004737
Douglas Gregorda0fb532009-11-11 19:31:23 +00004738 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00004739 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00004740 // therefore cannot be a non-type template argument.
4741 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
4742 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004743
Douglas Gregorda0fb532009-11-11 19:31:23 +00004744 Diag(Param->getLocation(), diag::note_template_param_here);
4745 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004746
Douglas Gregorda0fb532009-11-11 19:31:23 +00004747 case TemplateArgument::Type: {
4748 // We have a non-type template parameter but the template
4749 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004750
Douglas Gregorda0fb532009-11-11 19:31:23 +00004751 // C++ [temp.arg]p2:
4752 // In a template-argument, an ambiguity between a type-id and
4753 // an expression is resolved to a type-id, regardless of the
4754 // form of the corresponding template-parameter.
4755 //
4756 // We warn specifically about this case, since it can be rather
4757 // confusing for users.
4758 QualType T = Arg.getArgument().getAsType();
4759 SourceRange SR = Arg.getSourceRange();
4760 if (T->isFunctionType())
4761 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
4762 else
4763 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
4764 Diag(Param->getLocation(), diag::note_template_param_here);
4765 return true;
4766 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004767
Douglas Gregorda0fb532009-11-11 19:31:23 +00004768 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004769 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004770 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004771
Douglas Gregorda0fb532009-11-11 19:31:23 +00004772 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004773 }
4774
4775
Douglas Gregorda0fb532009-11-11 19:31:23 +00004776 // Check template template parameters.
4777 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004778
Richard Smith5d331022018-03-08 01:07:33 +00004779 TemplateParameterList *Params = TempParm->getTemplateParameters();
4780 if (TempParm->isExpandedParameterPack())
4781 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
4782
Douglas Gregorda0fb532009-11-11 19:31:23 +00004783 // Substitute into the template parameter list of the template
4784 // template parameter, since previously-supplied template arguments
4785 // may appear within the template template parameter.
Richard Smith5d331022018-03-08 01:07:33 +00004786 //
4787 // FIXME: Skip this if the parameters aren't instantiation-dependent.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004788 {
4789 // Set up a template instantiation context.
4790 LocalInstantiationScope Scope(*this);
4791 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00004792 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004793 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004794 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004795 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004796
David Majnemer8b622692016-07-03 21:17:51 +00004797 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
Richard Smith5d331022018-03-08 01:07:33 +00004798 Params = SubstTemplateParams(Params, CurContext,
4799 MultiLevelTemplateArgumentList(TemplateArgs));
4800 if (!Params)
Douglas Gregorda0fb532009-11-11 19:31:23 +00004801 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00004802 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004803
Richard Smith11255ec2017-01-18 19:19:22 +00004804 // C++1z [temp.local]p1: (DR1004)
4805 // When [the injected-class-name] is used [...] as a template-argument for
4806 // a template template-parameter [...] it refers to the class template
4807 // itself.
4808 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
4809 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
4810 Arg.getTypeSourceInfo()->getTypeLoc());
4811 if (!ConvertedArg.getArgument().isNull())
4812 Arg = ConvertedArg;
4813 }
4814
Douglas Gregorda0fb532009-11-11 19:31:23 +00004815 switch (Arg.getArgument().getKind()) {
4816 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00004817 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004818
Douglas Gregorda0fb532009-11-11 19:31:23 +00004819 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004820 case TemplateArgument::TemplateExpansion:
Richard Smith5d331022018-03-08 01:07:33 +00004821 if (CheckTemplateTemplateArgument(Params, Arg))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004822 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004823
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004824 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00004825 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004826
Douglas Gregorda0fb532009-11-11 19:31:23 +00004827 case TemplateArgument::Expression:
4828 case TemplateArgument::Type:
4829 // We have a template template parameter but the template
4830 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004831 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004832 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00004833 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004834
Douglas Gregorda0fb532009-11-11 19:31:23 +00004835 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00004836 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004837 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00004838 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00004839 case TemplateArgument::NullPtr:
4840 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004841
Douglas Gregorda0fb532009-11-11 19:31:23 +00004842 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004843 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004844 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004845
Douglas Gregorda0fb532009-11-11 19:31:23 +00004846 return false;
4847}
4848
Simon Pilgrim6905d222016-12-30 22:55:33 +00004849/// \brief Diagnose an arity mismatch in the
Douglas Gregor8e072612012-02-03 07:34:46 +00004850static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
4851 SourceLocation TemplateLoc,
4852 TemplateArgumentListInfo &TemplateArgs) {
4853 TemplateParameterList *Params = Template->getTemplateParameters();
4854 unsigned NumParams = Params->size();
4855 unsigned NumArgs = TemplateArgs.size();
4856
4857 SourceRange Range;
4858 if (NumArgs > NumParams)
Simon Pilgrim6905d222016-12-30 22:55:33 +00004859 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
Douglas Gregor8e072612012-02-03 07:34:46 +00004860 TemplateArgs.getRAngleLoc());
4861 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4862 << (NumArgs > NumParams)
Richard Smith0c062b42017-01-14 02:19:59 +00004863 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(Template))
Douglas Gregor8e072612012-02-03 07:34:46 +00004864 << Template << Range;
4865 S.Diag(Template->getLocation(), diag::note_template_decl_here)
4866 << Params->getSourceRange();
4867 return true;
4868}
4869
Richard Smith1fde8ec2012-09-07 02:06:42 +00004870/// \brief Check whether the template parameter is a pack expansion, and if so,
4871/// determine the number of parameters produced by that expansion. For instance:
4872///
4873/// \code
4874/// template<typename ...Ts> struct A {
4875/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
4876/// };
4877/// \endcode
4878///
4879/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
4880/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00004881static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00004882 if (NonTypeTemplateParmDecl *NTTP
4883 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4884 if (NTTP->isExpandedParameterPack())
4885 return NTTP->getNumExpansionTypes();
4886 }
4887
4888 if (TemplateTemplateParmDecl *TTP
4889 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
4890 if (TTP->isExpandedParameterPack())
4891 return TTP->getNumExpansionTemplateParameters();
4892 }
4893
David Blaikie7a30dc52013-02-21 01:47:18 +00004894 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00004895}
4896
Richard Smith35c1df52015-06-17 20:16:32 +00004897/// Diagnose a missing template argument.
4898template<typename TemplateParmDecl>
4899static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
4900 TemplateDecl *TD,
4901 const TemplateParmDecl *D,
4902 TemplateArgumentListInfo &Args) {
4903 // Dig out the most recent declaration of the template parameter; there may be
4904 // declarations of the template that are more recent than TD.
4905 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
4906 ->getTemplateParameters()
4907 ->getParam(D->getIndex()));
4908
4909 // If there's a default argument that's not visible, diagnose that we're
4910 // missing a module import.
4911 llvm::SmallVector<Module*, 8> Modules;
4912 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
4913 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
4914 D->getDefaultArgumentLoc(), Modules,
4915 Sema::MissingImportKind::DefaultArgument,
Richard Smith6739a102016-05-05 00:56:12 +00004916 /*Recover*/true);
Richard Smith35c1df52015-06-17 20:16:32 +00004917 return true;
4918 }
4919
4920 // FIXME: If there's a more recent default argument that *is* visible,
4921 // diagnose that it was declared too late.
4922
4923 return diagnoseArityMismatch(S, TD, Loc, Args);
4924}
4925
Douglas Gregord32e0282009-02-09 23:23:08 +00004926/// \brief Check that the given template argument list is well-formed
4927/// for specializing the given template.
Richard Smith11255ec2017-01-18 19:19:22 +00004928bool Sema::CheckTemplateArgumentList(
4929 TemplateDecl *Template, SourceLocation TemplateLoc,
4930 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
4931 SmallVectorImpl<TemplateArgument> &Converted,
4932 bool UpdateArgsWithConversions) {
Richard Trieu15b66532015-01-24 02:48:32 +00004933 // Make a copy of the template arguments for processing. Only make the
4934 // changes at the end when successful in matching the arguments to the
4935 // template.
4936 TemplateArgumentListInfo NewArgs = TemplateArgs;
4937
Erich Keaneaf0795b2017-10-24 01:39:56 +00004938 // Make sure we get the template parameter list from the most
4939 // recentdeclaration, since that is the only one that has is guaranteed to
4940 // have all the default template argument information.
4941 TemplateParameterList *Params =
4942 cast<TemplateDecl>(Template->getMostRecentDecl())
4943 ->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00004944
Richard Trieu15b66532015-01-24 02:48:32 +00004945 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00004946
Mike Stump11289f42009-09-09 15:08:12 +00004947 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00004948 // [...] The type and form of each template-argument specified in
4949 // a template-id shall match the type and form specified for the
4950 // corresponding parameter declared by the template in its
4951 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00004952 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004953 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00004954 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00004955 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00004956 for (TemplateParameterList::iterator Param = Params->begin(),
4957 ParamEnd = Params->end();
4958 Param != ParamEnd; /* increment in loop */) {
4959 // If we have an expanded parameter pack, make sure we don't have too
4960 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00004961 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00004962 if (*Expansions == ArgumentPack.size()) {
4963 // We're done with this parameter pack. Pack up its arguments and add
4964 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00004965 Converted.push_back(
Benjamin Kramercce63472015-08-05 09:40:22 +00004966 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00004967 ArgumentPack.clear();
4968
Richard Smith1fde8ec2012-09-07 02:06:42 +00004969 // This argument is assigned to the next parameter.
4970 ++Param;
4971 continue;
4972 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
4973 // Not enough arguments for this parameter pack.
4974 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4975 << false
Richard Smith0c062b42017-01-14 02:19:59 +00004976 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
Richard Smith1fde8ec2012-09-07 02:06:42 +00004977 << Template;
4978 Diag(Template->getLocation(), diag::note_template_decl_here)
4979 << Params->getSourceRange();
4980 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004981 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00004982 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004983
Richard Smith1fde8ec2012-09-07 02:06:42 +00004984 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00004985 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00004986 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004987 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004988 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00004989 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004990
Richard Smith96d71c32014-11-12 23:38:38 +00004991 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00004992 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00004993 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
4994 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00004995 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00004996 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00004997 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00004998 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00004999 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00005000 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00005001 Diag((*Param)->getLocation(), diag::note_template_param_here);
5002 return true;
5003 }
5004
Richard Smith1fde8ec2012-09-07 02:06:42 +00005005 // We're now done with this argument.
5006 ++ArgIdx;
5007
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005008 if ((*Param)->isTemplateParameterPack()) {
5009 // The template parameter was a template parameter pack, so take the
5010 // deduced argument and place it on the argument pack. Note that we
5011 // stay on the same template parameter so that we can deduce more
5012 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00005013 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005014 } else {
5015 // Move to the next template parameter.
5016 ++Param;
5017 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00005018
Richard Smith96d71c32014-11-12 23:38:38 +00005019 // If we just saw a pack expansion into a non-pack, then directly convert
5020 // the remaining arguments, because we don't know what parameters they'll
5021 // match up with.
5022 if (PackExpansionIntoNonPack) {
5023 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00005024 // If we were part way through filling in an expanded parameter pack,
5025 // fall back to just producing individual arguments.
5026 Converted.insert(Converted.end(),
5027 ArgumentPack.begin(), ArgumentPack.end());
5028 ArgumentPack.clear();
5029 }
5030
5031 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00005032 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00005033 ++ArgIdx;
5034 }
5035
Richard Smith1fde8ec2012-09-07 02:06:42 +00005036 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00005037 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00005038
Douglas Gregor84d49a22009-11-11 21:54:23 +00005039 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005040 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005041
Douglas Gregor2f157c92011-06-03 02:59:40 +00005042 // If we're checking a partial template argument list, we're done.
5043 if (PartialTemplateArgs) {
5044 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
Benjamin Kramercce63472015-08-05 09:40:22 +00005045 Converted.push_back(
5046 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5047
Richard Smith1fde8ec2012-09-07 02:06:42 +00005048 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00005049 }
5050
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005051 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005052 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00005053 if ((*Param)->isTemplateParameterPack()) {
5054 assert(!getExpandedPackSize(*Param) &&
5055 "Should have dealt with this already");
5056
5057 // A non-expanded parameter pack before the end of the parameter list
5058 // only occurs for an ill-formed template parameter list, unless we've
5059 // got a partial argument list for a function template, so just bail out.
5060 if (Param + 1 != ParamEnd)
5061 return true;
5062
Benjamin Kramercce63472015-08-05 09:40:22 +00005063 Converted.push_back(
5064 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00005065 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00005066
5067 ++Param;
5068 continue;
5069 }
5070
Douglas Gregor8e072612012-02-03 07:34:46 +00005071 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00005072 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005073
Douglas Gregor84d49a22009-11-11 21:54:23 +00005074 // Retrieve the default template argument from the template
5075 // parameter. For each kind of template parameter, we substitute the
5076 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005077 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00005078 // the default argument.
5079 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00005080 if (!hasVisibleDefaultArgument(TTP))
Richard Smith35c1df52015-06-17 20:16:32 +00005081 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
5082 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005083
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005084 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00005085 Template,
5086 TemplateLoc,
5087 RAngleLoc,
5088 TTP,
5089 Converted);
5090 if (!ArgType)
5091 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005092
Douglas Gregor84d49a22009-11-11 21:54:23 +00005093 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
5094 ArgType);
5095 } else if (NonTypeTemplateParmDecl *NTTP
5096 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00005097 if (!hasVisibleDefaultArgument(NTTP))
Richard Smith35c1df52015-06-17 20:16:32 +00005098 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
5099 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005100
John McCalldadc5752010-08-24 06:29:42 +00005101 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005102 TemplateLoc,
5103 RAngleLoc,
5104 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00005105 Converted);
5106 if (E.isInvalid())
5107 return true;
5108
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005109 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00005110 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
5111 } else {
5112 TemplateTemplateParmDecl *TempParm
5113 = cast<TemplateTemplateParmDecl>(*Param);
5114
Richard Smith95d83952015-06-10 20:36:34 +00005115 if (!hasVisibleDefaultArgument(TempParm))
Richard Smith35c1df52015-06-17 20:16:32 +00005116 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
5117 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005118
Douglas Gregordf846d12011-03-02 18:46:51 +00005119 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00005120 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005121 TemplateLoc,
5122 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00005123 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00005124 Converted,
5125 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005126 if (Name.isNull())
5127 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005128
Douglas Gregor9d802122011-03-02 17:09:35 +00005129 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
5130 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00005131 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005132
Douglas Gregor84d49a22009-11-11 21:54:23 +00005133 // Introduce an instantiation record that describes where we are using
Richard Smith54f18e82016-08-31 02:15:21 +00005134 // the default template argument. We're not actually instantiating a
5135 // template here, we just create this object to put a note into the
5136 // context stack.
Alp Tokerd4a72d52013-10-08 08:09:04 +00005137 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
5138 SourceRange(TemplateLoc, RAngleLoc));
5139 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00005140 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005141
Douglas Gregor84d49a22009-11-11 21:54:23 +00005142 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00005143 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00005144 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00005145 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005146
Richard Trieu15b66532015-01-24 02:48:32 +00005147 // Core issue 150 (assumed resolution): if this is a template template
5148 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00005149 // template definition.
5150 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00005151 NewArgs.addArgument(Arg);
5152
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005153 // Move to the next template parameter and argument.
5154 ++Param;
5155 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00005156 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005157
Richard Smith07f79912014-06-06 16:00:50 +00005158 // If we're performing a partial argument substitution, allow any trailing
5159 // pack expansions; they might be empty. This can happen even if
5160 // PartialTemplateArgs is false (the list of arguments is complete but
5161 // still dependent).
5162 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5163 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00005164 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
5165 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00005166 }
5167
Douglas Gregor8e072612012-02-03 07:34:46 +00005168 // If we have any leftover arguments, then there were too many arguments.
5169 // Complain and fail.
5170 if (ArgIdx < NumArgs)
Richard Trieu15b66532015-01-24 02:48:32 +00005171 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
5172
5173 // No problems found with the new argument list, propagate changes back
5174 // to caller.
Richard Smith11255ec2017-01-18 19:19:22 +00005175 if (UpdateArgsWithConversions)
5176 TemplateArgs = std::move(NewArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005177
Richard Smith1fde8ec2012-09-07 02:06:42 +00005178 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00005179}
5180
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005181namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005182 class UnnamedLocalNoLinkageFinder
5183 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005184 {
5185 Sema &S;
5186 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005187
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005188 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005189
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005190 public:
5191 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5192
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005193 bool Visit(QualType T) {
Daniel Jasper5cad6852017-01-02 22:55:45 +00005194 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005195 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005196
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005197#define TYPE(Class, Parent) \
5198 bool Visit##Class##Type(const Class##Type *);
5199#define ABSTRACT_TYPE(Class, Parent) \
5200 bool Visit##Class##Type(const Class##Type *) { return false; }
5201#define NON_CANONICAL_TYPE(Class, Parent) \
5202 bool Visit##Class##Type(const Class##Type *) { return false; }
5203#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005204
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005205 bool VisitTagDecl(const TagDecl *Tag);
5206 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5207 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005208} // end anonymous namespace
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005209
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005210bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005211 return false;
5212}
5213
5214bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5215 return Visit(T->getElementType());
5216}
5217
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005218bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005219 return Visit(T->getPointeeType());
5220}
5221
5222bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005223 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005224 return Visit(T->getPointeeType());
5225}
5226
5227bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005228 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005229 return Visit(T->getPointeeType());
5230}
5231
5232bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005233 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005234 return Visit(T->getPointeeType());
5235}
5236
5237bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005238 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005239 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5240}
5241
5242bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005243 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005244 return Visit(T->getElementType());
5245}
5246
5247bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005248 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005249 return Visit(T->getElementType());
5250}
5251
5252bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005253 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005254 return Visit(T->getElementType());
5255}
5256
5257bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005258 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005259 return Visit(T->getElementType());
5260}
5261
5262bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005263 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005264 return Visit(T->getElementType());
5265}
5266
Andrew Gozillon572bbb02017-10-02 06:25:51 +00005267bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
5268 const DependentAddressSpaceType *T) {
5269 return Visit(T->getPointeeType());
5270}
5271
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005272bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5273 return Visit(T->getElementType());
5274}
5275
5276bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5277 return Visit(T->getElementType());
5278}
5279
5280bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5281 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005282 for (const auto &A : T->param_types()) {
5283 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005284 return true;
5285 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005286
Alp Toker314cc812014-01-25 16:55:45 +00005287 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005288}
5289
5290bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5291 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00005292 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005293}
5294
5295bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5296 const UnresolvedUsingType*) {
5297 return false;
5298}
5299
5300bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5301 return false;
5302}
5303
5304bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5305 return Visit(T->getUnderlyingType());
5306}
5307
5308bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5309 return false;
5310}
5311
Alexis Hunte852b102011-05-24 22:41:36 +00005312bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5313 const UnaryTransformType*) {
5314 return false;
5315}
5316
Richard Smith30482bc2011-02-20 03:19:35 +00005317bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5318 return Visit(T->getDeducedType());
5319}
5320
Richard Smith600b5262017-01-26 20:40:47 +00005321bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5322 const DeducedTemplateSpecializationType *T) {
5323 return Visit(T->getDeducedType());
5324}
5325
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005326bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5327 return VisitTagDecl(T->getDecl());
5328}
5329
5330bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5331 return VisitTagDecl(T->getDecl());
5332}
5333
5334bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5335 const TemplateTypeParmType*) {
5336 return false;
5337}
5338
Douglas Gregorada4b792011-01-14 02:55:32 +00005339bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5340 const SubstTemplateTypeParmPackType *) {
5341 return false;
5342}
5343
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005344bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
5345 const TemplateSpecializationType*) {
5346 return false;
5347}
5348
5349bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
5350 const InjectedClassNameType* T) {
5351 return VisitTagDecl(T->getDecl());
5352}
5353
5354bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
5355 const DependentNameType* T) {
5356 return VisitNestedNameSpecifier(T->getQualifier());
5357}
5358
5359bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
5360 const DependentTemplateSpecializationType* T) {
5361 return VisitNestedNameSpecifier(T->getQualifier());
5362}
5363
Douglas Gregord2fa7662010-12-20 02:24:11 +00005364bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
5365 const PackExpansionType* T) {
5366 return Visit(T->getPattern());
5367}
5368
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005369bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5370 return false;
5371}
5372
5373bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
5374 const ObjCInterfaceType *) {
5375 return false;
5376}
5377
5378bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
5379 const ObjCObjectPointerType *) {
5380 return false;
5381}
5382
Eli Friedman0dfb8892011-10-06 23:00:33 +00005383bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
5384 return Visit(T->getValueType());
5385}
5386
Xiuli Pan9c14e282016-01-09 12:53:17 +00005387bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
5388 return false;
5389}
5390
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005391bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
5392 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005393 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005394 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00005395 diag::warn_cxx98_compat_template_arg_local_type :
5396 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005397 << S.Context.getTypeDeclType(Tag) << SR;
5398 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005399 }
5400
John McCall5ea95772013-03-09 00:54:27 +00005401 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005402 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005403 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00005404 diag::warn_cxx98_compat_template_arg_unnamed_type :
5405 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005406 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
5407 return true;
5408 }
5409
5410 return false;
5411}
5412
5413bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5414 NestedNameSpecifier *NNS) {
5415 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5416 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005417
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005418 switch (NNS->getKind()) {
5419 case NestedNameSpecifier::Identifier:
5420 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005421 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005422 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00005423 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005424 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005425
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005426 case NestedNameSpecifier::TypeSpec:
5427 case NestedNameSpecifier::TypeSpecWithTemplate:
5428 return Visit(QualType(NNS->getAsType(), 0));
5429 }
David Blaikie8a40f702012-01-17 06:56:22 +00005430 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005431}
5432
Douglas Gregord32e0282009-02-09 23:23:08 +00005433/// \brief Check a template argument against its corresponding
5434/// template type parameter.
5435///
5436/// This routine implements the semantics of C++ [temp.arg.type]. It
5437/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005438bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00005439 TypeSourceInfo *ArgInfo) {
5440 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00005441 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00005442 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00005443
5444 if (Arg->isVariablyModifiedType()) {
5445 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005446 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005447 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00005448 }
5449
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005450 // C++03 [temp.arg.type]p2:
5451 // A local type, a type with no linkage, an unnamed type or a type
5452 // compounded from any of these types shall not be used as a
5453 // template-argument for a template type-parameter.
5454 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00005455 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005456 // a warning.
Daniel Jasper5cad6852017-01-02 22:55:45 +00005457 if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005458 UnnamedLocalNoLinkageFinder Finder(*this, SR);
5459 (void)Finder.Visit(Context.getCanonicalType(Arg));
5460 }
5461
Douglas Gregord32e0282009-02-09 23:23:08 +00005462 return false;
5463}
5464
Douglas Gregor20fdef32012-04-10 17:08:25 +00005465enum NullPointerValueKind {
5466 NPV_NotNullPointer,
5467 NPV_NullPointer,
5468 NPV_Error
5469};
5470
5471/// \brief Determine whether the given template argument is a null pointer
5472/// value of the appropriate type.
5473static NullPointerValueKind
5474isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
Reid Klecknercd016d82017-07-07 22:04:29 +00005475 QualType ParamType, Expr *Arg,
5476 Decl *Entity = nullptr) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00005477 if (Arg->isValueDependent() || Arg->isTypeDependent())
5478 return NPV_NotNullPointer;
David Majnemer69c3ddc2015-09-11 20:18:09 +00005479
Reid Klecknercd016d82017-07-07 22:04:29 +00005480 // dllimport'd entities aren't constant but are available inside of template
5481 // arguments.
5482 if (Entity && Entity->hasAttr<DLLImportAttr>())
5483 return NPV_NotNullPointer;
5484
Richard Smithdb0ac552015-12-18 22:40:25 +00005485 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
David Majnemerb54368c2015-09-11 20:55:29 +00005486 llvm_unreachable(
5487 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
David Majnemer69c3ddc2015-09-11 20:18:09 +00005488
David Majnemer5c734ad2014-08-14 00:49:23 +00005489 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00005490 return NPV_NotNullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005491
Douglas Gregor20fdef32012-04-10 17:08:25 +00005492 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00005493 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
5494 if (ArgRV.isInvalid())
5495 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005496 Arg = ArgRV.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005497
Douglas Gregor20fdef32012-04-10 17:08:25 +00005498 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005499 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00005500 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005501 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00005502 EvalResult.HasSideEffects) {
5503 SourceLocation DiagLoc = Arg->getExprLoc();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005504
Douglas Gregor350880c2012-04-10 19:03:30 +00005505 // If our only note is the usual "invalid subexpression" note, just point
5506 // the caret at its location rather than producing an essentially
5507 // redundant note.
5508 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5509 diag::note_invalid_subexpr_in_const_expr) {
5510 DiagLoc = Notes[0].first;
5511 Notes.clear();
5512 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005513
Douglas Gregor350880c2012-04-10 19:03:30 +00005514 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5515 << Arg->getType() << Arg->getSourceRange();
5516 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5517 S.Diag(Notes[I].first, Notes[I].second);
Simon Pilgrim6905d222016-12-30 22:55:33 +00005518
Douglas Gregor350880c2012-04-10 19:03:30 +00005519 S.Diag(Param->getLocation(), diag::note_template_param_here);
5520 return NPV_Error;
5521 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005522
Douglas Gregor20fdef32012-04-10 17:08:25 +00005523 // C++11 [temp.arg.nontype]p1:
5524 // - an address constant expression of type std::nullptr_t
5525 if (Arg->getType()->isNullPtrType())
5526 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005527
Douglas Gregor20fdef32012-04-10 17:08:25 +00005528 // - a constant expression that evaluates to a null pointer value (4.10); or
5529 // - a constant expression that evaluates to a null member pointer value
5530 // (4.11); or
5531 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
5532 (EvalResult.Val.isMemberPointer() &&
5533 !EvalResult.Val.getMemberPointerDecl())) {
5534 // If our expression has an appropriate type, we've succeeded.
5535 bool ObjCLifetimeConversion;
5536 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5537 S.IsQualificationConversion(Arg->getType(), ParamType, false,
5538 ObjCLifetimeConversion))
5539 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005540
Douglas Gregor20fdef32012-04-10 17:08:25 +00005541 // The types didn't match, but we know we got a null pointer; complain,
5542 // then recover as if the types were correct.
5543 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
5544 << Arg->getType() << ParamType << Arg->getSourceRange();
5545 S.Diag(Param->getLocation(), diag::note_template_param_here);
5546 return NPV_NullPointer;
5547 }
5548
5549 // If we don't have a null pointer value, but we do have a NULL pointer
5550 // constant, suggest a cast to the appropriate type.
5551 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
5552 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
5553 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Alp Tokerb6cc5922014-05-03 03:45:55 +00005554 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
5555 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
5556 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00005557 S.Diag(Param->getLocation(), diag::note_template_param_here);
5558 return NPV_NullPointer;
5559 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005560
Douglas Gregor20fdef32012-04-10 17:08:25 +00005561 // FIXME: If we ever want to support general, address-constant expressions
5562 // as non-type template arguments, we should return the ExprResult here to
5563 // be interpreted by the caller.
5564 return NPV_NotNullPointer;
5565}
5566
David Majnemer61c39a12013-08-23 05:39:39 +00005567/// \brief Checks whether the given template argument is compatible with its
5568/// template parameter.
5569static bool CheckTemplateArgumentIsCompatibleWithParameter(
5570 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
5571 Expr *Arg, QualType ArgType) {
5572 bool ObjCLifetimeConversion;
5573 if (ParamType->isPointerType() &&
5574 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
5575 S.IsQualificationConversion(ArgType, ParamType, false,
5576 ObjCLifetimeConversion)) {
5577 // For pointer-to-object types, qualification conversions are
5578 // permitted.
5579 } else {
5580 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
5581 if (!ParamRef->getPointeeType()->isFunctionType()) {
5582 // C++ [temp.arg.nontype]p5b3:
5583 // For a non-type template-parameter of type reference to
5584 // object, no conversions apply. The type referred to by the
5585 // reference may be more cv-qualified than the (otherwise
5586 // identical) type of the template- argument. The
5587 // template-parameter is bound directly to the
5588 // template-argument, which shall be an lvalue.
5589
5590 // FIXME: Other qualifiers?
5591 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
5592 unsigned ArgQuals = ArgType.getCVRQualifiers();
5593
5594 if ((ParamQuals | ArgQuals) != ParamQuals) {
5595 S.Diag(Arg->getLocStart(),
5596 diag::err_template_arg_ref_bind_ignores_quals)
5597 << ParamType << Arg->getType() << Arg->getSourceRange();
5598 S.Diag(Param->getLocation(), diag::note_template_param_here);
5599 return true;
5600 }
5601 }
5602 }
5603
5604 // At this point, the template argument refers to an object or
5605 // function with external linkage. We now need to check whether the
5606 // argument and parameter types are compatible.
5607 if (!S.Context.hasSameUnqualifiedType(ArgType,
5608 ParamType.getNonReferenceType())) {
5609 // We can't perform this conversion or binding.
5610 if (ParamType->isReferenceType())
5611 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
5612 << ParamType << ArgIn->getType() << Arg->getSourceRange();
5613 else
5614 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
5615 << ArgIn->getType() << ParamType << Arg->getSourceRange();
5616 S.Diag(Param->getLocation(), diag::note_template_param_here);
5617 return true;
5618 }
5619 }
5620
5621 return false;
5622}
5623
Douglas Gregorccb07762009-02-11 19:52:55 +00005624/// \brief Checks whether the given template argument is the address
5625/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005626static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00005627CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
5628 NonTypeTemplateParmDecl *Param,
5629 QualType ParamType,
5630 Expr *ArgIn,
5631 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005632 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005633 Expr *Arg = ArgIn;
5634 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00005635
Douglas Gregorb242683d2010-04-01 18:32:35 +00005636 bool AddressTaken = false;
5637 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00005638 if (S.getLangOpts().MicrosoftExt) {
5639 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
5640 // dereference and address-of operators.
5641 Arg = Arg->IgnoreParenCasts();
5642
5643 bool ExtWarnMSTemplateArg = false;
5644 UnaryOperatorKind FirstOpKind;
5645 SourceLocation FirstOpLoc;
5646 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5647 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
5648 if (UnOpKind == UO_Deref)
5649 ExtWarnMSTemplateArg = true;
5650 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
5651 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
5652 if (!AddrOpLoc.isValid()) {
5653 FirstOpKind = UnOpKind;
5654 FirstOpLoc = UnOp->getOperatorLoc();
5655 }
5656 } else
5657 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005658 }
David Majnemer61c39a12013-08-23 05:39:39 +00005659 if (FirstOpLoc.isValid()) {
5660 if (ExtWarnMSTemplateArg)
5661 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
5662 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00005663
David Majnemer61c39a12013-08-23 05:39:39 +00005664 if (FirstOpKind == UO_AddrOf)
5665 AddressTaken = true;
5666 else if (Arg->getType()->isPointerType()) {
5667 // We cannot let pointers get dereferenced here, that is obviously not a
5668 // constant expression.
5669 assert(FirstOpKind == UO_Deref);
5670 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5671 << Arg->getSourceRange();
5672 }
5673 }
5674 } else {
5675 // See through any implicit casts we added to fix the type.
5676 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00005677
David Majnemer61c39a12013-08-23 05:39:39 +00005678 // C++ [temp.arg.nontype]p1:
5679 //
5680 // A template-argument for a non-type, non-template
5681 // template-parameter shall be one of: [...]
5682 //
5683 // -- the address of an object or function with external
5684 // linkage, including function templates and function
5685 // template-ids but excluding non-static class members,
5686 // expressed as & id-expression where the & is optional if
5687 // the name refers to a function or array, or if the
5688 // corresponding template-parameter is a reference; or
5689
5690 // In C++98/03 mode, give an extension warning on any extra parentheses.
5691 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5692 bool ExtraParens = false;
5693 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5694 if (!Invalid && !ExtraParens) {
5695 S.Diag(Arg->getLocStart(),
5696 S.getLangOpts().CPlusPlus11
5697 ? diag::warn_cxx98_compat_template_arg_extra_parens
5698 : diag::ext_template_arg_extra_parens)
5699 << Arg->getSourceRange();
5700 ExtraParens = true;
5701 }
5702
5703 Arg = Parens->getSubExpr();
5704 }
5705
5706 while (SubstNonTypeTemplateParmExpr *subst =
5707 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5708 Arg = subst->getReplacement()->IgnoreImpCasts();
5709
5710 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5711 if (UnOp->getOpcode() == UO_AddrOf) {
5712 Arg = UnOp->getSubExpr();
5713 AddressTaken = true;
5714 AddrOpLoc = UnOp->getOperatorLoc();
5715 }
5716 }
5717
5718 while (SubstNonTypeTemplateParmExpr *subst =
5719 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5720 Arg = subst->getReplacement()->IgnoreImpCasts();
5721 }
John McCall7c454bb2011-07-15 05:09:51 +00005722
David Majnemer07910d62014-06-26 07:48:46 +00005723 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
5724 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5725
5726 // If our parameter has pointer type, check for a null template value.
5727 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
Reid Klecknercd016d82017-07-07 22:04:29 +00005728 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
5729 Entity)) {
David Majnemer07910d62014-06-26 07:48:46 +00005730 case NPV_NullPointer:
5731 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005732 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5733 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00005734 return false;
5735
5736 case NPV_Error:
5737 return true;
5738
5739 case NPV_NotNullPointer:
5740 break;
5741 }
5742 }
5743
Chandler Carruth724a8a12010-01-31 10:01:20 +00005744 // Stop checking the precise nature of the argument if it is value dependent,
5745 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00005746 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005747 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00005748 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005749 }
David Majnemer61c39a12013-08-23 05:39:39 +00005750
5751 if (isa<CXXUuidofExpr>(Arg)) {
5752 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
5753 ArgIn, Arg, ArgType))
5754 return true;
5755
5756 Converted = TemplateArgument(ArgIn);
5757 return false;
5758 }
5759
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005760 if (!DRE) {
5761 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5762 << Arg->getSourceRange();
5763 S.Diag(Param->getLocation(), diag::note_template_param_here);
5764 return true;
5765 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00005766
Douglas Gregorccb07762009-02-11 19:52:55 +00005767 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00005768 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005769 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
David Majnemer6bedcfa2013-10-26 06:12:44 +00005770 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005771 S.Diag(Param->getLocation(), diag::note_template_param_here);
5772 return true;
5773 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005774
5775 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00005776 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005777 if (!Method->isStatic()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005778 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00005779 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005780 S.Diag(Param->getLocation(), diag::note_template_param_here);
5781 return true;
5782 }
Richard Smith9380e0e2012-04-04 21:11:30 +00005783 }
Mike Stump11289f42009-09-09 15:08:12 +00005784
Richard Smith9380e0e2012-04-04 21:11:30 +00005785 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
5786 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00005787
Richard Smith9380e0e2012-04-04 21:11:30 +00005788 // A non-type template argument must refer to an object or function.
5789 if (!Func && !Var) {
5790 // We found something, but we don't know specifically what it is.
5791 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
5792 << Arg->getSourceRange();
5793 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
5794 return true;
5795 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005796
Richard Smith9380e0e2012-04-04 21:11:30 +00005797 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00005798 if (Entity->getFormalLinkage() == InternalLinkage) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005799 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
Richard Smith9380e0e2012-04-04 21:11:30 +00005800 diag::warn_cxx98_compat_template_arg_object_internal :
5801 diag::ext_template_arg_object_internal)
5802 << !Func << Entity << Arg->getSourceRange();
5803 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5804 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00005805 } else if (!Entity->hasLinkage()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00005806 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
5807 << !Func << Entity << Arg->getSourceRange();
5808 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5809 << !Func;
5810 return true;
5811 }
5812
5813 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005814 // If the template parameter has pointer type, the function decays.
5815 if (ParamType->isPointerType() && !AddressTaken)
5816 ArgType = S.Context.getPointerType(Func->getType());
5817 else if (AddressTaken && ParamType->isReferenceType()) {
5818 // If we originally had an address-of operator, but the
5819 // parameter has reference type, complain and (if things look
5820 // like they will work) drop the address-of operator.
5821 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
5822 ParamType.getNonReferenceType())) {
5823 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5824 << ParamType;
5825 S.Diag(Param->getLocation(), diag::note_template_param_here);
5826 return true;
5827 }
5828
5829 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5830 << ParamType
5831 << FixItHint::CreateRemoval(AddrOpLoc);
5832 S.Diag(Param->getLocation(), diag::note_template_param_here);
5833
5834 ArgType = Func->getType();
5835 }
Richard Smith9380e0e2012-04-04 21:11:30 +00005836 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005837 // A value of reference type is not an object.
5838 if (Var->getType()->isReferenceType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005839 S.Diag(Arg->getLocStart(),
Douglas Gregorb242683d2010-04-01 18:32:35 +00005840 diag::err_template_arg_reference_var)
5841 << Var->getType() << Arg->getSourceRange();
5842 S.Diag(Param->getLocation(), diag::note_template_param_here);
5843 return true;
5844 }
5845
Richard Smith9380e0e2012-04-04 21:11:30 +00005846 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00005847 if (Var->getTLSKind()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00005848 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
5849 << Arg->getSourceRange();
5850 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
5851 return true;
5852 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00005853
5854 // If the template parameter has pointer type, we must have taken
5855 // the address of this object.
5856 if (ParamType->isReferenceType()) {
5857 if (AddressTaken) {
5858 // If we originally had an address-of operator, but the
5859 // parameter has reference type, complain and (if things look
5860 // like they will work) drop the address-of operator.
5861 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
5862 ParamType.getNonReferenceType())) {
5863 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5864 << ParamType;
5865 S.Diag(Param->getLocation(), diag::note_template_param_here);
5866 return true;
5867 }
5868
5869 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5870 << ParamType
5871 << FixItHint::CreateRemoval(AddrOpLoc);
5872 S.Diag(Param->getLocation(), diag::note_template_param_here);
5873
5874 ArgType = Var->getType();
5875 }
5876 } else if (!AddressTaken && ParamType->isPointerType()) {
5877 if (Var->getType()->isArrayType()) {
5878 // Array-to-pointer decay.
5879 ArgType = S.Context.getArrayDecayedType(Var->getType());
5880 } else {
5881 // If the template parameter has pointer type but the address of
5882 // this object was not taken, complain and (possibly) recover by
5883 // taking the address of the entity.
5884 ArgType = S.Context.getPointerType(Var->getType());
5885 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
5886 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5887 << ParamType;
5888 S.Diag(Param->getLocation(), diag::note_template_param_here);
5889 return true;
5890 }
5891
5892 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5893 << ParamType
5894 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
5895
5896 S.Diag(Param->getLocation(), diag::note_template_param_here);
5897 }
5898 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005899 }
Mike Stump11289f42009-09-09 15:08:12 +00005900
David Majnemer61c39a12013-08-23 05:39:39 +00005901 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
5902 Arg, ArgType))
5903 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005904
5905 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00005906 Converted =
5907 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Nick Lewycky45b50522013-02-02 00:25:55 +00005908 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00005909 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00005910}
5911
5912/// \brief Checks whether the given template argument is a pointer to
5913/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00005914static bool CheckTemplateArgumentPointerToMember(Sema &S,
5915 NonTypeTemplateParmDecl *Param,
5916 QualType ParamType,
5917 Expr *&ResultArg,
5918 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005919 bool Invalid = false;
5920
Douglas Gregor20fdef32012-04-10 17:08:25 +00005921 Expr *Arg = ResultArg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005922 bool ObjCLifetimeConversion;
Douglas Gregorccb07762009-02-11 19:52:55 +00005923
5924 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00005925 //
Douglas Gregorccb07762009-02-11 19:52:55 +00005926 // A template-argument for a non-type, non-template
5927 // template-parameter shall be one of: [...]
5928 //
5929 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00005930 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00005931
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00005932 // In C++98/03 mode, give an extension warning on any extra parentheses.
5933 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5934 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00005935 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005936 if (!Invalid && !ExtraParens) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00005937 S.Diag(Arg->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005938 S.getLangOpts().CPlusPlus11 ?
Douglas Gregor20fdef32012-04-10 17:08:25 +00005939 diag::warn_cxx98_compat_template_arg_extra_parens :
5940 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00005941 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00005942 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00005943 }
5944
5945 Arg = Parens->getSubExpr();
5946 }
5947
John McCall7c454bb2011-07-15 05:09:51 +00005948 while (SubstNonTypeTemplateParmExpr *subst =
5949 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5950 Arg = subst->getReplacement()->IgnoreImpCasts();
5951
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005952 // A pointer-to-member constant written &Class::member.
5953 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00005954 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005955 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
5956 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00005957 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005958 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005959 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005960 // A constant of pointer-to-member type.
5961 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00005962 ValueDecl *VD = DRE->getDecl();
5963 if (VD->getType()->isMemberPointerType()) {
5964 if (isa<NonTypeTemplateParmDecl>(VD)) {
5965 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5966 Converted = TemplateArgument(Arg);
5967 } else {
5968 VD = cast<ValueDecl>(VD->getCanonicalDecl());
5969 Converted = TemplateArgument(VD, ParamType);
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005970 }
George Burgess IV00f70bd2018-03-01 05:43:23 +00005971 return Invalid;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005972 }
5973 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005974
Craig Topperc3ec1492014-05-26 06:22:03 +00005975 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005976 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005977
Reid Klecknercd016d82017-07-07 22:04:29 +00005978 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5979
5980 // Check for a null pointer value.
5981 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
5982 Entity)) {
5983 case NPV_Error:
5984 return true;
5985 case NPV_NullPointer:
5986 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5987 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5988 /*isNullPtr*/true);
5989 return false;
5990 case NPV_NotNullPointer:
5991 break;
5992 }
5993
5994 if (S.IsQualificationConversion(ResultArg->getType(),
5995 ParamType.getNonReferenceType(), false,
5996 ObjCLifetimeConversion)) {
5997 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
5998 ResultArg->getValueKind())
5999 .get();
6000 } else if (!S.Context.hasSameUnqualifiedType(
6001 ResultArg->getType(), ParamType.getNonReferenceType())) {
6002 // We can't perform this conversion.
6003 S.Diag(ResultArg->getLocStart(), diag::err_template_arg_not_convertible)
6004 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
6005 S.Diag(Param->getLocation(), diag::note_template_param_here);
6006 return true;
6007 }
6008
Douglas Gregorccb07762009-02-11 19:52:55 +00006009 if (!DRE)
Douglas Gregor20fdef32012-04-10 17:08:25 +00006010 return S.Diag(Arg->getLocStart(),
6011 diag::err_template_arg_not_pointer_to_member_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00006012 << Arg->getSourceRange();
6013
David Majnemer3ac84e62013-10-22 21:56:38 +00006014 if (isa<FieldDecl>(DRE->getDecl()) ||
6015 isa<IndirectFieldDecl>(DRE->getDecl()) ||
6016 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00006017 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00006018 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00006019 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
6020 "Only non-static member pointers can make it here");
6021
6022 // Okay: this is the address of a non-static member, and therefore
6023 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00006024 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00006025 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00006026 } else {
6027 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00006028 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00006029 }
Douglas Gregorccb07762009-02-11 19:52:55 +00006030 return Invalid;
6031 }
6032
6033 // We found something else, but we don't know specifically what it is.
Douglas Gregor20fdef32012-04-10 17:08:25 +00006034 S.Diag(Arg->getLocStart(),
6035 diag::err_template_arg_not_pointer_to_member_form)
6036 << Arg->getSourceRange();
6037 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00006038 return true;
6039}
6040
Douglas Gregord32e0282009-02-09 23:23:08 +00006041/// \brief Check a template argument against its corresponding
6042/// non-type template parameter.
6043///
Douglas Gregor463421d2009-03-03 04:44:36 +00006044/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00006045/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00006046/// returns the converted template argument. \p ParamType is the
6047/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00006048ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00006049 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00006050 TemplateArgument &Converted,
6051 CheckTemplateArgumentKind CTAK) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006052 SourceLocation StartLoc = Arg->getLocStart();
Douglas Gregorc40290e2009-03-09 23:48:35 +00006053
Richard Smith5f274382016-09-28 23:55:27 +00006054 // If the parameter type somehow involves auto, deduce the type now.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00006055 if (getLangOpts().CPlusPlus17 && ParamType->isUndeducedType()) {
Richard Smith4ae5ec82017-02-22 20:01:55 +00006056 // During template argument deduction, we allow 'decltype(auto)' to
6057 // match an arbitrary dependent argument.
6058 // FIXME: The language rules don't say what happens in this case.
6059 // FIXME: We get an opaque dependent type out of decltype(auto) if the
6060 // expression is merely instantiation-dependent; is this enough?
6061 if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
6062 auto *AT = dyn_cast<AutoType>(ParamType);
6063 if (AT && AT->isDecltypeAuto()) {
6064 Converted = TemplateArgument(Arg);
6065 return Arg;
6066 }
6067 }
6068
Richard Smith87d263e2016-12-25 08:05:23 +00006069 // When checking a deduced template argument, deduce from its type even if
6070 // the type is dependent, in order to check the types of non-type template
6071 // arguments line up properly in partial ordering.
6072 Optional<unsigned> Depth;
6073 if (CTAK != CTAK_Specified)
6074 Depth = Param->getDepth() + 1;
Richard Smith5f274382016-09-28 23:55:27 +00006075 if (DeduceAutoType(
6076 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
Richard Smith87d263e2016-12-25 08:05:23 +00006077 Arg, ParamType, Depth) == DAR_Failed) {
Richard Smith5f274382016-09-28 23:55:27 +00006078 Diag(Arg->getExprLoc(),
6079 diag::err_non_type_template_parm_type_deduction_failure)
6080 << Param->getDeclName() << Param->getType() << Arg->getType()
6081 << Arg->getSourceRange();
6082 Diag(Param->getLocation(), diag::note_template_param_here);
6083 return ExprError();
6084 }
6085 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
6086 // an error. The error message normally references the parameter
6087 // declaration, but here we'll pass the argument location because that's
6088 // where the parameter type is deduced.
6089 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
6090 if (ParamType.isNull()) {
6091 Diag(Param->getLocation(), diag::note_template_param_here);
6092 return ExprError();
6093 }
6094 }
6095
Richard Smithd663fdd2014-12-17 20:42:37 +00006096 // We should have already dropped all cv-qualifiers by now.
6097 assert(!ParamType.hasQualifiers() &&
6098 "non-type template parameter type cannot be qualified");
6099
6100 if (CTAK == CTAK_Deduced &&
Richard Smithd92eddf2016-12-27 06:14:37 +00006101 !Context.hasSameType(ParamType.getNonLValueExprType(Context),
Richard Smith0e617ec2016-12-27 07:56:27 +00006102 Arg->getType())) {
Richard Smith957fbf12017-01-17 02:14:37 +00006103 // FIXME: If either type is dependent, we skip the check. This isn't
6104 // correct, since during deduction we're supposed to have replaced each
6105 // template parameter with some unique (non-dependent) placeholder.
6106 // FIXME: If the argument type contains 'auto', we carry on and fail the
6107 // type check in order to force specific types to be more specialized than
6108 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
6109 // work.
6110 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
6111 !Arg->getType()->getContainedAutoType()) {
6112 Converted = TemplateArgument(Arg);
6113 return Arg;
6114 }
6115 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
6116 // we should actually be checking the type of the template argument in P,
6117 // not the type of the template argument deduced from A, against the
6118 // template parameter type.
Richard Smithd663fdd2014-12-17 20:42:37 +00006119 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
Richard Smith0e617ec2016-12-27 07:56:27 +00006120 << Arg->getType()
Richard Smithd663fdd2014-12-17 20:42:37 +00006121 << ParamType.getUnqualifiedType();
6122 Diag(Param->getLocation(), diag::note_template_param_here);
6123 return ExprError();
6124 }
6125
Richard Smith87d263e2016-12-25 08:05:23 +00006126 // If either the parameter has a dependent type or the argument is
6127 // type-dependent, there's nothing we can check now.
6128 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
6129 // FIXME: Produce a cloned, canonical expression?
6130 Converted = TemplateArgument(Arg);
6131 return Arg;
6132 }
6133
Richard Smithe5945872017-01-06 22:52:53 +00006134 // The initialization of the parameter from the argument is
6135 // a constant-evaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006136 EnterExpressionEvaluationContext ConstantEvaluated(
6137 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Richard Smithe5945872017-01-06 22:52:53 +00006138
Aaron Ballmanc351fba2017-12-04 20:27:34 +00006139 if (getLangOpts().CPlusPlus17) {
6140 // C++17 [temp.arg.nontype]p1:
Richard Smith410cc892014-11-26 03:26:53 +00006141 // A template-argument for a non-type template parameter shall be
6142 // a converted constant expression of the type of the template-parameter.
6143 APValue Value;
6144 ExprResult ArgResult = CheckConvertedConstantExpression(
6145 Arg, ParamType, Value, CCEK_TemplateArg);
6146 if (ArgResult.isInvalid())
6147 return ExprError();
6148
Richard Smith52e624f2016-12-21 21:42:57 +00006149 // For a value-dependent argument, CheckConvertedConstantExpression is
6150 // permitted (and expected) to be unable to determine a value.
6151 if (ArgResult.get()->isValueDependent()) {
Richard Smith01bfa682016-12-27 02:02:09 +00006152 Converted = TemplateArgument(ArgResult.get());
6153 return ArgResult;
Richard Smith52e624f2016-12-21 21:42:57 +00006154 }
6155
Richard Smithd663fdd2014-12-17 20:42:37 +00006156 QualType CanonParamType = Context.getCanonicalType(ParamType);
6157
Richard Smith410cc892014-11-26 03:26:53 +00006158 // Convert the APValue to a TemplateArgument.
6159 switch (Value.getKind()) {
6160 case APValue::Uninitialized:
6161 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00006162 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00006163 break;
6164 case APValue::Int:
6165 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00006166 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00006167 break;
6168 case APValue::MemberPointer: {
6169 assert(ParamType->isMemberPointerType());
6170
6171 // FIXME: We need TemplateArgument representation and mangling for these.
6172 if (!Value.getMemberPointerPath().empty()) {
6173 Diag(Arg->getLocStart(),
6174 diag::err_template_arg_member_ptr_base_derived_not_supported)
6175 << Value.getMemberPointerDecl() << ParamType
6176 << Arg->getSourceRange();
6177 return ExprError();
6178 }
6179
6180 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00006181 Converted = VD ? TemplateArgument(VD, CanonParamType)
6182 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00006183 break;
6184 }
6185 case APValue::LValue: {
6186 // For a non-type template-parameter of pointer or reference type,
6187 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00006188 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
6189 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00006190 // -- a temporary object
6191 // -- a string literal
6192 // -- the result of a typeid expression, or
Eric Christopher0d2c56a2017-03-31 01:45:39 +00006193 // -- a predefined __func__ variable
Richard Smith410cc892014-11-26 03:26:53 +00006194 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
6195 if (isa<CXXUuidofExpr>(E)) {
6196 Converted = TemplateArgument(const_cast<Expr*>(E));
6197 break;
6198 }
6199 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
6200 << Arg->getSourceRange();
6201 return ExprError();
6202 }
6203 auto *VD = const_cast<ValueDecl *>(
6204 Value.getLValueBase().dyn_cast<const ValueDecl *>());
6205 // -- a subobject
6206 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
6207 VD && VD->getType()->isArrayType() &&
6208 Value.getLValuePath()[0].ArrayIndex == 0 &&
6209 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
6210 // Per defect report (no number yet):
6211 // ... other than a pointer to the first element of a complete array
6212 // object.
6213 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
6214 Value.isLValueOnePastTheEnd()) {
6215 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
6216 << Value.getAsString(Context, ParamType);
6217 return ExprError();
6218 }
Richard Smithd663fdd2014-12-17 20:42:37 +00006219 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00006220 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00006221 assert((!VD || !ParamType->isNullPtrType()) &&
6222 "non-null value of type nullptr_t?");
6223 Converted = VD ? TemplateArgument(VD, CanonParamType)
6224 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00006225 break;
6226 }
6227 case APValue::AddrLabelDiff:
6228 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
6229 case APValue::Float:
6230 case APValue::ComplexInt:
6231 case APValue::ComplexFloat:
6232 case APValue::Vector:
6233 case APValue::Array:
6234 case APValue::Struct:
6235 case APValue::Union:
6236 llvm_unreachable("invalid kind for template argument");
6237 }
6238
6239 return ArgResult.get();
6240 }
6241
Douglas Gregor86560402009-02-10 23:36:10 +00006242 // C++ [temp.arg.nontype]p5:
6243 // The following conversions are performed on each expression used
6244 // as a non-type template-argument. If a non-type
6245 // template-argument cannot be converted to the type of the
6246 // corresponding template-parameter then the program is
6247 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00006248 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00006249 // C++11:
6250 // -- for a non-type template-parameter of integral or
6251 // enumeration type, conversions permitted in a converted
6252 // constant expression are applied.
6253 //
6254 // C++98:
6255 // -- for a non-type template-parameter of integral or
6256 // enumeration type, integral promotions (4.5) and integral
6257 // conversions (4.7) are applied.
6258
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006259 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00006260 // C++ [temp.arg.nontype]p1:
6261 // A template-argument for a non-type, non-template template-parameter
6262 // shall be one of:
6263 //
6264 // -- for a non-type template-parameter of integral or enumeration
6265 // type, a converted constant expression of the type of the
6266 // template-parameter; or
6267 llvm::APSInt Value;
6268 ExprResult ArgResult =
6269 CheckConvertedConstantExpression(Arg, ParamType, Value,
6270 CCEK_TemplateArg);
6271 if (ArgResult.isInvalid())
6272 return ExprError();
6273
Richard Smith01bfa682016-12-27 02:02:09 +00006274 // We can't check arbitrary value-dependent arguments.
6275 if (ArgResult.get()->isValueDependent()) {
6276 Converted = TemplateArgument(ArgResult.get());
6277 return ArgResult;
6278 }
6279
Richard Smithf8379a02012-01-18 23:55:52 +00006280 // Widen the argument value to sizeof(parameter type). This is almost
6281 // always a no-op, except when the parameter type is bool. In
6282 // that case, this may extend the argument from 1 bit to 8 bits.
6283 QualType IntegerType = ParamType;
6284 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6285 IntegerType = Enum->getDecl()->getIntegerType();
6286 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
6287
Benjamin Kramer6003ad52012-06-07 15:09:51 +00006288 Converted = TemplateArgument(Context, Value,
6289 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00006290 return ArgResult;
6291 }
6292
Richard Smith08b12f12011-10-27 22:11:44 +00006293 ExprResult ArgResult = DefaultLvalueConversion(Arg);
6294 if (ArgResult.isInvalid())
6295 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006296 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00006297
6298 QualType ArgType = Arg->getType();
6299
Douglas Gregor86560402009-02-10 23:36:10 +00006300 // C++ [temp.arg.nontype]p1:
6301 // A template-argument for a non-type, non-template
6302 // template-parameter shall be one of:
6303 //
6304 // -- an integral constant-expression of integral or enumeration
6305 // type; or
6306 // -- the name of a non-type template-parameter; or
Douglas Gregor264ec4f2009-02-17 01:05:43 +00006307 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00006308 if (!ArgType->isIntegralOrEnumerationType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006309 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00006310 diag::err_template_arg_not_integral_or_enumeral)
6311 << ArgType << Arg->getSourceRange();
6312 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00006313 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00006314 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00006315 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
6316 QualType T;
Simon Pilgrim6905d222016-12-30 22:55:33 +00006317
Douglas Gregore2b37442012-05-04 22:38:52 +00006318 public:
6319 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00006320
6321 void diagnoseNotICE(Sema &S, SourceLocation Loc,
6322 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00006323 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
6324 }
6325 } Diagnoser(ArgType);
6326
6327 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006328 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00006329 if (!Arg)
6330 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00006331 }
6332
Richard Smithd663fdd2014-12-17 20:42:37 +00006333 // From here on out, all we care about is the unqualified form
6334 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006335 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00006336
6337 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00006338 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00006339 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00006340 } else if (ParamType->isBooleanType()) {
6341 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006342 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00006343 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
6344 !ParamType->isEnumeralType()) {
6345 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006346 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00006347 } else {
6348 // We can't perform this conversion.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006349 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00006350 diag::err_template_arg_not_convertible)
Richard Smithd663fdd2014-12-17 20:42:37 +00006351 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00006352 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00006353 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00006354 }
6355
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006356 // Add the value of this argument to the list of converted
6357 // arguments. We use the bitwidth and signedness of the template
6358 // parameter.
6359 if (Arg->isValueDependent()) {
6360 // The argument is value-dependent. Create a new
6361 // TemplateArgument with the converted expression.
6362 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006363 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006364 }
6365
Douglas Gregor52aba872009-03-14 00:20:21 +00006366 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00006367 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00006368 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00006369
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006370 if (ParamType->isBooleanType()) {
6371 // Value must be zero or one.
6372 Value = Value != 0;
6373 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6374 if (Value.getBitWidth() != AllowedBits)
6375 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006376 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006377 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006378 llvm::APSInt OldValue = Value;
Simon Pilgrim6905d222016-12-30 22:55:33 +00006379
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006380 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006381 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00006382 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00006383 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006384 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006385 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Simon Pilgrim6905d222016-12-30 22:55:33 +00006386
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006387 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006388 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006389 && (OldValue.isSigned() && OldValue.isNegative())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006390 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006391 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6392 << Arg->getSourceRange();
6393 Diag(Param->getLocation(), diag::note_template_param_here);
6394 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006395
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006396 // Complain if we overflowed the template parameter's type.
6397 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006398 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006399 RequiredBits = OldValue.getActiveBits();
6400 else if (OldValue.isUnsigned())
6401 RequiredBits = OldValue.getActiveBits() + 1;
6402 else
6403 RequiredBits = OldValue.getMinSignedBits();
6404 if (RequiredBits > AllowedBits) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006405 Diag(Arg->getLocStart(),
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006406 diag::warn_template_arg_too_large)
6407 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6408 << Arg->getSourceRange();
6409 Diag(Param->getLocation(), diag::note_template_param_here);
6410 }
Douglas Gregor52aba872009-03-14 00:20:21 +00006411 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00006412
Benjamin Kramer6003ad52012-06-07 15:09:51 +00006413 Converted = TemplateArgument(Context, Value,
Simon Pilgrim6905d222016-12-30 22:55:33 +00006414 ParamType->isEnumeralType()
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00006415 ? Context.getCanonicalType(ParamType)
6416 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006417 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00006418 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006419
Richard Smith08b12f12011-10-27 22:11:44 +00006420 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00006421 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
6422
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006423 // Handle pointer-to-function, reference-to-function, and
6424 // pointer-to-member-function all in (roughly) the same way.
6425 if (// -- For a non-type template-parameter of type pointer to
6426 // function, only the function-to-pointer conversion (4.3) is
6427 // applied. If the template-argument represents a set of
6428 // overloaded functions (or a pointer to such), the matching
6429 // function is selected from the set (13.4).
6430 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006431 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006432 // -- For a non-type template-parameter of type reference to
6433 // function, no conversions apply. If the template-argument
6434 // represents a set of overloaded functions, the matching
6435 // function is selected from the set (13.4).
6436 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006437 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006438 // -- For a non-type template-parameter of type pointer to
6439 // member function, no conversions apply. If the
6440 // template-argument represents a set of overloaded member
6441 // functions, the matching member function is selected from
6442 // the set (13.4).
6443 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006444 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006445 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006446
Douglas Gregor064fdb22010-04-14 23:11:21 +00006447 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006448 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00006449 true,
6450 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006451 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00006452 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00006453
6454 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6455 ArgType = Arg->getType();
6456 } else
John Wiegley01296292011-04-08 18:41:53 +00006457 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006458 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006459
John Wiegley01296292011-04-08 18:41:53 +00006460 if (!ParamType->isMemberPointerType()) {
6461 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6462 ParamType,
6463 Arg, Converted))
6464 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006465 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00006466 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00006467
Douglas Gregor20fdef32012-04-10 17:08:25 +00006468 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6469 Converted))
John Wiegley01296292011-04-08 18:41:53 +00006470 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006471 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006472 }
6473
Chris Lattner696197c2009-02-20 21:37:53 +00006474 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006475 // -- for a non-type template-parameter of type pointer to
6476 // object, qualification conversions (4.4) and the
6477 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00006478 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00006479 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006480 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00006481
John Wiegley01296292011-04-08 18:41:53 +00006482 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6483 ParamType,
6484 Arg, Converted))
6485 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006486 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00006487 }
Mike Stump11289f42009-09-09 15:08:12 +00006488
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006489 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006490 // -- For a non-type template-parameter of type reference to
6491 // object, no conversions apply. The type referred to by the
6492 // reference may be more cv-qualified than the (otherwise
6493 // identical) type of the template-argument. The
6494 // template-parameter is bound directly to the
6495 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00006496 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006497 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00006498
Douglas Gregor064fdb22010-04-14 23:11:21 +00006499 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006500 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
6501 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00006502 true,
6503 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006504 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00006505 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00006506
6507 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6508 ArgType = Arg->getType();
6509 } else
John Wiegley01296292011-04-08 18:41:53 +00006510 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006511 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006512
John Wiegley01296292011-04-08 18:41:53 +00006513 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6514 ParamType,
6515 Arg, Converted))
6516 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006517 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006518 }
Douglas Gregor0e558532009-02-11 16:16:59 +00006519
Douglas Gregor20fdef32012-04-10 17:08:25 +00006520 // Deal with parameters of type std::nullptr_t.
6521 if (ParamType->isNullPtrType()) {
6522 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6523 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006524 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006525 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006526
Douglas Gregor20fdef32012-04-10 17:08:25 +00006527 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
6528 case NPV_NotNullPointer:
6529 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
6530 << Arg->getType() << ParamType;
6531 Diag(Param->getLocation(), diag::note_template_param_here);
6532 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00006533
Douglas Gregor20fdef32012-04-10 17:08:25 +00006534 case NPV_Error:
6535 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00006536
Douglas Gregor20fdef32012-04-10 17:08:25 +00006537 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00006538 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00006539 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
6540 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006541 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006542 }
6543 }
6544
Douglas Gregor0e558532009-02-11 16:16:59 +00006545 // -- For a non-type template-parameter of type pointer to data
6546 // member, qualification conversions (4.4) are applied.
6547 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
6548
Douglas Gregor20fdef32012-04-10 17:08:25 +00006549 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6550 Converted))
John Wiegley01296292011-04-08 18:41:53 +00006551 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006552 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00006553}
6554
Richard Smith26b86ea2016-12-31 21:41:23 +00006555static void DiagnoseTemplateParameterListArityMismatch(
6556 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
6557 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
6558
Douglas Gregord32e0282009-02-09 23:23:08 +00006559/// \brief Check a template argument against its corresponding
6560/// template template parameter.
6561///
6562/// This routine implements the semantics of C++ [temp.arg.template].
6563/// It returns true if an error occurred, and false otherwise.
Richard Smith5d331022018-03-08 01:07:33 +00006564bool Sema::CheckTemplateTemplateArgument(TemplateParameterList *Params,
6565 TemplateArgumentLoc &Arg) {
Eli Friedmanb826a002012-09-26 02:36:12 +00006566 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006567 TemplateDecl *Template = Name.getAsTemplateDecl();
6568 if (!Template) {
6569 // Any dependent template name is fine.
6570 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
6571 return false;
6572 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00006573
Richard Smith26b86ea2016-12-31 21:41:23 +00006574 if (Template->isInvalidDecl())
6575 return true;
6576
Richard Smith3f1b5d02011-05-05 21:57:07 +00006577 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00006578 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00006579 // the name of a class template or an alias template, expressed as an
6580 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00006581 // primary class templates are considered when matching the
6582 // template template argument with the corresponding parameter;
6583 // partial specializations are not considered even if their
6584 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00006585 //
6586 // Note that we also allow template template parameters here, which
6587 // will happen when we are dealing with, e.g., class template
6588 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00006589 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00006590 !isa<TemplateTemplateParmDecl>(Template) &&
David Majnemerc2406d42016-07-11 17:09:56 +00006591 !isa<TypeAliasTemplateDecl>(Template) &&
6592 !isa<BuiltinTemplateDecl>(Template)) {
6593 assert(isa<FunctionTemplateDecl>(Template) &&
6594 "Only function templates are possible here");
Faisal Valib8b04f82016-03-26 20:46:45 +00006595 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
David Majnemerc2406d42016-07-11 17:09:56 +00006596 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
6597 << Template;
Douglas Gregor85e0f662009-02-10 00:24:35 +00006598 }
6599
Richard Smith26b86ea2016-12-31 21:41:23 +00006600 // C++1z [temp.arg.template]p3: (DR 150)
6601 // A template-argument matches a template template-parameter P when P
6602 // is at least as specialized as the template-argument A.
6603 if (getLangOpts().RelaxedTemplateTemplateArgs) {
6604 // Quick check for the common case:
6605 // If P contains a parameter pack, then A [...] matches P if each of A's
6606 // template parameters matches the corresponding template parameter in
6607 // the template-parameter-list of P.
6608 if (TemplateParameterListsAreEqual(
6609 Template->getTemplateParameters(), Params, false,
6610 TPL_TemplateTemplateArgumentMatch, Arg.getLocation()))
6611 return false;
6612
6613 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
6614 Arg.getLocation()))
6615 return false;
6616 // FIXME: Produce better diagnostics for deduction failures.
6617 }
6618
Douglas Gregor85e0f662009-02-10 00:24:35 +00006619 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00006620 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006621 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006622 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006623 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00006624}
6625
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006626/// \brief Given a non-type template argument that refers to a
6627/// declaration and the type of its corresponding non-type template
6628/// parameter, produce an expression that properly refers to that
6629/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006630ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006631Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6632 QualType ParamType,
6633 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00006634 // C++ [temp.param]p8:
6635 //
6636 // A non-type template-parameter of type "array of T" or
6637 // "function returning T" is adjusted to be of type "pointer to
6638 // T" or "pointer to function returning T", respectively.
6639 if (ParamType->isArrayType())
6640 ParamType = Context.getArrayDecayedType(ParamType);
6641 else if (ParamType->isFunctionType())
6642 ParamType = Context.getPointerType(ParamType);
6643
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006644 // For a NULL non-type template argument, return nullptr casted to the
6645 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00006646 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006647 return ImpCastExprToType(
6648 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
6649 ParamType,
6650 ParamType->getAs<MemberPointerType>()
6651 ? CK_NullToMemberPointer
6652 : CK_NullToPointer);
6653 }
Eli Friedmanb826a002012-09-26 02:36:12 +00006654 assert(Arg.getKind() == TemplateArgument::Declaration &&
6655 "Only declaration template arguments permitted here");
6656
George Burgess IV00f70bd2018-03-01 05:43:23 +00006657 ValueDecl *VD = Arg.getAsDecl();
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006658
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006659 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00006660 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
6661 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006662 // If the value is a class member, we might have a pointer-to-member.
6663 // Determine whether the non-type template template parameter is of
6664 // pointer-to-member type. If so, we need to build an appropriate
6665 // expression for a pointer-to-member, since a "normal" DeclRefExpr
6666 // would refer to the member itself.
6667 if (ParamType->isMemberPointerType()) {
6668 QualType ClassType
6669 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
6670 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00006671 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00006672 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006673 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00006674 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00006675
6676 // The actual value-ness of this is unimportant, but for
6677 // internal consistency's sake, references to instance methods
6678 // are r-values.
6679 ExprValueKind VK = VK_LValue;
6680 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
6681 VK = VK_RValue;
6682
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006683 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00006684 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00006685 VK,
John McCall7decc9e2010-11-18 06:31:45 +00006686 Loc,
6687 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006688 if (RefExpr.isInvalid())
6689 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006690
John McCalle3027922010-08-25 11:45:40 +00006691 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006692
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006693 // We might need to perform a trailing qualification conversion, since
6694 // the element type on the parameter could be more qualified than the
6695 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00006696 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006697 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00006698 ParamType.getUnqualifiedType(), false,
6699 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006700 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006701
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006702 assert(!RefExpr.isInvalid() &&
6703 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006704 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006705 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006706 }
6707 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006708
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006709 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00006710
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006711 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006712 // When the non-type template parameter is a pointer, take the
6713 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00006714 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006715 if (RefExpr.isInvalid())
6716 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006717
Richard Smithfc6fca12017-01-28 00:38:35 +00006718 if (!Context.hasSameUnqualifiedType(ParamType->getPointeeType(), T) &&
6719 (T->isFunctionType() || T->isArrayType())) {
6720 // Decay functions and arrays unless we're forming a pointer to array.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006721 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00006722 if (RefExpr.isInvalid())
6723 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006724
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006725 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006726 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006727
Douglas Gregorb242683d2010-04-01 18:32:35 +00006728 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00006729 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006730 }
6731
John McCall7decc9e2010-11-18 06:31:45 +00006732 ExprValueKind VK = VK_RValue;
6733
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006734 // If the non-type template parameter has reference type, qualify the
6735 // resulting declaration reference with the extra qualifiers on the
6736 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00006737 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
6738 VK = VK_LValue;
6739 T = Context.getQualifiedType(T,
6740 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00006741 } else if (isa<FunctionDecl>(VD)) {
6742 // References to functions are always lvalues.
6743 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00006744 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006745
John McCall7decc9e2010-11-18 06:31:45 +00006746 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006747}
6748
6749/// \brief Construct a new expression that refers to the given
6750/// integral template argument with the given source-location
6751/// information.
6752///
6753/// This routine takes care of the mapping from an integral template
6754/// argument (which may have any integral type) to the appropriate
6755/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006756ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006757Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6758 SourceLocation Loc) {
6759 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00006760 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006761 QualType OrigT = Arg.getIntegralType();
6762
6763 // If this is an enum type that we're instantiating, we need to use an integer
6764 // type the same size as the enumerator. We don't want to build an
6765 // IntegerLiteral with enum type. The integer type of an enum type can be of
6766 // any integral type with C++11 enum classes, make sure we create the right
6767 // type of literal for it.
6768 QualType T = OrigT;
6769 if (const EnumType *ET = OrigT->getAs<EnumType>())
6770 T = ET->getDecl()->getIntegerType();
6771
6772 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00006773 if (T->isAnyCharacterType()) {
Aaron Ballman9a17c852016-01-07 20:59:26 +00006774 // This does not need to handle u8 character literals because those are
6775 // of type char, and so can also be covered by an ASCII character literal.
Douglas Gregorfb65e592011-07-27 05:40:30 +00006776 CharacterLiteral::CharacterKind Kind;
6777 if (T->isWideCharType())
6778 Kind = CharacterLiteral::Wide;
6779 else if (T->isChar16Type())
6780 Kind = CharacterLiteral::UTF16;
6781 else if (T->isChar32Type())
6782 Kind = CharacterLiteral::UTF32;
6783 else
6784 Kind = CharacterLiteral::Ascii;
6785
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006786 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
6787 Kind, T, Loc);
6788 } else if (T->isBooleanType()) {
6789 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
6790 T, Loc);
6791 } else if (T->isNullPtrType()) {
6792 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
6793 } else {
6794 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00006795 }
6796
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006797 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00006798 // FIXME: This is a hack. We need a better way to handle substituted
6799 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00006800 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
6801 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006802 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00006803 Loc, Loc);
6804 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006805
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006806 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006807}
6808
Douglas Gregor641040a2011-01-12 23:45:44 +00006809/// \brief Match two template parameters within template parameter lists.
6810static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
6811 bool Complain,
6812 Sema::TemplateParameterListEqualKind Kind,
6813 SourceLocation TemplateArgLoc) {
6814 // Check the actual kind (type, non-type, template).
6815 if (Old->getKind() != New->getKind()) {
6816 if (Complain) {
6817 unsigned NextDiag = diag::err_template_param_different_kind;
6818 if (TemplateArgLoc.isValid()) {
6819 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6820 NextDiag = diag::note_template_param_different_kind;
6821 }
6822 S.Diag(New->getLocation(), NextDiag)
6823 << (Kind != Sema::TPL_TemplateMatch);
6824 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
6825 << (Kind != Sema::TPL_TemplateMatch);
6826 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006827
Douglas Gregor641040a2011-01-12 23:45:44 +00006828 return false;
6829 }
6830
Richard Smith26b86ea2016-12-31 21:41:23 +00006831 // Check that both are parameter packs or neither are parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006832 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006833 // template template parameter, the template template parameter can have
6834 // a parameter pack where the template template argument does not.
6835 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
6836 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
6837 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00006838 if (Complain) {
6839 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
6840 if (TemplateArgLoc.isValid()) {
6841 S.Diag(TemplateArgLoc,
6842 diag::err_template_arg_template_params_mismatch);
6843 NextDiag = diag::note_template_parameter_pack_non_pack;
6844 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006845
Douglas Gregor641040a2011-01-12 23:45:44 +00006846 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
6847 : isa<NonTypeTemplateParmDecl>(New)? 1
6848 : 2;
6849 S.Diag(New->getLocation(), NextDiag)
6850 << ParamKind << New->isParameterPack();
6851 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
6852 << ParamKind << Old->isParameterPack();
6853 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006854
Douglas Gregor641040a2011-01-12 23:45:44 +00006855 return false;
6856 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006857
Douglas Gregor641040a2011-01-12 23:45:44 +00006858 // For non-type template parameters, check the type of the parameter.
6859 if (NonTypeTemplateParmDecl *OldNTTP
6860 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
6861 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006862
Douglas Gregor641040a2011-01-12 23:45:44 +00006863 // If we are matching a template template argument to a template
6864 // template parameter and one of the non-type template parameter types
Richard Smith13894182017-04-13 21:37:24 +00006865 // is dependent, then we must wait until template instantiation time
6866 // to actually compare the arguments.
Douglas Gregor641040a2011-01-12 23:45:44 +00006867 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
Richard Smith13894182017-04-13 21:37:24 +00006868 (OldNTTP->getType()->isDependentType() ||
6869 NewNTTP->getType()->isDependentType()))
Douglas Gregor641040a2011-01-12 23:45:44 +00006870 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006871
Douglas Gregor641040a2011-01-12 23:45:44 +00006872 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
6873 if (Complain) {
6874 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
6875 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006876 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00006877 diag::err_template_arg_template_params_mismatch);
6878 NextDiag = diag::note_template_nontype_parm_different_type;
6879 }
6880 S.Diag(NewNTTP->getLocation(), NextDiag)
6881 << NewNTTP->getType()
6882 << (Kind != Sema::TPL_TemplateMatch);
6883 S.Diag(OldNTTP->getLocation(),
6884 diag::note_template_nontype_parm_prev_declaration)
6885 << OldNTTP->getType();
6886 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006887
Douglas Gregor641040a2011-01-12 23:45:44 +00006888 return false;
6889 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006890
Douglas Gregor641040a2011-01-12 23:45:44 +00006891 return true;
6892 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006893
Douglas Gregor641040a2011-01-12 23:45:44 +00006894 // For template template parameters, check the template parameter types.
6895 // The template parameter lists of template template
6896 // parameters must agree.
6897 if (TemplateTemplateParmDecl *OldTTP
6898 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006899 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00006900 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
6901 OldTTP->getTemplateParameters(),
6902 Complain,
6903 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006904 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00006905 : Kind),
6906 TemplateArgLoc);
6907 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006908
Douglas Gregor641040a2011-01-12 23:45:44 +00006909 return true;
6910}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006911
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006912/// \brief Diagnose a known arity mismatch when comparing template argument
6913/// lists.
6914static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006915void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006916 TemplateParameterList *New,
6917 TemplateParameterList *Old,
6918 Sema::TemplateParameterListEqualKind Kind,
6919 SourceLocation TemplateArgLoc) {
6920 unsigned NextDiag = diag::err_template_param_list_different_arity;
6921 if (TemplateArgLoc.isValid()) {
6922 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6923 NextDiag = diag::note_template_param_list_different_arity;
6924 }
6925 S.Diag(New->getTemplateLoc(), NextDiag)
6926 << (New->size() > Old->size())
6927 << (Kind != Sema::TPL_TemplateMatch)
6928 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
6929 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
6930 << (Kind != Sema::TPL_TemplateMatch)
6931 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
6932}
6933
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006934/// \brief Determine whether the given template parameter lists are
6935/// equivalent.
6936///
Mike Stump11289f42009-09-09 15:08:12 +00006937/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006938/// source code as part of a new template declaration.
6939///
6940/// \param Old The old template parameter list, typically found via
6941/// name lookup of the template declared with this template parameter
6942/// list.
6943///
6944/// \param Complain If true, this routine will produce a diagnostic if
6945/// the template parameter lists are not equivalent.
6946///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006947/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00006948///
6949/// \param TemplateArgLoc If this source location is valid, then we
6950/// are actually checking the template parameter list of a template
6951/// argument (New) against the template parameter list of its
6952/// corresponding template template parameter (Old). We produce
6953/// slightly different diagnostics in this scenario.
6954///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006955/// \returns True if the template parameter lists are equal, false
6956/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00006957bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006958Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
6959 TemplateParameterList *Old,
6960 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006961 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00006962 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006963 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
6964 if (Complain)
6965 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6966 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006967
6968 return false;
6969 }
6970
Douglas Gregor641040a2011-01-12 23:45:44 +00006971 // C++0x [temp.arg.template]p3:
6972 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00006973 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00006974 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00006975 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006976 // template-parameter-list of P. [...]
6977 TemplateParameterList::iterator NewParm = New->begin();
6978 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006979 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006980 OldParmEnd = Old->end();
6981 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00006982 if (Kind != TPL_TemplateTemplateArgumentMatch ||
6983 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006984 if (NewParm == NewParmEnd) {
6985 if (Complain)
6986 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6987 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006988
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006989 return false;
6990 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006991
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006992 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6993 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006994 return false;
6995
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006996 ++NewParm;
6997 continue;
6998 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006999
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007000 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00007001 // [...] When P's template- parameter-list contains a template parameter
7002 // pack (14.5.3), the template parameter pack will match zero or more
7003 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007004 // template-parameter-list of A with the same type and form as the
7005 // template parameter pack in P (ignoring whether those template
7006 // parameters are template parameter packs).
7007 for (; NewParm != NewParmEnd; ++NewParm) {
7008 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
7009 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007010 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007011 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007012 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007013
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007014 // Make sure we exhausted all of the arguments.
7015 if (NewParm != NewParmEnd) {
7016 if (Complain)
7017 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7018 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007019
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007020 return false;
7021 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007022
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007023 return true;
7024}
7025
7026/// \brief Check whether a template can be declared within this scope.
7027///
7028/// If the template declaration is valid in this scope, returns
7029/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00007030bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007031Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00007032 if (!S)
7033 return false;
7034
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007035 // Find the nearest enclosing declaration scope.
7036 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7037 (S->getFlags() & Scope::TemplateParamScope) != 0)
7038 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00007039
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00007040 // C++ [temp]p4:
7041 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007042 DeclContext *Ctx = S->getEntity();
Alex Lorenz560ae562016-11-02 15:46:34 +00007043 if (Ctx && Ctx->isExternCContext()) {
7044 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
7045 << TemplateParams->getSourceRange();
7046 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
7047 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
7048 return true;
7049 }
Richard Smith8df390f2016-09-08 23:14:54 +00007050 Ctx = Ctx->getRedeclContext();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007051
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00007052 // C++ [temp]p2:
7053 // A template-declaration can appear only as a namespace scope or
7054 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00007055 if (Ctx) {
7056 if (Ctx->isFileContext())
7057 return false;
7058 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
7059 // C++ [temp.mem]p2:
7060 // A local class shall not have member templates.
7061 if (RD->isLocalClass())
7062 return Diag(TemplateParams->getTemplateLoc(),
7063 diag::err_template_inside_local_class)
7064 << TemplateParams->getSourceRange();
7065 else
7066 return false;
7067 }
7068 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007069
Mike Stump11289f42009-09-09 15:08:12 +00007070 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007071 diag::err_template_outside_namespace_or_class_scope)
7072 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007073}
Douglas Gregor67a65642009-02-17 23:15:12 +00007074
Douglas Gregor54888652009-10-07 00:13:32 +00007075/// \brief Determine what kind of template specialization the given declaration
7076/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007077static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00007078 if (!D)
7079 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007080
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007081 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
7082 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00007083 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
7084 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007085 if (VarDecl *Var = dyn_cast<VarDecl>(D))
7086 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007087
Douglas Gregor54888652009-10-07 00:13:32 +00007088 return TSK_Undeclared;
7089}
7090
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007091/// \brief Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007092/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00007093///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007094/// This routine determines whether a template specialization can be declared
7095/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00007096///
7097/// \param S the semantic analysis object for which this check is being
7098/// performed.
7099///
7100/// \param Specialized the entity being specialized or instantiated, which
7101/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007102/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00007103/// member class).
7104///
7105/// \param PrevDecl the previous declaration of this entity, if any.
7106///
7107/// \param Loc the location of the explicit specialization or instantiation of
7108/// this entity.
7109///
7110/// \param IsPartialSpecialization whether this is a partial specialization of
7111/// a class template.
7112///
Douglas Gregor54888652009-10-07 00:13:32 +00007113/// \returns true if there was an error that we cannot recover from, false
7114/// otherwise.
7115static bool CheckTemplateSpecializationScope(Sema &S,
7116 NamedDecl *Specialized,
7117 NamedDecl *PrevDecl,
7118 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007119 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00007120 // Keep these "kind" numbers in sync with the %select statements in the
7121 // various diagnostics emitted by this routine.
7122 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00007123 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00007124 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007125 else if (isa<VarTemplateDecl>(Specialized))
7126 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00007127 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00007128 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007129 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00007130 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007131 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00007132 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007133 else if (isa<RecordDecl>(Specialized))
7134 EntityKind = 7;
7135 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
7136 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00007137 else {
Richard Smith7d137e32012-03-23 03:33:32 +00007138 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007139 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007140 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00007141 return true;
7142 }
7143
Douglas Gregorf47b9112009-02-25 22:02:03 +00007144 // C++ [temp.expl.spec]p2:
Richard Smithc660c8f2018-03-16 13:36:56 +00007145 // An explicit specialization may be declared in any scope in which
7146 // the corresponding primary template may be defined.
Sebastian Redl50c68252010-08-31 00:36:30 +00007147 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00007148 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007149 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007150 return true;
7151 }
Douglas Gregore4b05162009-10-07 17:21:34 +00007152
7153 // C++ [temp.class.spec]p6:
Richard Smithc660c8f2018-03-16 13:36:56 +00007154 // A class template partial specialization may be declared in any
7155 // scope in which the primary template may be defined.
7156 DeclContext *SpecializedContext =
7157 Specialized->getDeclContext()->getRedeclContext();
7158 DeclContext *DC = S.CurContext->getRedeclContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00007159
Richard Smithc660c8f2018-03-16 13:36:56 +00007160 // Make sure that this redeclaration (or definition) occurs in the same
7161 // scope or an enclosing namespace.
7162 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
7163 : DC->Equals(SpecializedContext))) {
Richard Smitha98f8fc2013-12-07 05:09:50 +00007164 if (isa<TranslationUnitDecl>(SpecializedContext))
7165 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
7166 << EntityKind << Specialized;
Richard Smithc660c8f2018-03-16 13:36:56 +00007167 else {
7168 auto *ND = cast<NamedDecl>(SpecializedContext);
Alexey Bataev0068cb22015-03-20 07:21:46 +00007169 int Diag = diag::err_template_spec_redecl_out_of_scope;
Richard Smithc660c8f2018-03-16 13:36:56 +00007170 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
Alexey Bataev0068cb22015-03-20 07:21:46 +00007171 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
7172 S.Diag(Loc, Diag) << EntityKind << Specialized
Richard Smithc660c8f2018-03-16 13:36:56 +00007173 << ND << isa<CXXRecordDecl>(ND);
7174 }
Richard Smitha98f8fc2013-12-07 05:09:50 +00007175
7176 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007177
Richard Smithc660c8f2018-03-16 13:36:56 +00007178 // Don't allow specializing in the wrong class during error recovery.
7179 // Otherwise, things can go horribly wrong.
7180 if (DC->isRecord())
7181 return true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007182 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007183
Douglas Gregorf47b9112009-02-25 22:02:03 +00007184 return false;
7185}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007186
Richard Smith57aae072016-12-28 02:37:25 +00007187static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
7188 if (!E->isTypeDependent())
Richard Smith6056d5e2014-02-09 00:54:43 +00007189 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00007190 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00007191 Checker.TraverseStmt(E);
Richard Smith57aae072016-12-28 02:37:25 +00007192 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00007193 return E->getSourceRange();
7194 return Checker.MatchLoc;
7195}
7196
7197static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
7198 if (!TL.getType()->isDependentType())
7199 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00007200 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00007201 Checker.TraverseTypeLoc(TL);
Richard Smith57aae072016-12-28 02:37:25 +00007202 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00007203 return TL.getSourceRange();
7204 return Checker.MatchLoc;
7205}
7206
Larisse Voufo39a1e502013-08-06 01:03:05 +00007207/// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007208/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007209static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00007210 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
7211 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007212 for (unsigned I = 0; I != NumArgs; ++I) {
7213 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00007214 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00007215 S, TemplateNameLoc, Param, Args[I].pack_begin(),
7216 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007217 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007218
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007219 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007220 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007221
Eli Friedmanb826a002012-09-26 02:36:12 +00007222 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007223 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00007224
7225 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007226
Douglas Gregor98318c22011-01-03 21:37:45 +00007227 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007228 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
7229 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00007230
7231 // Strip off any implicit casts we added as part of type checking.
7232 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
7233 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007234
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007235 // C++ [temp.class.spec]p8:
7236 // A non-type argument is non-specialized if it is the name of a
7237 // non-type parameter. All other non-type arguments are
7238 // specialized.
7239 //
7240 // Below, we check the two conditions that only apply to
7241 // specialized non-type arguments, so skip any non-specialized
7242 // arguments.
7243 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00007244 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007245 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007246
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007247 // C++ [temp.class.spec]p9:
7248 // Within the argument list of a class template partial
7249 // specialization, the following restrictions apply:
7250 // -- A partially specialized non-type argument expression
7251 // shall not involve a template parameter of the partial
7252 // specialization except when the argument expression is a
7253 // simple identifier.
Richard Smith57aae072016-12-28 02:37:25 +00007254 // -- The type of a template parameter corresponding to a
7255 // specialized non-type argument shall not be dependent on a
7256 // parameter of the specialization.
7257 // DR1315 removes the first bullet, leaving an incoherent set of rules.
7258 // We implement a compromise between the original rules and DR1315:
7259 // -- A specialized non-type template argument shall not be
7260 // type-dependent and the corresponding template parameter
7261 // shall have a non-dependent type.
Richard Smith6056d5e2014-02-09 00:54:43 +00007262 SourceRange ParamUseRange =
Richard Smith57aae072016-12-28 02:37:25 +00007263 findTemplateParameterInType(Param->getDepth(), ArgExpr);
Richard Smith6056d5e2014-02-09 00:54:43 +00007264 if (ParamUseRange.isValid()) {
7265 if (IsDefaultArgument) {
7266 S.Diag(TemplateNameLoc,
7267 diag::err_dependent_non_type_arg_in_partial_spec);
7268 S.Diag(ParamUseRange.getBegin(),
7269 diag::note_dependent_non_type_default_arg_in_partial_spec)
7270 << ParamUseRange;
7271 } else {
7272 S.Diag(ParamUseRange.getBegin(),
7273 diag::err_dependent_non_type_arg_in_partial_spec)
7274 << ParamUseRange;
7275 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007276 return true;
7277 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007278
Richard Smith6056d5e2014-02-09 00:54:43 +00007279 ParamUseRange = findTemplateParameter(
Richard Smith57aae072016-12-28 02:37:25 +00007280 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
Richard Smith6056d5e2014-02-09 00:54:43 +00007281 if (ParamUseRange.isValid()) {
7282 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
7283 diag::err_dependent_typed_non_type_arg_in_partial_spec)
Richard Smith57aae072016-12-28 02:37:25 +00007284 << Param->getType();
Richard Smith6056d5e2014-02-09 00:54:43 +00007285 S.Diag(Param->getLocation(), diag::note_template_param_here)
Richard Smith57aae072016-12-28 02:37:25 +00007286 << (IsDefaultArgument ? ParamUseRange : SourceRange())
7287 << ParamUseRange;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007288 return true;
7289 }
7290 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007291
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007292 return false;
7293}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007294
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007295/// \brief Check the non-type template arguments of a class template
7296/// partial specialization according to C++ [temp.class.spec]p9.
7297///
Richard Smith6056d5e2014-02-09 00:54:43 +00007298/// \param TemplateNameLoc the location of the template name.
Simon Pilgrim6905d222016-12-30 22:55:33 +00007299/// \param PrimaryTemplate the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00007300/// template.
7301/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00007302/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00007303/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007304///
Richard Smith6056d5e2014-02-09 00:54:43 +00007305/// \returns \c true if there was an error, \c false otherwise.
Richard Smith57aae072016-12-28 02:37:25 +00007306bool Sema::CheckTemplatePartialSpecializationArgs(
7307 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
7308 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
7309 // We have to be conservative when checking a template in a dependent
7310 // context.
7311 if (PrimaryTemplate->getDeclContext()->isDependentContext())
7312 return false;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007313
Richard Smith57aae072016-12-28 02:37:25 +00007314 TemplateParameterList *TemplateParams =
7315 PrimaryTemplate->getTemplateParameters();
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007316 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7317 NonTypeTemplateParmDecl *Param
7318 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
7319 if (!Param)
7320 continue;
7321
Richard Smith57aae072016-12-28 02:37:25 +00007322 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
7323 Param, &TemplateArgs[I],
7324 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007325 return true;
7326 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007327
7328 return false;
7329}
7330
John McCall48871652010-08-21 09:40:31 +00007331DeclResult
Faisal Vali090da2d2018-01-01 18:23:28 +00007332Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
John McCall9bb74a52009-07-31 02:45:11 +00007333 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00007334 SourceLocation KWLoc,
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00007335 SourceLocation ModulePrivateLoc,
Richard Smith4b55a9c2014-04-17 03:29:33 +00007336 TemplateIdAnnotation &TemplateId,
Douglas Gregor67a65642009-02-17 23:15:12 +00007337 AttributeList *Attr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00007338 MultiTemplateParamsArg
7339 TemplateParameterLists,
7340 SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00007341 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00007342
Richard Smith4b55a9c2014-04-17 03:29:33 +00007343 CXXScopeSpec &SS = TemplateId.SS;
7344
Abramo Bagnara60804e12011-03-18 15:16:37 +00007345 // NOTE: KWLoc is the location of the tag keyword. This will instead
7346 // store the location of the outermost template keyword in the declaration.
7347 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00007348 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
7349 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
7350 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
7351 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00007352
Douglas Gregor67a65642009-02-17 23:15:12 +00007353 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00007354 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00007355 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00007356 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
7357
7358 if (!ClassTemplate) {
7359 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007360 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00007361 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
7362 return true;
7363 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007364
Richard Smithf445f192017-02-09 21:04:43 +00007365 bool isMemberSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00007366 bool isPartialSpecialization = false;
7367
Douglas Gregorf47b9112009-02-25 22:02:03 +00007368 // Check the validity of the template headers that introduce this
7369 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00007370 // FIXME: We probably shouldn't complain about these headers for
7371 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007372 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00007373 TemplateParameterList *TemplateParams =
7374 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00007375 KWLoc, TemplateNameLoc, SS, &TemplateId,
Richard Smithf445f192017-02-09 21:04:43 +00007376 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
Richard Smith4b55a9c2014-04-17 03:29:33 +00007377 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007378 if (Invalid)
7379 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007380
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007381 if (TemplateParams && TemplateParams->size() > 0) {
7382 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007383
Douglas Gregorec9518b2010-12-21 08:14:57 +00007384 if (TUK == TUK_Friend) {
7385 Diag(KWLoc, diag::err_partial_specialization_friend)
7386 << SourceRange(LAngleLoc, RAngleLoc);
7387 return true;
7388 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007389
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007390 // C++ [temp.class.spec]p10:
7391 // The template parameter list of a specialization shall not
7392 // contain default template argument values.
7393 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7394 Decl *Param = TemplateParams->getParam(I);
7395 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
7396 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00007397 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007398 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00007399 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007400 }
7401 } else if (NonTypeTemplateParmDecl *NTTP
7402 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
7403 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00007404 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007405 diag::err_default_arg_in_partial_spec)
7406 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00007407 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007408 }
7409 } else {
7410 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00007411 if (TTP->hasDefaultArgument()) {
7412 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007413 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00007414 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00007415 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00007416 }
7417 }
7418 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007419 } else if (TemplateParams) {
7420 if (TUK == TUK_Friend)
7421 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00007422 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007423 SourceRange(TemplateParams->getTemplateLoc(),
7424 TemplateParams->getRAngleLoc()))
7425 << SourceRange(LAngleLoc, RAngleLoc);
Richard Smith4b55a9c2014-04-17 03:29:33 +00007426 } else {
7427 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007428 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00007429
Douglas Gregor67a65642009-02-17 23:15:12 +00007430 // Check that the specialization uses the same tag kind as the
7431 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007432 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7433 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00007434 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007435 Kind, TUK == TUK_Definition, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00007436 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007437 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00007438 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007439 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00007440 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007441 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00007442 diag::note_previous_use);
7443 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7444 }
7445
Douglas Gregorc40290e2009-03-09 23:48:35 +00007446 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00007447 TemplateArgumentListInfo TemplateArgs =
7448 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00007449
Douglas Gregor14406932011-01-03 20:35:03 +00007450 // Check for unexpanded parameter packs in any of the template arguments.
7451 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007452 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00007453 UPPC_PartialSpecialization))
7454 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007455
Douglas Gregor67a65642009-02-17 23:15:12 +00007456 // Check that the template argument list is well-formed for this
7457 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007458 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007459 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7460 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00007461 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00007462
Douglas Gregor2373c592009-05-31 09:31:02 +00007463 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00007464 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00007465 if (isPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00007466 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
7467 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007468 return true;
7469
Richard Smith57aae072016-12-28 02:37:25 +00007470 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
7471 // also do it during instantiation.
Douglas Gregor678d76c2011-07-01 01:22:09 +00007472 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007473 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00007474 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00007475 TemplateArgs.arguments(), InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00007476 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
7477 << ClassTemplate->getDeclName();
7478 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00007479 }
7480 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007481
Craig Topperc3ec1492014-05-26 06:22:03 +00007482 void *InsertPos = nullptr;
7483 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00007484
7485 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007486 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00007487 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00007488 else
Craig Topper7e0daca2014-06-26 04:58:53 +00007489 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00007490
Craig Topperc3ec1492014-05-26 06:22:03 +00007491 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00007492
Douglas Gregorf47b9112009-02-25 22:02:03 +00007493 // Check whether we can declare a class template specialization in
7494 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00007495 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007496 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
7497 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007498 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00007499 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007500
Douglas Gregor15301382009-07-30 17:40:51 +00007501 // The canonical type
7502 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00007503 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00007504 // Build the canonical type that describes the converted template
7505 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00007506 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7507 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00007508 Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007509
7510 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007511 ClassTemplate->getInjectedClassNameSpecialization())) {
7512 // C++ [temp.class.spec]p9b3:
7513 //
7514 // -- The argument list of the specialization shall not be identical
7515 // to the implicit argument list of the primary template.
Richard Smith0e617ec2016-12-27 07:56:27 +00007516 //
7517 // This rule has since been removed, because it's redundant given DR1495,
7518 // but we keep it because it produces better diagnostics and recovery.
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007519 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00007520 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00007521 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007522 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
7523 ClassTemplate->getIdentifier(),
7524 TemplateNameLoc,
7525 Attr,
7526 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00007527 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00007528 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00007529 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007530 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007531 }
Douglas Gregor15301382009-07-30 17:40:51 +00007532
Douglas Gregor2373c592009-05-31 09:31:02 +00007533 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00007534 ClassTemplatePartialSpecializationDecl *PrevPartial
7535 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007536 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00007537 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00007538 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007539 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00007540 TemplateParams,
7541 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007542 Converted,
John McCall6b51f282009-11-23 01:53:49 +00007543 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00007544 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00007545 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00007546 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007547 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Benjamin Kramer9cc210652015-08-05 09:40:49 +00007548 Partial->setTemplateParameterListsInfo(
7549 Context, TemplateParameterLists.drop_back(1));
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007550 }
Douglas Gregor2373c592009-05-31 09:31:02 +00007551
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007552 if (!PrevPartial)
7553 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00007554 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00007555
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007556 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00007557 // template specialization, make a note of that.
7558 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
7559 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007560
Richard Smith57aae072016-12-28 02:37:25 +00007561 CheckTemplatePartialSpecialization(Partial);
Douglas Gregor67a65642009-02-17 23:15:12 +00007562 } else {
7563 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00007564 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00007565 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007566 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00007567 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007568 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007569 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007570 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00007571 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00007572 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007573 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00007574 Specialization->setTemplateParameterListsInfo(Context,
Benjamin Kramer9cc210652015-08-05 09:40:49 +00007575 TemplateParameterLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007576 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007577
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007578 if (!PrevDecl)
7579 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00007580
David Majnemer678f50b2015-11-18 19:49:19 +00007581 if (CurContext->isDependentContext()) {
David Majnemer678f50b2015-11-18 19:49:19 +00007582 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7583 CanonType = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00007584 CanonTemplate, Converted);
David Majnemer678f50b2015-11-18 19:49:19 +00007585 } else {
7586 CanonType = Context.getTypeDeclType(Specialization);
7587 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007588 }
7589
Douglas Gregor06db9f52009-10-12 20:18:28 +00007590 // C++ [temp.expl.spec]p6:
7591 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007592 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007593 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007594 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007595 // use occurs; no diagnostic is required.
7596 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007597 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007598 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007599 // Is there any previous explicit specialization declaration?
7600 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7601 Okay = true;
7602 break;
7603 }
7604 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007605
Douglas Gregorc854c662010-02-26 06:03:23 +00007606 if (!Okay) {
7607 SourceRange Range(TemplateNameLoc, RAngleLoc);
7608 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
7609 << Context.getTypeDeclType(Specialization) << Range;
7610
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007611 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00007612 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007613 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00007614 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00007615 return true;
7616 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007617 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007618
Douglas Gregor2208a292009-09-26 20:57:03 +00007619 // If this is not a friend, note that this is an explicit specialization.
7620 if (TUK != TUK_Friend)
7621 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00007622
7623 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00007624 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00007625 RecordDecl *Def = Specialization->getDefinition();
7626 NamedDecl *Hidden = nullptr;
7627 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
7628 SkipBody->ShouldSkip = true;
Richard Smith858e0e02017-05-11 23:11:16 +00007629 makeMergedDefinitionVisible(Hidden);
Richard Smithc7e6ff02015-05-18 20:36:47 +00007630 // From here on out, treat this as just a redeclaration.
7631 TUK = TUK_Declaration;
7632 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00007633 SourceRange Range(TemplateNameLoc, RAngleLoc);
Richard Smith792c22d2016-12-24 04:09:05 +00007634 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00007635 Diag(Def->getLocation(), diag::note_previous_definition);
7636 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00007637 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00007638 }
7639 }
7640
John McCall659a3372010-12-18 03:30:47 +00007641 if (Attr)
7642 ProcessDeclAttributeList(S, Specialization, Attr);
7643
Richard Smith034b94a2012-08-17 03:20:55 +00007644 // Add alignment attributes if necessary; these attributes are checked when
7645 // the ASTContext lays out the structure.
7646 if (TUK == TUK_Definition) {
7647 AddAlignmentAttributesForRecord(Specialization);
7648 AddMsStructLayoutForRecord(Specialization);
7649 }
7650
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00007651 if (ModulePrivateLoc.isValid())
7652 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
7653 << (isPartialSpecialization? 1 : 0)
7654 << FixItHint::CreateRemoval(ModulePrivateLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00007655
Douglas Gregord56a91e2009-02-26 22:19:44 +00007656 // Build the fully-sugared type for this class template
7657 // specialization as the user wrote in the specialization
7658 // itself. This means that we'll pretty-print the type retrieved
7659 // from the specialization's declaration the way that the user
7660 // actually wrote the specialization, rather than formatting the
7661 // name based on the "canonical" representation used to store the
7662 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007663 TypeSourceInfo *WrittenTy
7664 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7665 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007666 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00007667 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007668 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007669 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007670
Douglas Gregor1e249f82009-02-25 22:18:32 +00007671 // C++ [temp.expl.spec]p9:
7672 // A template explicit specialization is in the scope of the
7673 // namespace in which the template was defined.
7674 //
7675 // We actually implement this paragraph where we set the semantic
7676 // context (in the creation of the ClassTemplateSpecializationDecl),
7677 // but we also maintain the lexical context where the actual
7678 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00007679 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00007680
Douglas Gregor67a65642009-02-17 23:15:12 +00007681 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00007682 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00007683 Specialization->startDefinition();
7684
Douglas Gregor2208a292009-09-26 20:57:03 +00007685 if (TUK == TUK_Friend) {
7686 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
7687 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00007688 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00007689 /*FIXME:*/KWLoc);
7690 Friend->setAccess(AS_public);
7691 CurContext->addDecl(Friend);
7692 } else {
7693 // Add the specialization into its lexical context, so that it can
7694 // be seen when iterating through the list of declarations in that
7695 // context. However, specializations are not found by name lookup.
7696 CurContext->addDecl(Specialization);
7697 }
John McCall48871652010-08-21 09:40:31 +00007698 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00007699}
Douglas Gregor333489b2009-03-27 23:10:48 +00007700
John McCall48871652010-08-21 09:40:31 +00007701Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00007702 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00007703 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007704 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00007705 ActOnDocumentableDecl(NewDecl);
7706 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00007707}
7708
John McCall4f7ced62010-02-11 01:33:53 +00007709/// \brief Strips various properties off an implicit instantiation
7710/// that has just been explicitly specialized.
7711static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00007712 D->dropAttr<DLLImportAttr>();
7713 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00007714
Nico Webere4974382014-12-19 23:52:45 +00007715 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00007716 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00007717}
7718
Nico Webera8f80b32012-01-09 19:52:25 +00007719/// \brief Compute the diagnostic location for an explicit instantiation
7720// declaration or definition.
7721static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007722 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00007723 // Explicit instantiations following a specialization have no effect and
7724 // hence no PointOfInstantiation. In that case, walk decl backwards
7725 // until a valid name loc is found.
7726 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007727 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
7728 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00007729 PrevDiagLoc = Prev->getLocation();
7730 }
7731 assert(PrevDiagLoc.isValid() &&
7732 "Explicit instantiation without point of instantiation?");
7733 return PrevDiagLoc;
7734}
7735
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007736/// \brief Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007737/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007738/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007739/// new specialization/instantiation will have any effect.
7740///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007741/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007742/// instantiation.
7743///
7744/// \param NewTSK the kind of the new explicit specialization or instantiation.
7745///
7746/// \param PrevDecl the previous declaration of the entity.
7747///
7748/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
7749///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007750/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007751/// declaration was instantiated (either implicitly or explicitly).
7752///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007753/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007754/// specialization or instantiation has no effect and should be ignored.
7755///
7756/// \returns true if there was an error that should prevent the introduction of
7757/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00007758bool
7759Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7760 TemplateSpecializationKind NewTSK,
7761 NamedDecl *PrevDecl,
7762 TemplateSpecializationKind PrevTSK,
7763 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007764 bool &HasNoEffect) {
7765 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007766
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007767 switch (NewTSK) {
7768 case TSK_Undeclared:
7769 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00007770 assert(
7771 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
7772 "previous declaration must be implicit!");
7773 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007774
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007775 case TSK_ExplicitSpecialization:
7776 switch (PrevTSK) {
7777 case TSK_Undeclared:
7778 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007779 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007780 // explicitly specialized or has merely been mentioned without any
7781 // instantiation.
7782 return false;
7783
7784 case TSK_ImplicitInstantiation:
7785 if (PrevPointOfInstantiation.isInvalid()) {
7786 // The declaration itself has not actually been instantiated, so it is
7787 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00007788 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007789 return false;
7790 }
7791 // Fall through
Galina Kistanova3779cb32017-06-07 06:25:05 +00007792 LLVM_FALLTHROUGH;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007793
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007794 case TSK_ExplicitInstantiationDeclaration:
7795 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007796 assert((PrevTSK == TSK_ImplicitInstantiation ||
7797 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007798 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007799
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007800 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007801 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007802 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007803 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007804 // implicit instantiation to take place, in every translation unit in
7805 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007806 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007807 // Is there any previous explicit specialization declaration?
7808 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
7809 return false;
7810 }
7811
Douglas Gregor1d957a32009-10-27 18:42:08 +00007812 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007813 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007814 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007815 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007816
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007817 return true;
7818 }
Galina Kistanova1d36e832017-06-08 18:20:32 +00007819 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007820
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007821 case TSK_ExplicitInstantiationDeclaration:
7822 switch (PrevTSK) {
7823 case TSK_ExplicitInstantiationDeclaration:
7824 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00007825 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007826 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007827
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007828 case TSK_Undeclared:
7829 case TSK_ImplicitInstantiation:
7830 // We're explicitly instantiating something that may have already been
7831 // implicitly instantiated; that's fine.
7832 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007833
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007834 case TSK_ExplicitSpecialization:
7835 // C++0x [temp.explicit]p4:
7836 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007837 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007838 // specialization for that template, the explicit instantiation has no
7839 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007840 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007841 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007842
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007843 case TSK_ExplicitInstantiationDefinition:
7844 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007845 // If an entity is the subject of both an explicit instantiation
7846 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007847 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007848 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00007849 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00007850
7851 // Explicit instantiations following a specialization have no effect and
7852 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
7853 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00007854 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7855 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007856 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007857 return false;
7858 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007859
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007860 case TSK_ExplicitInstantiationDefinition:
7861 switch (PrevTSK) {
7862 case TSK_Undeclared:
7863 case TSK_ImplicitInstantiation:
7864 // We're explicitly instantiating something that may have already been
7865 // implicitly instantiated; that's fine.
7866 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007867
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007868 case TSK_ExplicitSpecialization:
7869 // C++ DR 259, C++0x [temp.explicit]p4:
7870 // For a given set of template parameters, if an explicit
7871 // instantiation of a template appears after a declaration of
7872 // an explicit specialization for that template, the explicit
7873 // instantiation has no effect.
Richard Smithe4caa482016-08-31 23:23:25 +00007874 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
Richard Smith0bf8a4922011-10-18 20:49:44 +00007875 << PrevDecl;
7876 Diag(PrevDecl->getLocation(),
7877 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007878 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007879 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007880
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007881 case TSK_ExplicitInstantiationDeclaration:
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00007882 // We're explicitly instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007883 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00007884
7885 // C++0x [temp.explicit]p4:
7886 // For a given set of template parameters, if an explicit instantiation
7887 // of a template appears after a declaration of an explicit
7888 // specialization for that template, the explicit instantiation has no
7889 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007890 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00007891 // Is there any previous explicit specialization declaration?
7892 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7893 HasNoEffect = true;
7894 break;
7895 }
7896 }
7897
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007898 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007899
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007900 case TSK_ExplicitInstantiationDefinition:
7901 // C++0x [temp.spec]p5:
7902 // For a given template and a given set of template-arguments,
7903 // - an explicit instantiation definition shall appear at most once
7904 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00007905
7906 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
7907 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00007908 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00007909 : diag::err_explicit_instantiation_duplicate)
7910 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00007911 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00007912 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007913 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007914 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007915 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007916 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007917
David Blaikie83d382b2011-09-23 05:06:16 +00007918 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007919}
7920
John McCallb9c78482010-04-08 09:05:18 +00007921/// \brief Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00007922/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00007923///
James Dennettf14a6e52012-06-15 22:23:43 +00007924/// The only possible way to get a dependent function template specialization
7925/// is with a friend declaration, like so:
7926///
7927/// \code
7928/// template \<class T> void foo(T);
7929/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00007930/// friend void foo<>(T);
7931/// };
James Dennettf14a6e52012-06-15 22:23:43 +00007932/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00007933///
7934/// There really isn't any useful analysis we can do here, so we
7935/// just store the information.
7936bool
7937Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
7938 const TemplateArgumentListInfo &ExplicitTemplateArgs,
7939 LookupResult &Previous) {
7940 // Remove anything from Previous that isn't a function template in
7941 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00007942 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00007943 LookupResult::Filter F = Previous.makeFilter();
7944 while (F.hasNext()) {
7945 NamedDecl *D = F.next()->getUnderlyingDecl();
7946 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00007947 !FDLookupContext->InEnclosingNamespaceSetOf(
7948 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00007949 F.erase();
7950 }
7951 F.done();
7952
7953 // Should this be diagnosed here?
7954 if (Previous.empty()) return true;
7955
7956 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
7957 ExplicitTemplateArgs);
7958 return false;
7959}
7960
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007961/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007962/// specialization.
7963///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007964/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007965/// explicit function template specialization. On successful completion,
7966/// the function declaration \p FD will become a function template
7967/// specialization.
7968///
7969/// \param FD the function declaration, which will be updated to become a
7970/// function template specialization.
7971///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007972/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
7973/// if any. Note that this may be valid info even when 0 arguments are
7974/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
7975/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007976///
Francois Pichet3a44e432011-07-08 06:21:47 +00007977/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007978/// this function specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007979bool Sema::CheckFunctionTemplateSpecialization(
7980 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
7981 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007982 // The set of function template specializations that could match this
7983 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00007984 UnresolvedSet<8> Candidates;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007985 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
7986 /*ForTakingAddress=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007987
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007988 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
7989 ConvertedTemplateArgs;
7990
Sebastian Redl50c68252010-08-31 00:36:30 +00007991 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00007992 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7993 I != E; ++I) {
7994 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
7995 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007996 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007997 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00007998 if (!FDLookupContext->InEnclosingNamespaceSetOf(
7999 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008000 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008001
Richard Smith574f4f62013-01-14 05:37:29 +00008002 // When matching a constexpr member function template specialization
8003 // against the primary template, we don't yet know whether the
8004 // specialization has an implicit 'const' (because we don't know whether
8005 // it will be a static member function until we know which template it
8006 // specializes), so adjust it now assuming it specializes this template.
8007 QualType FT = FD->getType();
8008 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00008009 CXXMethodDecl *OldMD =
8010 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00008011 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00008012 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00008013 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8014 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00008015 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00008016 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00008017 }
8018 }
8019
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008020 TemplateArgumentListInfo Args;
8021 if (ExplicitTemplateArgs)
8022 Args = *ExplicitTemplateArgs;
8023
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008024 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008025 // A trailing template-argument can be left unspecified in the
8026 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008027 // provided it can be deduced from the function argument type.
8028 // Perform template argument deduction to determine whether we may be
8029 // specializing this template.
8030 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00008031 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00008032 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00008033 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
8034 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
Richard Smithc2bebe92016-05-11 20:37:46 +00008035 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
8036 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008037 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008038 // that we can provide nifty diagnostics.
Richard Smithc2bebe92016-05-11 20:37:46 +00008039 FailedCandidates.addCandidate().set(
8040 I.getPair(), FunTmpl->getTemplatedDecl(),
8041 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008042 (void)TDK;
8043 continue;
8044 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008045
Artem Belevich64135c32016-12-08 19:38:13 +00008046 // Target attributes are part of the cuda function signature, so
8047 // the deduced template's cuda target must match that of the
8048 // specialization. Given that C++ template deduction does not
8049 // take target attributes into account, we reject candidates
8050 // here that have a different target.
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008051 if (LangOpts.CUDA &&
Artem Belevich64135c32016-12-08 19:38:13 +00008052 IdentifyCUDATarget(Specialization,
8053 /* IgnoreImplicitHDAttributes = */ true) !=
8054 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttributes = */ true)) {
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008055 FailedCandidates.addCandidate().set(
8056 I.getPair(), FunTmpl->getTemplatedDecl(),
8057 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
8058 continue;
8059 }
8060
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008061 // Record this candidate.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008062 if (ExplicitTemplateArgs)
8063 ConvertedTemplateArgs[Specialization] = std::move(Args);
John McCall58cc69d2010-01-27 01:50:18 +00008064 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008065 }
8066 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008067
Douglas Gregor5de279c2009-09-26 03:41:46 +00008068 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008069 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00008070 Candidates.begin(), Candidates.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00008071 FD->getLocation(),
8072 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
8073 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00008074 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00008075 PDiag(diag::note_function_template_spec_matched));
8076
John McCall58cc69d2010-01-27 01:50:18 +00008077 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008078 return true;
John McCall58cc69d2010-01-27 01:50:18 +00008079
8080 // Ignore access information; it doesn't figure into redeclaration checking.
8081 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00008082
8083 FunctionTemplateSpecializationInfo *SpecInfo
8084 = Specialization->getTemplateSpecializationInfo();
8085 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00008086
8087 // Note: do not overwrite location info if previous template
8088 // specialization kind was explicit.
8089 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00008090 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00008091 Specialization->setLocation(FD->getLocation());
Richard Smith54f04402017-05-18 02:29:20 +00008092 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
Richard Smith5b8b3db2012-02-20 23:28:05 +00008093 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
8094 // function can differ from the template declaration with respect to
8095 // the constexpr specifier.
Richard Smith77e9e842017-05-09 23:02:10 +00008096 // FIXME: We need an update record for this AST mutation.
8097 // FIXME: What if there are multiple such prior declarations (for instance,
8098 // from different modules)?
Richard Smith5b8b3db2012-02-20 23:28:05 +00008099 Specialization->setConstexpr(FD->isConstexpr());
8100 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008101
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008102 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00008103 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00008104
8105 // If this is a friend declaration, then we're not really declaring
8106 // an explicit specialization.
8107 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008108
Douglas Gregor54888652009-10-07 00:13:32 +00008109 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00008110 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008111 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00008112 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008113 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00008114 false))
Douglas Gregor54888652009-10-07 00:13:32 +00008115 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00008116
8117 // C++ [temp.expl.spec]p6:
8118 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008119 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00008120 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008121 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00008122 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00008123 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00008124 if (!isFriend &&
8125 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00008126 TSK_ExplicitSpecialization,
8127 Specialization,
8128 SpecInfo->getTemplateSpecializationKind(),
8129 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008130 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00008131 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008132
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008133 // Mark the prior declaration as an explicit specialization, so that later
8134 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00008135 if (!isFriend) {
Faisal Vali81a88be2016-06-14 03:23:15 +00008136 // Since explicit specializations do not inherit '=delete' from their
8137 // primary function template - check if the 'specialization' that was
8138 // implicitly generated (during template argument deduction for partial
8139 // ordering) from the most specialized of all the function templates that
8140 // 'FD' could have been specializing, has a 'deleted' definition. If so,
8141 // first check that it was implicitly generated during template argument
8142 // deduction by making sure it wasn't referenced, and then reset the deleted
8143 // flag to not-deleted, so that we can inherit that information from 'FD'.
8144 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
8145 !Specialization->getCanonicalDecl()->isReferenced()) {
Richard Smith77e9e842017-05-09 23:02:10 +00008146 // FIXME: This assert will not hold in the presence of modules.
Faisal Vali81a88be2016-06-14 03:23:15 +00008147 assert(
8148 Specialization->getCanonicalDecl() == Specialization &&
8149 "This must be the only existing declaration of this specialization");
Richard Smith77e9e842017-05-09 23:02:10 +00008150 // FIXME: We need an update record for this AST mutation.
Faisal Vali81a88be2016-06-14 03:23:15 +00008151 Specialization->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008152 }
Richard Smith54f04402017-05-18 02:29:20 +00008153 // FIXME: We need an update record for this AST mutation.
John McCall816d75b2010-03-24 07:46:06 +00008154 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00008155 MarkUnusedFileScopedDecl(Specialization);
8156 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008157
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008158 // Turn the given function declaration into a function template
8159 // specialization, with the template arguments from the previous
8160 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008161 // Take copies of (semantic and syntactic) template argument lists.
8162 const TemplateArgumentList* TemplArgs = new (Context)
8163 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008164 FD->setFunctionTemplateSpecialization(
8165 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
8166 SpecInfo->getTemplateSpecializationKind(),
8167 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008168
Artem Belevich64135c32016-12-08 19:38:13 +00008169 // A function template specialization inherits the target attributes
8170 // of its template. (We require the attributes explicitly in the
8171 // code to match, but a template may have implicit attributes by
8172 // virtue e.g. of being constexpr, and it passes these implicit
8173 // attributes on to its specializations.)
8174 if (LangOpts.CUDA)
8175 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
8176
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008177 // The "previous declaration" for this function template specialization is
8178 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00008179 Previous.clear();
8180 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008181 return false;
8182}
8183
Douglas Gregor86d142a2009-10-08 07:24:58 +00008184/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008185/// specialization.
8186///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008187/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008188/// explicit member function specialization. On successful completion,
8189/// the function declaration \p FD will become a member function
8190/// specialization.
8191///
Douglas Gregor86d142a2009-10-08 07:24:58 +00008192/// \param Member the member declaration, which will be updated to become a
8193/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008194///
John McCall1f82f242009-11-18 22:49:29 +00008195/// \param Previous the set of declarations, one of which may be specialized
8196/// by this function specialization; the set will be modified to contain the
8197/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008198bool
John McCall1f82f242009-11-18 22:49:29 +00008199Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008200 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00008201
Douglas Gregor86d142a2009-10-08 07:24:58 +00008202 // Try to find the member we are instantiating.
Richard Smith22e7cc62016-05-24 00:01:49 +00008203 NamedDecl *FoundInstantiation = nullptr;
Craig Topperc3ec1492014-05-26 06:22:03 +00008204 NamedDecl *Instantiation = nullptr;
8205 NamedDecl *InstantiatedFrom = nullptr;
8206 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00008207
John McCall1f82f242009-11-18 22:49:29 +00008208 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008209 // Nowhere to look anyway.
8210 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008211 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8212 I != E; ++I) {
8213 NamedDecl *D = (*I)->getUnderlyingDecl();
8214 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00008215 QualType Adjusted = Function->getType();
8216 if (!hasExplicitCallingConv(Adjusted))
8217 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
8218 if (Context.hasSameType(Adjusted, Method->getType())) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008219 FoundInstantiation = *I;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008220 Instantiation = Method;
8221 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008222 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008223 break;
8224 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008225 }
8226 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00008227 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008228 VarDecl *PrevVar;
8229 if (Previous.isSingleResult() &&
8230 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00008231 if (PrevVar->isStaticDataMember()) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008232 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00008233 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008234 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008235 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008236 }
8237 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008238 CXXRecordDecl *PrevRecord;
8239 if (Previous.isSingleResult() &&
8240 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008241 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00008242 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008243 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008244 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008245 }
Richard Smith7d137e32012-03-23 03:33:32 +00008246 } else if (isa<EnumDecl>(Member)) {
8247 EnumDecl *PrevEnum;
8248 if (Previous.isSingleResult() &&
8249 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008250 FoundInstantiation = Previous.getRepresentativeDecl();
Richard Smith7d137e32012-03-23 03:33:32 +00008251 Instantiation = PrevEnum;
8252 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
8253 MSInfo = PrevEnum->getMemberSpecializationInfo();
8254 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008255 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008256
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008257 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008258 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008259 // specializations are always out-of-line, the caller will complain about
8260 // this mismatch later.
8261 return false;
8262 }
John McCalle820e5e2010-04-13 20:37:33 +00008263
Richard Smith77e9e842017-05-09 23:02:10 +00008264 // A member specialization in a friend declaration isn't really declaring
8265 // an explicit specialization, just identifying a specific (possibly implicit)
8266 // specialization. Don't change the template specialization kind.
8267 //
8268 // FIXME: Is this really valid? Other compilers reject.
John McCalle820e5e2010-04-13 20:37:33 +00008269 if (Member->getFriendObjectKind() != Decl::FOK_None) {
8270 // Preserve instantiation information.
8271 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
8272 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
8273 cast<CXXMethodDecl>(InstantiatedFrom),
8274 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
8275 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
8276 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
8277 cast<CXXRecordDecl>(InstantiatedFrom),
8278 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
8279 }
8280
8281 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00008282 Previous.addDecl(FoundInstantiation);
John McCalle820e5e2010-04-13 20:37:33 +00008283 return false;
8284 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008285
Douglas Gregor86d142a2009-10-08 07:24:58 +00008286 // Make sure that this is a specialization of a member.
8287 if (!InstantiatedFrom) {
8288 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
8289 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008290 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
8291 return true;
8292 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008293
Douglas Gregor06db9f52009-10-12 20:18:28 +00008294 // C++ [temp.expl.spec]p6:
8295 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00008296 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00008297 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008298 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00008299 // use occurs; no diagnostic is required.
8300 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00008301
Abramo Bagnara8075c852010-06-12 07:44:57 +00008302 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00008303 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
8304 TSK_ExplicitSpecialization,
8305 Instantiation,
8306 MSInfo->getTemplateSpecializationKind(),
8307 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008308 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00008309 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008310
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008311 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008312 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00008313 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008314 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00008315 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008316 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00008317
Richard Smith77e9e842017-05-09 23:02:10 +00008318 // Note that this member specialization is an "instantiation of" the
8319 // corresponding member of the original template.
8320 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008321 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
8322 if (InstantiationFunction->getTemplateSpecializationKind() ==
8323 TSK_ImplicitInstantiation) {
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008324 // Explicit specializations of member functions of class templates do not
8325 // inherit '=delete' from the member function they are specializing.
8326 if (InstantiationFunction->isDeleted()) {
Richard Smith77e9e842017-05-09 23:02:10 +00008327 // FIXME: This assert will not hold in the presence of modules.
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008328 assert(InstantiationFunction->getCanonicalDecl() ==
8329 InstantiationFunction);
Richard Smith77e9e842017-05-09 23:02:10 +00008330 // FIXME: We need an update record for this AST mutation.
Richard Smith5f274382016-09-28 23:55:27 +00008331 InstantiationFunction->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008332 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008333 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008334
Richard Smith77e9e842017-05-09 23:02:10 +00008335 MemberFunction->setInstantiationOfMemberFunction(
8336 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8337 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
8338 MemberVar->setInstantiationOfStaticDataMember(
Larisse Voufo39a1e502013-08-06 01:03:05 +00008339 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Richard Smith77e9e842017-05-09 23:02:10 +00008340 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
8341 MemberClass->setInstantiationOfMemberClass(
8342 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8343 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
8344 MemberEnum->setInstantiationOfMemberEnum(
Richard Smith7d137e32012-03-23 03:33:32 +00008345 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Richard Smith77e9e842017-05-09 23:02:10 +00008346 } else {
8347 llvm_unreachable("unknown member specialization kind");
Douglas Gregor86d142a2009-10-08 07:24:58 +00008348 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008349
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008350 // Save the caller the trouble of having to figure out which declaration
8351 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00008352 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00008353 Previous.addDecl(FoundInstantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008354 return false;
8355}
8356
Richard Smith77e9e842017-05-09 23:02:10 +00008357/// Complete the explicit specialization of a member of a class template by
8358/// updating the instantiated member to be marked as an explicit specialization.
8359///
8360/// \param OrigD The member declaration instantiated from the template.
8361/// \param Loc The location of the explicit specialization of the member.
8362template<typename DeclT>
8363static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
8364 SourceLocation Loc) {
8365 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
8366 return;
8367
8368 // FIXME: Inform AST mutation listeners of this AST mutation.
8369 // FIXME: If there are multiple in-class declarations of the member (from
8370 // multiple modules, or a declaration and later definition of a member type),
8371 // should we update all of them?
8372 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
8373 OrigD->setLocation(Loc);
8374}
8375
8376void Sema::CompleteMemberSpecialization(NamedDecl *Member,
8377 LookupResult &Previous) {
8378 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
8379 if (Instantiation == Member)
8380 return;
8381
8382 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
8383 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
8384 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
8385 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
8386 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
8387 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
8388 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
8389 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
8390 else
8391 llvm_unreachable("unknown member specialization kind");
8392}
8393
Douglas Gregore47f5a72009-10-14 23:41:34 +00008394/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008395///
8396/// \returns true if a serious error occurs, false otherwise.
8397static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00008398 SourceLocation InstLoc,
8399 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00008400 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
8401 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008402
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008403 if (CurContext->isRecord()) {
8404 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
8405 << D;
8406 return true;
8407 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008408
Richard Smith050d2612011-10-18 02:28:33 +00008409 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008410 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00008411 // template. If the name declared in the explicit instantiation is an
8412 // unqualified name, the explicit instantiation shall appear in the
8413 // namespace where its template is declared or, if that namespace is inline
8414 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008415 //
8416 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00008417 if (WasQualifiedName) {
8418 if (CurContext->Encloses(OrigContext))
8419 return false;
8420 } else {
8421 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
8422 return false;
8423 }
8424
8425 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
8426 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008427 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008428 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008429 diag::err_explicit_instantiation_out_of_scope :
8430 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008431 << D << NS;
8432 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008433 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008434 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008435 diag::err_explicit_instantiation_unqualified_wrong_namespace :
8436 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
8437 << D << NS;
8438 } else
8439 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008440 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008441 diag::err_explicit_instantiation_must_be_global :
8442 diag::warn_explicit_instantiation_must_be_global_0x)
8443 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00008444 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008445 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00008446}
8447
8448/// \brief Determine whether the given scope specifier has a template-id in it.
8449static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
8450 if (!SS.isSet())
8451 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008452
Richard Smith050d2612011-10-18 02:28:33 +00008453 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008454 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008455 // or a static data member of a class template specialization, the name of
8456 // the class template specialization in the qualified-id for the member
8457 // name shall be a simple-template-id.
8458 //
8459 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00008460 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
8461 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00008462 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00008463 if (isa<TemplateSpecializationType>(T))
8464 return true;
8465
8466 return false;
8467}
8468
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008469/// Make a dllexport or dllimport attr on a class template specialization take
8470/// effect.
8471static void dllExportImportClassTemplateSpecialization(
8472 Sema &S, ClassTemplateSpecializationDecl *Def) {
8473 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
8474 assert(A && "dllExportImportClassTemplateSpecialization called "
8475 "on Def without dllexport or dllimport");
8476
8477 // We reject explicit instantiations in class scope, so there should
8478 // never be any delayed exported classes to worry about.
8479 assert(S.DelayedDllExportClasses.empty() &&
8480 "delayed exports present at explicit instantiation");
8481 S.checkClassLevelDLLAttribute(Def);
8482
8483 // Propagate attribute to base class templates.
8484 for (auto &B : Def->bases()) {
8485 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
8486 B.getType()->getAsCXXRecordDecl()))
8487 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
8488 }
8489
8490 S.referenceDLLExportedClassMethods();
8491}
8492
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008493// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00008494DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00008495Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00008496 SourceLocation ExternLoc,
8497 SourceLocation TemplateLoc,
Faisal Vali090da2d2018-01-01 18:23:28 +00008498 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00008499 SourceLocation KWLoc,
8500 const CXXScopeSpec &SS,
8501 TemplateTy TemplateD,
8502 SourceLocation TemplateNameLoc,
8503 SourceLocation LAngleLoc,
8504 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00008505 SourceLocation RAngleLoc,
8506 AttributeList *Attr) {
8507 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00008508 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00008509 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00008510 // Check that the specialization uses the same tag kind as the
8511 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00008512 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8513 assert(Kind != TTK_Enum &&
8514 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00008515
Richard Trieu265c3442016-04-05 21:13:54 +00008516 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
8517
8518 if (!ClassTemplate) {
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00008519 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
8520 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
Richard Trieu265c3442016-04-05 21:13:54 +00008521 Diag(TD->getLocation(), diag::note_previous_use);
Richard Smith392497b2013-06-22 22:03:31 +00008522 return true;
8523 }
8524
Douglas Gregord9034f02009-05-14 16:41:31 +00008525 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00008526 Kind, /*isDefinition*/false, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00008527 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00008528 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00008529 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00008530 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00008531 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00008532 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00008533 diag::note_previous_use);
8534 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8535 }
8536
Douglas Gregore47f5a72009-10-14 23:41:34 +00008537 // C++0x [temp.explicit]p2:
8538 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008539 // definition and an explicit instantiation declaration. An explicit
8540 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00008541 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
8542 ? TSK_ExplicitInstantiationDefinition
8543 : TSK_ExplicitInstantiationDeclaration;
8544
8545 if (TSK == TSK_ExplicitInstantiationDeclaration) {
8546 // Check for dllexport class template instantiation declarations.
8547 for (AttributeList *A = Attr; A; A = A->getNext()) {
8548 if (A->getKind() == AttributeList::AT_DLLExport) {
8549 Diag(ExternLoc,
8550 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8551 Diag(A->getLoc(), diag::note_attribute);
8552 break;
8553 }
8554 }
8555
8556 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
8557 Diag(ExternLoc,
8558 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8559 Diag(A->getLocation(), diag::note_attribute);
8560 }
8561 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008562
Hans Wennborga86a83b2016-05-26 19:42:56 +00008563 // In MSVC mode, dllimported explicit instantiation definitions are treated as
8564 // instantiation declarations for most purposes.
8565 bool DLLImportExplicitInstantiationDef = false;
8566 if (TSK == TSK_ExplicitInstantiationDefinition &&
8567 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
8568 // Check for dllimport class template instantiation definitions.
8569 bool DLLImport =
8570 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
8571 for (AttributeList *A = Attr; A; A = A->getNext()) {
8572 if (A->getKind() == AttributeList::AT_DLLImport)
8573 DLLImport = true;
8574 if (A->getKind() == AttributeList::AT_DLLExport) {
8575 // dllexport trumps dllimport here.
8576 DLLImport = false;
8577 break;
8578 }
8579 }
8580 if (DLLImport) {
8581 TSK = TSK_ExplicitInstantiationDeclaration;
8582 DLLImportExplicitInstantiationDef = true;
8583 }
8584 }
8585
Douglas Gregora1f49972009-05-13 00:25:59 +00008586 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00008587 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00008588 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00008589
8590 // Check that the template argument list is well-formed for this
8591 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008592 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00008593 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
8594 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00008595 return true;
8596
Douglas Gregora1f49972009-05-13 00:25:59 +00008597 // Find the class template specialization declaration that
8598 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00008599 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00008600 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00008601 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00008602
Abramo Bagnara8075c852010-06-12 07:44:57 +00008603 TemplateSpecializationKind PrevDecl_TSK
8604 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
8605
Douglas Gregor54888652009-10-07 00:13:32 +00008606 // C++0x [temp.explicit]p2:
8607 // [...] An explicit instantiation shall appear in an enclosing
8608 // namespace of its template. [...]
8609 //
8610 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008611 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
8612 SS.isSet()))
8613 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008614
Craig Topperc3ec1492014-05-26 06:22:03 +00008615 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00008616
Abramo Bagnara8075c852010-06-12 07:44:57 +00008617 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00008618 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00008619 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00008620 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00008621 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008622 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00008623 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00008624
Abramo Bagnara8075c852010-06-12 07:44:57 +00008625 // Even though HasNoEffect == true means that this explicit instantiation
8626 // has no effect on semantics, we go on to put its syntax in the AST.
8627
8628 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
8629 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008630 // Since the only prior class template specialization with these
8631 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00008632 // declaration node as our own, updating the source location
8633 // for the template name to reflect our new declaration.
8634 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008635 Specialization = PrevDecl;
8636 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00008637 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008638 }
Hans Wennborga86a83b2016-05-26 19:42:56 +00008639
8640 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
8641 DLLImportExplicitInstantiationDef) {
8642 // The new specialization might add a dllimport attribute.
8643 HasNoEffect = false;
8644 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00008645 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00008646
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008647 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00008648 // Create a new class template specialization declaration node for
8649 // this explicit specialization.
8650 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00008651 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00008652 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00008653 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00008654 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00008655 Converted,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008656 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00008657 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00008658
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00008659 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00008660 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00008661 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008662 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008663 }
8664
8665 // Build the fully-sugared type for this explicit instantiation as
8666 // the user wrote in the explicit instantiation itself. This means
8667 // that we'll pretty-print the type retrieved from the
8668 // specialization's declaration the way that the user actually wrote
8669 // the explicit instantiation, rather than formatting the name based
8670 // on the "canonical" representation used to store the template
8671 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00008672 TypeSourceInfo *WrittenTy
8673 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
8674 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00008675 Context.getTypeDeclType(Specialization));
8676 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00008677
Abramo Bagnara8075c852010-06-12 07:44:57 +00008678 // Set source locations for keywords.
8679 Specialization->setExternLoc(ExternLoc);
8680 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00008681 Specialization->setBraceRange(SourceRange());
Abramo Bagnara8075c852010-06-12 07:44:57 +00008682
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00008683 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
Rafael Espindola0b062072012-01-03 06:04:21 +00008684 if (Attr)
8685 ProcessDeclAttributeList(S, Specialization, Attr);
8686
Abramo Bagnara8075c852010-06-12 07:44:57 +00008687 // Add the explicit instantiation into its lexical context. However,
8688 // since explicit instantiations are never found by name lookup, we
8689 // just put it into the declaration context directly.
8690 Specialization->setLexicalDeclContext(CurContext);
8691 CurContext->addDecl(Specialization);
8692
8693 // Syntax is now OK, so return if it has no other effect on semantics.
8694 if (HasNoEffect) {
8695 // Set the template specialization kind.
8696 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00008697 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00008698 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008699
8700 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00008701 // A definition of a class template or class member template
8702 // shall be in scope at the point of the explicit instantiation of
8703 // the class template or class member template.
8704 //
8705 // This check comes when we actually try to perform the
8706 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00008707 ClassTemplateSpecializationDecl *Def
8708 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008709 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00008710 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00008711 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008712 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00008713 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008714 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
8715 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00008716
Douglas Gregor1d957a32009-10-27 18:42:08 +00008717 // Instantiate the members of this class template specialization.
8718 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008719 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00008720 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008721 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008722 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
8723 // TSK_ExplicitInstantiationDefinition
8724 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborga86a83b2016-05-26 19:42:56 +00008725 (TSK == TSK_ExplicitInstantiationDefinition ||
8726 DLLImportExplicitInstantiationDef)) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00008727 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008728 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00008729
Hans Wennborgc0875502015-06-09 00:39:05 +00008730 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
Shoaib Meenaiab3f96c2016-11-09 23:52:20 +00008731 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8732 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
Hans Wennborgc0875502015-06-09 00:39:05 +00008733 // In the MS ABI, an explicit instantiation definition can add a dll
8734 // attribute to a template with a previous instantiation declaration.
8735 // MinGW doesn't allow this.
Hans Wennborg17f9b442015-05-27 00:06:45 +00008736 auto *A = cast<InheritableAttr>(
8737 getDLLAttr(Specialization)->clone(getASTContext()));
8738 A->setInherited(true);
8739 Def->addAttr(A);
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008740 dllExportImportClassTemplateSpecialization(*this, Def);
Hans Wennborg17f9b442015-05-27 00:06:45 +00008741 }
8742 }
8743
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008744 // Fix a TSK_ImplicitInstantiation followed by a
8745 // TSK_ExplicitInstantiationDefinition
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00008746 bool NewlyDLLExported =
8747 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
8748 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008749 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8750 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
8751 // In the MS ABI, an explicit instantiation definition can add a dll
8752 // attribute to a template with a previous implicit instantiation.
8753 // MinGW doesn't allow this. We limit clang to only adding dllexport, to
8754 // avoid potentially strange codegen behavior. For example, if we extend
8755 // this conditional to dllimport, and we have a source file calling a
8756 // method on an implicitly instantiated template class instance and then
8757 // declaring a dllimport explicit instantiation definition for the same
8758 // template class, the codegen for the method call will not respect the
8759 // dllimport, while it will with cl. The Def will already have the DLL
8760 // attribute, since the Def and Specialization will be the same in the
8761 // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
8762 // attribute to the Specialization; we just need to make it take effect.
8763 assert(Def == Specialization &&
8764 "Def and Specialization should match for implicit instantiation");
8765 dllExportImportClassTemplateSpecialization(*this, Def);
8766 }
8767
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00008768 // Set the template specialization kind. Make sure it is set before
8769 // instantiating the members which will trigger ASTConsumer callbacks.
8770 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregor12e49d32009-10-15 22:53:21 +00008771 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00008772 } else {
8773
8774 // Set the template specialization kind.
8775 Specialization->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00008776 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008777
John McCall48871652010-08-21 09:40:31 +00008778 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00008779}
8780
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008781// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00008782DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00008783Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00008784 SourceLocation ExternLoc,
8785 SourceLocation TemplateLoc,
Faisal Vali090da2d2018-01-01 18:23:28 +00008786 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008787 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00008788 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008789 IdentifierInfo *Name,
8790 SourceLocation NameLoc,
8791 AttributeList *Attr) {
8792
Douglas Gregord6ab8742009-05-28 23:31:59 +00008793 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00008794 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00008795 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00008796 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00008797 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00008798 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00008799 SourceLocation(), false, TypeResult(),
Akira Hatanaka12ddcee2017-06-26 18:46:12 +00008800 /*IsTypeSpecifier*/false,
8801 /*IsTemplateParamOrArg*/false);
John McCall7f41d982009-09-11 04:59:25 +00008802 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
8803
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008804 if (!TagD)
8805 return true;
8806
John McCall48871652010-08-21 09:40:31 +00008807 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00008808 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008809
Douglas Gregorb8006faf2009-05-27 17:30:49 +00008810 if (Tag->isInvalidDecl())
8811 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008812
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008813 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
8814 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
8815 if (!Pattern) {
8816 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
8817 << Context.getTypeDeclType(Record);
8818 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
8819 return true;
8820 }
8821
Douglas Gregore47f5a72009-10-14 23:41:34 +00008822 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008823 // If the explicit instantiation is for a class or member class, the
8824 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00008825 // simple-template-id.
8826 //
8827 // C++98 has the same restriction, just worded differently.
8828 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00008829 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008830 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008831
Douglas Gregore47f5a72009-10-14 23:41:34 +00008832 // C++0x [temp.explicit]p2:
8833 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008834 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00008835 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00008836 TemplateSpecializationKind TSK
8837 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8838 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008839
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008840 // C++0x [temp.explicit]p2:
8841 // [...] An explicit instantiation shall appear in an enclosing
8842 // namespace of its template. [...]
8843 //
8844 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008845 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008846
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008847 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008848 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00008849 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008850 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00008851 PrevDecl = Record;
8852 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008853 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00008854 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008855 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008856 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008857 PrevDecl,
8858 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008859 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008860 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008861 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00008862 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008863 return TagD;
8864 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008865
Douglas Gregor12e49d32009-10-15 22:53:21 +00008866 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008867 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00008868 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00008869 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008870 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00008871 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008872 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008873 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00008874 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00008875 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
8876 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00008877 Diag(Pattern->getLocation(), diag::note_forward_declaration)
8878 << Pattern;
8879 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008880 } else {
8881 if (InstantiateClass(NameLoc, Record, Def,
8882 getTemplateInstantiationArgs(Record),
8883 TSK))
8884 return true;
8885
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008886 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00008887 if (!RecordDef)
8888 return true;
8889 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008890 }
8891
Douglas Gregor1d957a32009-10-27 18:42:08 +00008892 // Instantiate all of the members of the class.
8893 InstantiateClassMembers(NameLoc, RecordDef,
8894 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008895
Douglas Gregor88d292c2010-05-13 16:44:06 +00008896 if (TSK == TSK_ExplicitInstantiationDefinition)
8897 MarkVTableUsed(NameLoc, RecordDef, true);
8898
Mike Stump87c57ac2009-05-16 07:39:55 +00008899 // FIXME: We don't have any representation for explicit instantiations of
8900 // member classes. Such a representation is not needed for compilation, but it
8901 // should be available for clients that want to see all of the declarations in
8902 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008903 return TagD;
8904}
8905
John McCallfaf5fb42010-08-26 23:41:50 +00008906DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
8907 SourceLocation ExternLoc,
8908 SourceLocation TemplateLoc,
8909 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00008910 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008911 // TODO: check if/when DNInfo should replace Name.
8912 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8913 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00008914 if (!Name) {
8915 if (!D.isInvalidType())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008916 Diag(D.getDeclSpec().getLocStart(),
Douglas Gregor450f00842009-09-25 18:43:00 +00008917 diag::err_explicit_instantiation_requires_name)
8918 << D.getDeclSpec().getSourceRange()
8919 << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008920
Douglas Gregor450f00842009-09-25 18:43:00 +00008921 return true;
8922 }
8923
8924 // The scope passed in may not be a decl scope. Zip up the scope tree until
8925 // we find one that is.
8926 while ((S->getFlags() & Scope::DeclScope) == 0 ||
8927 (S->getFlags() & Scope::TemplateParamScope) != 0)
8928 S = S->getParent();
8929
8930 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00008931 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
8932 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00008933 if (R.isNull())
8934 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008935
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008936 // C++ [dcl.stc]p1:
Simon Pilgrim6905d222016-12-30 22:55:33 +00008937 // A storage-class-specifier shall not be specified in [...] an explicit
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008938 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00008939 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00008940 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
8941 << Name;
8942 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008943 } else if (D.getDeclSpec().getStorageClassSpec()
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008944 != DeclSpec::SCS_unspecified) {
8945 // Complain about then remove the storage class specifier.
8946 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
8947 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Simon Pilgrim6905d222016-12-30 22:55:33 +00008948
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008949 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00008950 }
8951
Douglas Gregor3c74d412009-10-14 20:14:33 +00008952 // C++0x [temp.explicit]p1:
8953 // [...] An explicit instantiation of a function template shall not use the
8954 // inline or constexpr specifiers.
8955 // Presumably, this also applies to member functions of class templates as
8956 // well.
Richard Smith83c19292011-10-18 03:44:03 +00008957 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008958 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008959 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00008960 diag::err_explicit_instantiation_inline :
8961 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00008962 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00008963 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00008964 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
8965 // not already specified.
8966 Diag(D.getDeclSpec().getConstexprSpecLoc(),
8967 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008968
Richard Smith19a311a2017-02-09 22:47:51 +00008969 // A deduction guide is not on the list of entities that can be explicitly
8970 // instantiated.
8971 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8972 Diag(D.getDeclSpec().getLocStart(), diag::err_deduction_guide_specialized)
8973 << /*explicit instantiation*/ 0;
8974 return true;
8975 }
8976
Douglas Gregore47f5a72009-10-14 23:41:34 +00008977 // C++0x [temp.explicit]p2:
8978 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008979 // definition and an explicit instantiation declaration. An explicit
8980 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00008981 TemplateSpecializationKind TSK
8982 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8983 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008984
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008985 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00008986 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00008987
8988 if (!R->isFunctionType()) {
8989 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008990 // A [...] static data member of a class template can be explicitly
8991 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00008992 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00008993 // C++1y [temp.explicit]p1:
8994 // A [...] variable [...] template specialization can be explicitly
8995 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00008996 if (Previous.isAmbiguous())
8997 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008998
John McCall67c00872009-12-02 08:25:40 +00008999 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00009000 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009001
Larisse Voufo39a1e502013-08-06 01:03:05 +00009002 if (!PrevTemplate) {
9003 if (!Prev || !Prev->isStaticDataMember()) {
9004 // We expect to see a data data member here.
9005 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
9006 << Name;
9007 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9008 P != PEnd; ++P)
9009 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
9010 return true;
9011 }
9012
9013 if (!Prev->getInstantiatedFromStaticDataMember()) {
9014 // FIXME: Check for explicit specialization?
9015 Diag(D.getIdentifierLoc(),
9016 diag::err_explicit_instantiation_data_member_not_instantiated)
9017 << Prev;
9018 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
9019 // FIXME: Can we provide a note showing where this was declared?
9020 return true;
9021 }
9022 } else {
9023 // Explicitly instantiate a variable template.
9024
9025 // C++1y [dcl.spec.auto]p6:
9026 // ... A program that uses auto or decltype(auto) in a context not
9027 // explicitly allowed in this section is ill-formed.
9028 //
9029 // This includes auto-typed variable template instantiations.
9030 if (R->isUndeducedType()) {
9031 Diag(T->getTypeLoc().getLocStart(),
9032 diag::err_auto_not_allowed_var_inst);
9033 return true;
9034 }
9035
Faisal Vali2ab8c152017-12-30 04:15:27 +00009036 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
Richard Smithef985ac2013-09-18 02:10:12 +00009037 // C++1y [temp.explicit]p3:
9038 // If the explicit instantiation is for a variable, the unqualified-id
9039 // in the declaration shall be a template-id.
9040 Diag(D.getIdentifierLoc(),
9041 diag::err_explicit_instantiation_without_template_id)
9042 << PrevTemplate;
9043 Diag(PrevTemplate->getLocation(),
9044 diag::note_explicit_instantiation_here);
9045 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00009046 }
9047
Richard Smithef985ac2013-09-18 02:10:12 +00009048 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00009049 TemplateArgumentListInfo TemplateArgs =
9050 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00009051
Larisse Voufo39a1e502013-08-06 01:03:05 +00009052 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
9053 D.getIdentifierLoc(), TemplateArgs);
9054 if (Res.isInvalid())
9055 return true;
9056
9057 // Ignore access control bits, we don't need them for redeclaration
9058 // checking.
9059 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00009060 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009061
Douglas Gregore47f5a72009-10-14 23:41:34 +00009062 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009063 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00009064 // or a static data member of a class template specialization, the name of
9065 // the class template specialization in the qualified-id for the member
9066 // name shall be a simple-template-id.
9067 //
9068 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00009069 //
Richard Smith5977d872013-09-18 21:55:14 +00009070 // This does not apply to variable template specializations, where the
9071 // template-id is in the unqualified-id instead.
9072 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009073 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00009074 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00009075 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009076
Douglas Gregore47f5a72009-10-14 23:41:34 +00009077 // Check the scope of this explicit instantiation.
9078 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009079
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009080 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00009081 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
9082 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00009083 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00009084 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00009085 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009086 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009087
Larisse Voufo39a1e502013-08-06 01:03:05 +00009088 if (!HasNoEffect) {
9089 // Instantiate static data member or variable template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00009090 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9091 if (PrevTemplate) {
9092 // Merge attributes.
9093 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
9094 ProcessDeclAttributeList(S, Prev, Attr);
9095 }
9096 if (TSK == TSK_ExplicitInstantiationDefinition)
9097 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
9098 }
9099
9100 // Check the new variable specialization against the parsed input.
9101 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
9102 Diag(T->getTypeLoc().getLocStart(),
9103 diag::err_invalid_var_template_spec_type)
9104 << 0 << PrevTemplate << R << Prev->getType();
9105 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
9106 << 2 << PrevTemplate->getDeclName();
9107 return true;
9108 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009109
Douglas Gregor450f00842009-09-25 18:43:00 +00009110 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00009111 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009112 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009113
9114 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00009115 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00009116 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00009117 TemplateArgumentListInfo TemplateArgs;
Faisal Vali2ab8c152017-12-30 04:15:27 +00009118 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00009119 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00009120 HasExplicitTemplateArgs = true;
9121 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009122
Douglas Gregor450f00842009-09-25 18:43:00 +00009123 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009124 // A [...] function [...] can be explicitly instantiated from its template.
9125 // A member function [...] of a class template can be explicitly
9126 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00009127 // template.
John McCall27c11dd2017-06-07 23:00:05 +00009128 UnresolvedSet<8> TemplateMatches;
9129 FunctionDecl *NonTemplateMatch = nullptr;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00009130 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009131 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00009132 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9133 P != PEnd; ++P) {
9134 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00009135 if (!HasExplicitTemplateArgs) {
9136 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Richard Smithbaa47832016-12-01 02:11:49 +00009137 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
9138 /*AdjustExceptionSpec*/true);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00009139 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
John McCall27c11dd2017-06-07 23:00:05 +00009140 if (Method->getPrimaryTemplate()) {
9141 TemplateMatches.addDecl(Method, P.getAccess());
9142 } else {
9143 // FIXME: Can this assert ever happen? Needs a test.
9144 assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
9145 NonTemplateMatch = Method;
9146 }
Douglas Gregord90fd522009-09-25 21:45:23 +00009147 }
Douglas Gregor450f00842009-09-25 18:43:00 +00009148 }
9149 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009150
Douglas Gregor450f00842009-09-25 18:43:00 +00009151 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
9152 if (!FunTmpl)
9153 continue;
9154
Larisse Voufo98b20f12013-07-19 23:00:19 +00009155 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00009156 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009157 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009158 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00009159 (HasExplicitTemplateArgs ? &TemplateArgs
9160 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00009161 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009162 // Keep track of almost-matches.
9163 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +00009164 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +00009165 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00009166 (void)TDK;
9167 continue;
9168 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009169
Artem Belevich64135c32016-12-08 19:38:13 +00009170 // Target attributes are part of the cuda function signature, so
9171 // the cuda target of the instantiated function must match that of its
9172 // template. Given that C++ template deduction does not take
9173 // target attributes into account, we reject candidates here that
9174 // have a different target.
9175 if (LangOpts.CUDA &&
9176 IdentifyCUDATarget(Specialization,
9177 /* IgnoreImplicitHDAttributes = */ true) !=
9178 IdentifyCUDATarget(Attr)) {
9179 FailedCandidates.addCandidate().set(
9180 P.getPair(), FunTmpl->getTemplatedDecl(),
9181 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
9182 continue;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00009183 }
9184
John McCall27c11dd2017-06-07 23:00:05 +00009185 TemplateMatches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00009186 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009187
John McCall27c11dd2017-06-07 23:00:05 +00009188 FunctionDecl *Specialization = NonTemplateMatch;
9189 if (!Specialization) {
9190 // Find the most specialized function template specialization.
9191 UnresolvedSetIterator Result = getMostSpecialized(
9192 TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
9193 D.getIdentifierLoc(),
9194 PDiag(diag::err_explicit_instantiation_not_known) << Name,
9195 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
9196 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00009197
John McCall27c11dd2017-06-07 23:00:05 +00009198 if (Result == TemplateMatches.end())
9199 return true;
John McCall58cc69d2010-01-27 01:50:18 +00009200
John McCall27c11dd2017-06-07 23:00:05 +00009201 // Ignore access control bits, we don't need them for redeclaration checking.
9202 Specialization = cast<FunctionDecl>(*Result);
9203 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009204
Alexey Bataev73983912014-11-06 10:10:50 +00009205 // C++11 [except.spec]p4
9206 // In an explicit instantiation an exception-specification may be specified,
9207 // but is not required.
9208 // If an exception-specification is specified in an explicit instantiation
9209 // directive, it shall be compatible with the exception-specifications of
9210 // other declarations of that function.
9211 if (auto *FPT = R->getAs<FunctionProtoType>())
9212 if (FPT->hasExceptionSpec()) {
9213 unsigned DiagID =
9214 diag::err_mismatched_exception_spec_explicit_instantiation;
9215 if (getLangOpts().MicrosoftExt)
9216 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
9217 bool Result = CheckEquivalentExceptionSpec(
9218 PDiag(DiagID) << Specialization->getType(),
9219 PDiag(diag::note_explicit_instantiation_here),
9220 Specialization->getType()->getAs<FunctionProtoType>(),
9221 Specialization->getLocation(), FPT, D.getLocStart());
9222 // In Microsoft mode, mismatching exception specifications just cause a
9223 // warning.
9224 if (!getLangOpts().MicrosoftExt && Result)
9225 return true;
9226 }
9227
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009228 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009229 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00009230 diag::err_explicit_instantiation_member_function_not_instantiated)
9231 << Specialization
9232 << (Specialization->getTemplateSpecializationKind() ==
9233 TSK_ExplicitSpecialization);
9234 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
9235 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009236 }
9237
Douglas Gregorec9fd132012-01-14 16:38:05 +00009238 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00009239 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
9240 PrevDecl = Specialization;
9241
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009242 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00009243 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00009244 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009245 PrevDecl,
9246 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009247 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00009248 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009249 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009250
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009251 // FIXME: We may still want to build some representation of this
9252 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00009253 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00009254 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009255 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00009256
Rafael Espindola2aa7acf2012-01-04 05:40:59 +00009257 if (Attr)
9258 ProcessDeclAttributeList(S, Specialization, Attr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009259
Hans Wennborgb8304a62017-11-29 23:44:11 +00009260 // In MSVC mode, dllimported explicit instantiation definitions are treated as
9261 // instantiation declarations.
9262 if (TSK == TSK_ExplicitInstantiationDefinition &&
9263 Specialization->hasAttr<DLLImportAttr>() &&
9264 Context.getTargetInfo().getCXXABI().isMicrosoft())
9265 TSK = TSK_ExplicitInstantiationDeclaration;
9266
9267 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9268
Richard Smitheb36ddf2014-04-24 22:45:46 +00009269 if (Specialization->isDefined()) {
9270 // Let the ASTConsumer know that this function has been explicitly
9271 // instantiated now, and its linkage might have changed.
9272 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
9273 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00009274 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009275
Douglas Gregore47f5a72009-10-14 23:41:34 +00009276 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009277 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00009278 // or a static data member of a class template specialization, the name of
9279 // the class template specialization in the qualified-id for the member
9280 // name shall be a simple-template-id.
9281 //
9282 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009283 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Faisal Vali2ab8c152017-12-30 04:15:27 +00009284 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009285 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00009286 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009287 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00009288 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00009289 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009290
Douglas Gregore47f5a72009-10-14 23:41:34 +00009291 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009292 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregore47f5a72009-10-14 23:41:34 +00009293 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009294 D.getIdentifierLoc(),
Douglas Gregore47f5a72009-10-14 23:41:34 +00009295 D.getCXXScopeSpec().isSet());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009296
Douglas Gregor450f00842009-09-25 18:43:00 +00009297 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00009298 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009299}
9300
John McCallfaf5fb42010-08-26 23:41:50 +00009301TypeResult
Faisal Vali090da2d2018-01-01 18:23:28 +00009302Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
John McCall7f41d982009-09-11 04:59:25 +00009303 const CXXScopeSpec &SS, IdentifierInfo *Name,
9304 SourceLocation TagLoc, SourceLocation NameLoc) {
9305 // This has to hold, because SS is expected to be defined.
9306 assert(Name && "Expected a name in a dependent tag");
9307
Aaron Ballman4a979672014-01-03 13:56:08 +00009308 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00009309 if (!NNS)
9310 return true;
9311
Abramo Bagnara6150c882010-05-11 21:36:43 +00009312 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00009313
Douglas Gregorba41d012010-04-24 16:38:41 +00009314 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
9315 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00009316 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00009317 return true;
9318 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00009319
Douglas Gregore7c20652011-03-02 00:47:37 +00009320 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00009321 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00009322 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009323
Douglas Gregore7c20652011-03-02 00:47:37 +00009324 // Create type-source location information for this type.
9325 TypeLocBuilder TLB;
9326 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009327 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00009328 TL.setQualifierLoc(SS.getWithLocInContext(Context));
9329 TL.setNameLoc(NameLoc);
9330 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00009331}
9332
John McCallfaf5fb42010-08-26 23:41:50 +00009333TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009334Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
9335 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00009336 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009337 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00009338 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009339
Richard Smith0bf8a4922011-10-18 20:49:44 +00009340 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9341 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009342 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00009343 diag::warn_cxx98_compat_typename_outside_of_template :
9344 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009345 << FixItHint::CreateRemoval(TypenameLoc);
9346
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009347 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00009348 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
9349 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00009350 if (T.isNull())
9351 return true;
John McCall99b2fe52010-04-29 23:50:39 +00009352
9353 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9354 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00009355 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009356 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009357 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00009358 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00009359 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00009360 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009361 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009362 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00009363 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00009364 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009365
John McCallba7bf592010-08-24 05:47:05 +00009366 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00009367}
9368
John McCallfaf5fb42010-08-26 23:41:50 +00009369TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009370Sema::ActOnTypenameType(Scope *S,
9371 SourceLocation TypenameLoc,
9372 const CXXScopeSpec &SS,
9373 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00009374 TemplateTy TemplateIn,
Richard Smith74f02342017-01-19 21:00:13 +00009375 IdentifierInfo *TemplateII,
9376 SourceLocation TemplateIILoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00009377 SourceLocation LAngleLoc,
9378 ASTTemplateArgsPtr TemplateArgsIn,
9379 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00009380 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9381 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009382 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00009383 diag::warn_cxx98_compat_typename_outside_of_template :
9384 diag::ext_typename_outside_of_template)
9385 << FixItHint::CreateRemoval(TypenameLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009386
Richard Smith74f02342017-01-19 21:00:13 +00009387 // Strangely, non-type results are not ignored by this lookup, so the
9388 // program is ill-formed if it finds an injected-class-name.
Richard Smith62559bd2017-02-01 21:36:38 +00009389 if (TypenameLoc.isValid()) {
9390 auto *LookupRD =
9391 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
9392 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
9393 Diag(TemplateIILoc,
9394 diag::ext_out_of_line_qualified_id_type_names_constructor)
9395 << TemplateII << 0 /*injected-class-name used as template name*/
9396 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
9397 }
Richard Smith74f02342017-01-19 21:00:13 +00009398 }
9399
Douglas Gregorb09518c2011-02-27 22:46:49 +00009400 // Translate the parser's template argument list in our AST format.
9401 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9402 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009403
Douglas Gregorb09518c2011-02-27 22:46:49 +00009404 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009405 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
9406 // Construct a dependent template specialization type.
9407 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00009408 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009409 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
9410 DTN->getQualifier(),
9411 DTN->getIdentifier(),
9412 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009413
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009414 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00009415 TypeLocBuilder Builder;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009416 DependentTemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009417 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009418 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
9419 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00009420 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00009421 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009422 SpecTL.setLAngleLoc(LAngleLoc);
9423 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009424 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9425 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009426 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00009427 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009428
Richard Smith74f02342017-01-19 21:00:13 +00009429 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009430 if (T.isNull())
9431 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009432
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009433 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00009434 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009435 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009436 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009437 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00009438 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009439 SpecTL.setLAngleLoc(LAngleLoc);
9440 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009441 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9442 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009443
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009444 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
9445 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009446 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009447 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Simon Pilgrim6905d222016-12-30 22:55:33 +00009448
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009449 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
9450 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00009451}
9452
Douglas Gregorb09518c2011-02-27 22:46:49 +00009453
Richard Smith6f8d2c62012-05-09 05:17:00 +00009454/// Determine whether this failed name lookup should be treated as being
9455/// disabled by a usage of std::enable_if.
9456static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009457 SourceRange &CondRange, Expr *&Cond) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00009458 // We must be looking for a ::type...
9459 if (!II.isStr("type"))
9460 return false;
9461
9462 // ... within an explicitly-written template specialization...
9463 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
9464 return false;
9465 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00009466 TemplateSpecializationTypeLoc EnableIfTSTLoc =
9467 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
9468 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00009469 return false;
George Burgess IV00f70bd2018-03-01 05:43:23 +00009470 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009471
9472 // ... which names a complete class template declaration...
9473 const TemplateDecl *EnableIfDecl =
9474 EnableIfTST->getTemplateName().getAsTemplateDecl();
9475 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
9476 return false;
9477
9478 // ... called "enable_if".
9479 const IdentifierInfo *EnableIfII =
9480 EnableIfDecl->getDeclName().getAsIdentifierInfo();
9481 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
9482 return false;
9483
9484 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00009485 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009486
9487 // Dig out the condition.
9488 Cond = nullptr;
9489 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
9490 != TemplateArgument::Expression)
9491 return true;
9492
9493 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
9494
9495 // Ignore Boolean literals; they add no value.
9496 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
9497 Cond = nullptr;
9498
Richard Smith6f8d2c62012-05-09 05:17:00 +00009499 return true;
9500}
9501
Douglas Gregor333489b2009-03-27 23:10:48 +00009502/// \brief Build the type that describes a C++ typename specifier,
9503/// e.g., "typename T::type".
9504QualType
Simon Pilgrim6905d222016-12-30 22:55:33 +00009505Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009506 SourceLocation KeywordLoc,
Simon Pilgrim6905d222016-12-30 22:55:33 +00009507 NestedNameSpecifierLoc QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009508 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00009509 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00009510 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009511 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00009512
John McCall0b66eb32010-05-01 00:40:08 +00009513 DeclContext *Ctx = computeDeclContext(SS);
9514 if (!Ctx) {
9515 // If the nested-name-specifier is dependent and couldn't be
9516 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009517 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009518 return Context.getDependentNameType(Keyword,
9519 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009520 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00009521 }
Douglas Gregor333489b2009-03-27 23:10:48 +00009522
John McCall0b66eb32010-05-01 00:40:08 +00009523 // If the nested-name-specifier refers to the current instantiation,
9524 // the "typename" keyword itself is superfluous. In C++03, the
9525 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
9526 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00009527 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00009528
John McCall0b66eb32010-05-01 00:40:08 +00009529 if (RequireCompleteDeclContext(SS, Ctx))
9530 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00009531
9532 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00009533 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00009534 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00009535 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00009536 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00009537 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00009538 case LookupResult::NotFound: {
9539 // If we're looking up 'type' within a template named 'enable_if', produce
9540 // a more specific diagnostic.
9541 SourceRange CondRange;
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009542 Expr *Cond = nullptr;
9543 if (isEnableIf(QualifierLoc, II, CondRange, Cond)) {
9544 // If we have a condition, narrow it down to the specific failed
9545 // condition.
9546 if (Cond) {
9547 Expr *FailedCond;
9548 std::string FailedDescription;
9549 std::tie(FailedCond, FailedDescription) =
Douglas Gregor672281a2017-09-14 23:38:42 +00009550 findFailedBooleanCondition(Cond, /*AllowTopLevelCond=*/true);
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009551
9552 Diag(FailedCond->getExprLoc(),
9553 diag::err_typename_nested_not_found_requirement)
9554 << FailedDescription
9555 << FailedCond->getSourceRange();
9556 return QualType();
9557 }
9558
Richard Smith6f8d2c62012-05-09 05:17:00 +00009559 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009560 << Ctx << CondRange;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009561 return QualType();
9562 }
9563
Douglas Gregore40876a2009-10-13 21:16:44 +00009564 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00009565 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009566 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009567
9568 case LookupResult::FoundUnresolvedValue: {
9569 // We found a using declaration that is a value. Most likely, the using
9570 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009571 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009572 IILoc);
9573 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
9574 << Name << Ctx << FullRange;
9575 if (UnresolvedUsingValueDecl *Using
9576 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009577 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009578 Diag(Loc, diag::note_using_value_decl_missing_typename)
9579 << FixItHint::CreateInsertion(Loc, "typename ");
9580 }
9581 }
9582 // Fall through to create a dependent typename type, from which we can recover
9583 // better.
Galina Kistanova3779cb32017-06-07 06:25:05 +00009584 LLVM_FALLTHROUGH;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009585
Douglas Gregord0d2ee02010-01-15 01:44:47 +00009586 case LookupResult::NotFoundInCurrentInstantiation:
9587 // Okay, it's a member of an unknown instantiation.
Simon Pilgrim6905d222016-12-30 22:55:33 +00009588 return Context.getDependentNameType(Keyword,
9589 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009590 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00009591
9592 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009593 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Richard Smith74f02342017-01-19 21:00:13 +00009594 // C++ [class.qual]p2:
9595 // In a lookup in which function names are not ignored and the
9596 // nested-name-specifier nominates a class C, if the name specified
9597 // after the nested-name-specifier, when looked up in C, is the
9598 // injected-class-name of C [...] then the name is instead considered
9599 // to name the constructor of class C.
9600 //
9601 // Unlike in an elaborated-type-specifier, function names are not ignored
9602 // in typename-specifier lookup. However, they are ignored in all the
9603 // contexts where we form a typename type with no keyword (that is, in
9604 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
9605 //
9606 // FIXME: That's not strictly true: mem-initializer-id lookup does not
9607 // ignore functions, but that appears to be an oversight.
9608 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
9609 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
9610 if (Keyword == ETK_Typename && LookupRD && FoundRD &&
9611 FoundRD->isInjectedClassName() &&
9612 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
9613 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
9614 << &II << 1 << 0 /*'typename' keyword used*/;
9615
Abramo Bagnara6150c882010-05-11 21:36:43 +00009616 // We found a type. Build an ElaboratedType, since the
9617 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00009618 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Richard Smith74f02342017-01-19 21:00:13 +00009619 return Context.getElaboratedType(Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009620 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00009621 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00009622 }
9623
Richard Smithee579842017-01-30 20:39:26 +00009624 // C++ [dcl.type.simple]p2:
9625 // A type-specifier of the form
9626 // typename[opt] nested-name-specifier[opt] template-name
9627 // is a placeholder for a deduced class type [...].
Aaron Ballmanc351fba2017-12-04 20:27:34 +00009628 if (getLangOpts().CPlusPlus17) {
Richard Smithee579842017-01-30 20:39:26 +00009629 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
9630 return Context.getElaboratedType(
9631 Keyword, QualifierLoc.getNestedNameSpecifier(),
9632 Context.getDeducedTemplateSpecializationType(TemplateName(TD),
9633 QualType(), false));
9634 }
9635 }
Richard Smith600b5262017-01-26 20:40:47 +00009636
Douglas Gregor333489b2009-03-27 23:10:48 +00009637 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00009638 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00009639 break;
9640
9641 case LookupResult::FoundOverloaded:
9642 DiagID = diag::err_typename_nested_not_type;
9643 Referenced = *Result.begin();
9644 break;
9645
John McCall6538c932009-10-10 05:48:19 +00009646 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00009647 return QualType();
9648 }
9649
9650 // If we get here, it's because name lookup did not find a
9651 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009652 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00009653 IILoc);
9654 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00009655 if (Referenced)
9656 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
9657 << Name;
9658 return QualType();
9659}
Douglas Gregor15acfb92009-08-06 16:20:37 +00009660
9661namespace {
9662 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00009663 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00009664 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00009665 SourceLocation Loc;
9666 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00009667
Douglas Gregor15acfb92009-08-06 16:20:37 +00009668 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00009669 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009670
Mike Stump11289f42009-09-09 15:08:12 +00009671 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00009672 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00009673 DeclarationName Entity)
9674 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00009675 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00009676
9677 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00009678 /// transformed.
9679 ///
9680 /// For the purposes of type reconstruction, a type has already been
9681 /// transformed if it is NULL or if it is not dependent.
9682 bool AlreadyTransformed(QualType T) {
9683 return T.isNull() || !T->isDependentType();
9684 }
Mike Stump11289f42009-09-09 15:08:12 +00009685
9686 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00009687 /// rebuilt.
9688 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00009689
Douglas Gregor15acfb92009-08-06 16:20:37 +00009690 /// \brief Returns the name of the entity whose type is being rebuilt.
9691 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00009692
Douglas Gregoref6ab412009-10-27 06:26:26 +00009693 /// \brief Sets the "base" location and entity when that
9694 /// information is known based on another transformation.
9695 void setBase(SourceLocation Loc, DeclarationName Entity) {
9696 this->Loc = Loc;
9697 this->Entity = Entity;
9698 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009699
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00009700 ExprResult TransformLambdaExpr(LambdaExpr *E) {
9701 // Lambdas never need to be transformed.
9702 return E;
9703 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00009704 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009705} // end anonymous namespace
Douglas Gregor15acfb92009-08-06 16:20:37 +00009706
Douglas Gregor15acfb92009-08-06 16:20:37 +00009707/// \brief Rebuilds a type within the context of the current instantiation.
9708///
Mike Stump11289f42009-09-09 15:08:12 +00009709/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00009710/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00009711/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00009712/// partial specialization thereof). This routine will rebuild that type now
9713/// that we have entered the declarator's scope, which may produce different
9714/// canonical types, e.g.,
9715///
9716/// \code
9717/// template<typename T>
9718/// struct X {
9719/// typedef T* pointer;
9720/// pointer data();
9721/// };
9722///
9723/// template<typename T>
9724/// typename X<T>::pointer X<T>::data() { ... }
9725/// \endcode
9726///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00009727/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00009728/// since we do not know that we can look into X<T> when we parsed the type.
9729/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00009730/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00009731/// as the canonical type of T*, allowing the return types of the out-of-line
9732/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00009733TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
9734 SourceLocation Loc,
9735 DeclarationName Name) {
9736 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00009737 return T;
Mike Stump11289f42009-09-09 15:08:12 +00009738
Douglas Gregor15acfb92009-08-06 16:20:37 +00009739 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
9740 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00009741}
Douglas Gregorbe999392009-09-15 16:23:51 +00009742
John McCalldadc5752010-08-24 06:29:42 +00009743ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00009744 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
9745 DeclarationName());
9746 return Rebuilder.TransformExpr(E);
9747}
9748
John McCall99b2fe52010-04-29 23:50:39 +00009749bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00009750 if (SS.isInvalid())
Douglas Gregor10176412011-02-25 16:07:42 +00009751 return true;
John McCall2408e322010-04-27 00:57:59 +00009752
Douglas Gregor10176412011-02-25 16:07:42 +00009753 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00009754 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
9755 DeclarationName());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009756 NestedNameSpecifierLoc Rebuilt
Douglas Gregor10176412011-02-25 16:07:42 +00009757 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009758 if (!Rebuilt)
Douglas Gregor10176412011-02-25 16:07:42 +00009759 return true;
John McCall99b2fe52010-04-29 23:50:39 +00009760
Douglas Gregor10176412011-02-25 16:07:42 +00009761 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00009762 return false;
John McCall2408e322010-04-27 00:57:59 +00009763}
9764
Douglas Gregor041b0842011-10-14 15:31:12 +00009765/// \brief Rebuild the template parameters now that we know we're in a current
9766/// instantiation.
9767bool Sema::RebuildTemplateParamsInCurrentInstantiation(
9768 TemplateParameterList *Params) {
9769 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
9770 Decl *Param = Params->getParam(I);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009771
Douglas Gregor041b0842011-10-14 15:31:12 +00009772 // There is nothing to rebuild in a type parameter.
9773 if (isa<TemplateTypeParmDecl>(Param))
9774 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009775
Douglas Gregor041b0842011-10-14 15:31:12 +00009776 // Rebuild the template parameter list of a template template parameter.
Simon Pilgrim6905d222016-12-30 22:55:33 +00009777 if (TemplateTemplateParmDecl *TTP
Douglas Gregor041b0842011-10-14 15:31:12 +00009778 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
9779 if (RebuildTemplateParamsInCurrentInstantiation(
9780 TTP->getTemplateParameters()))
9781 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009782
Douglas Gregor041b0842011-10-14 15:31:12 +00009783 continue;
9784 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009785
Douglas Gregor041b0842011-10-14 15:31:12 +00009786 // Rebuild the type of a non-type template parameter.
9787 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009788 TypeSourceInfo *NewTSI
9789 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
9790 NTTP->getLocation(),
Douglas Gregor041b0842011-10-14 15:31:12 +00009791 NTTP->getDeclName());
9792 if (!NewTSI)
9793 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009794
Douglas Gregor041b0842011-10-14 15:31:12 +00009795 if (NewTSI != NTTP->getTypeSourceInfo()) {
9796 NTTP->setTypeSourceInfo(NewTSI);
9797 NTTP->setType(NewTSI->getType());
9798 }
9799 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009800
Douglas Gregor041b0842011-10-14 15:31:12 +00009801 return false;
9802}
9803
Douglas Gregorbe999392009-09-15 16:23:51 +00009804/// \brief Produces a formatted string that describes the binding of
9805/// template parameters to template arguments.
9806std::string
9807Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9808 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009809 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00009810}
9811
9812std::string
9813Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9814 const TemplateArgument *Args,
9815 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009816 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +00009817 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +00009818
Douglas Gregore62e6a02009-11-11 19:13:48 +00009819 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00009820 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009821
Douglas Gregorbe999392009-09-15 16:23:51 +00009822 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00009823 if (I >= NumArgs)
9824 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009825
Douglas Gregorbe999392009-09-15 16:23:51 +00009826 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00009827 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +00009828 else
Douglas Gregor0192c232010-12-20 16:52:59 +00009829 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009830
Douglas Gregorbe999392009-09-15 16:23:51 +00009831 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +00009832 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +00009833 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +00009834 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +00009835 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009836
Douglas Gregor0192c232010-12-20 16:52:59 +00009837 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +00009838 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +00009839 }
Douglas Gregor0192c232010-12-20 16:52:59 +00009840
9841 Out << ']';
9842 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +00009843}
Francois Pichet1c229c02011-04-22 22:18:13 +00009844
Richard Smithe40f2ba2013-08-07 21:41:30 +00009845void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
9846 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +00009847 if (!FD)
9848 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +00009849
Justin Lebar28f09c52016-10-10 16:26:08 +00009850 auto LPT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00009851
9852 // Take tokens to avoid allocations
9853 LPT->Toks.swap(Toks);
9854 LPT->D = FnD;
Justin Lebar28f09c52016-10-10 16:26:08 +00009855 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00009856
9857 FD->setLateTemplateParsed(true);
9858}
9859
9860void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
9861 if (!FD)
9862 return;
9863 FD->setLateTemplateParsed(false);
9864}
Francois Pichet1c229c02011-04-22 22:18:13 +00009865
9866bool Sema::IsInsideALocalClassWithinATemplateFunction() {
9867 DeclContext *DC = CurContext;
9868
9869 while (DC) {
9870 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
9871 const FunctionDecl *FD = RD->isLocalClass();
9872 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
9873 } else if (DC->isTranslationUnit() || DC->isNamespace())
9874 return false;
9875
9876 DC = DC->getParent();
9877 }
9878 return false;
9879}
Richard Smith6739a102016-05-05 00:56:12 +00009880
Benjamin Kramera0a13c32016-08-06 11:21:04 +00009881namespace {
Richard Smith6739a102016-05-05 00:56:12 +00009882/// \brief Walk the path from which a declaration was instantiated, and check
9883/// that every explicit specialization along that path is visible. This enforces
9884/// C++ [temp.expl.spec]/6:
9885///
9886/// If a template, a member template or a member of a class template is
9887/// explicitly specialized then that specialization shall be declared before
9888/// the first use of that specialization that would cause an implicit
9889/// instantiation to take place, in every translation unit in which such a
9890/// use occurs; no diagnostic is required.
9891///
9892/// and also C++ [temp.class.spec]/1:
9893///
9894/// A partial specialization shall be declared before the first use of a
9895/// class template specialization that would make use of the partial
9896/// specialization as the result of an implicit or explicit instantiation
9897/// in every translation unit in which such a use occurs; no diagnostic is
9898/// required.
9899class ExplicitSpecializationVisibilityChecker {
9900 Sema &S;
9901 SourceLocation Loc;
9902 llvm::SmallVector<Module *, 8> Modules;
9903
9904public:
9905 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
9906 : S(S), Loc(Loc) {}
9907
9908 void check(NamedDecl *ND) {
9909 if (auto *FD = dyn_cast<FunctionDecl>(ND))
9910 return checkImpl(FD);
9911 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
9912 return checkImpl(RD);
9913 if (auto *VD = dyn_cast<VarDecl>(ND))
9914 return checkImpl(VD);
9915 if (auto *ED = dyn_cast<EnumDecl>(ND))
9916 return checkImpl(ED);
9917 }
9918
9919private:
9920 void diagnose(NamedDecl *D, bool IsPartialSpec) {
9921 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
9922 : Sema::MissingImportKind::ExplicitSpecialization;
9923 const bool Recover = true;
9924
9925 // If we got a custom set of modules (because only a subset of the
9926 // declarations are interesting), use them, otherwise let
9927 // diagnoseMissingImport intelligently pick some.
9928 if (Modules.empty())
9929 S.diagnoseMissingImport(Loc, D, Kind, Recover);
9930 else
9931 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
9932 }
9933
9934 // Check a specific declaration. There are three problematic cases:
9935 //
9936 // 1) The declaration is an explicit specialization of a template
9937 // specialization.
9938 // 2) The declaration is an explicit specialization of a member of an
9939 // templated class.
9940 // 3) The declaration is an instantiation of a template, and that template
9941 // is an explicit specialization of a member of a templated class.
9942 //
9943 // We don't need to go any deeper than that, as the instantiation of the
9944 // surrounding class / etc is not triggered by whatever triggered this
9945 // instantiation, and thus should be checked elsewhere.
9946 template<typename SpecDecl>
9947 void checkImpl(SpecDecl *Spec) {
9948 bool IsHiddenExplicitSpecialization = false;
9949 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
9950 IsHiddenExplicitSpecialization =
9951 Spec->getMemberSpecializationInfo()
9952 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
Richard Smith54f04402017-05-18 02:29:20 +00009953 : !S.hasVisibleExplicitSpecialization(Spec, &Modules);
Richard Smith6739a102016-05-05 00:56:12 +00009954 } else {
9955 checkInstantiated(Spec);
9956 }
9957
9958 if (IsHiddenExplicitSpecialization)
9959 diagnose(Spec->getMostRecentDecl(), false);
9960 }
9961
9962 void checkInstantiated(FunctionDecl *FD) {
9963 if (auto *TD = FD->getPrimaryTemplate())
9964 checkTemplate(TD);
9965 }
9966
9967 void checkInstantiated(CXXRecordDecl *RD) {
9968 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
9969 if (!SD)
9970 return;
9971
9972 auto From = SD->getSpecializedTemplateOrPartial();
9973 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
9974 checkTemplate(TD);
9975 else if (auto *TD =
9976 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
9977 if (!S.hasVisibleDeclaration(TD))
9978 diagnose(TD, true);
9979 checkTemplate(TD);
9980 }
9981 }
9982
9983 void checkInstantiated(VarDecl *RD) {
9984 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
9985 if (!SD)
9986 return;
9987
9988 auto From = SD->getSpecializedTemplateOrPartial();
9989 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
9990 checkTemplate(TD);
9991 else if (auto *TD =
9992 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
9993 if (!S.hasVisibleDeclaration(TD))
9994 diagnose(TD, true);
9995 checkTemplate(TD);
9996 }
9997 }
9998
9999 void checkInstantiated(EnumDecl *FD) {}
10000
10001 template<typename TemplDecl>
10002 void checkTemplate(TemplDecl *TD) {
10003 if (TD->isMemberSpecialization()) {
10004 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
10005 diagnose(TD->getMostRecentDecl(), false);
10006 }
10007 }
10008};
Benjamin Kramera0a13c32016-08-06 11:21:04 +000010009} // end anonymous namespace
Richard Smith6739a102016-05-05 00:56:12 +000010010
10011void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
10012 if (!getLangOpts().Modules)
10013 return;
10014
10015 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
10016}
10017
10018/// \brief Check whether a template partial specialization that we've discovered
10019/// is hidden, and produce suitable diagnostics if so.
10020void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
10021 NamedDecl *Spec) {
10022 llvm::SmallVector<Module *, 8> Modules;
10023 if (!hasVisibleDeclaration(Spec, &Modules))
10024 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
10025 MissingImportKind::PartialSpecialization,
10026 /*Recover*/true);
10027}