blob: 3f9dc989103faa4599d8762c1580b7e7b05932fe [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 {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000049/// [temp.constr.decl]p2: A template's associated constraints are
Hubert Tong5a8ec4e2017-02-10 02:46:19 +000050/// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000068/// Determine whether the declaration found is acceptable as the name
Douglas Gregorb7bfe792009-09-02 22:59:36 +000069/// 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
Richard Smithcbebd622018-05-14 20:52:48 +0000108 // 'using Dependent::foo;' can resolve to a template name.
109 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
110 // injected-class-name).
111 if (isa<UnresolvedUsingValueDecl>(D))
112 return D;
113
Craig Topperc3ec1492014-05-26 06:22:03 +0000114 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000115}
116
Simon Pilgrim6905d222016-12-30 22:55:33 +0000117void Sema::FilterAcceptableTemplateNames(LookupResult &R,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000118 bool AllowFunctionTemplates) {
Douglas Gregor41f90302010-04-12 20:54:26 +0000119 // The set of class templates we've already seen.
120 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCalle66edc12009-11-24 19:00:30 +0000121 LookupResult::Filter filter = R.makeFilter();
122 while (filter.hasNext()) {
123 NamedDecl *Orig = filter.next();
Simon Pilgrim6905d222016-12-30 22:55:33 +0000124 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000125 AllowFunctionTemplates);
John McCalle66edc12009-11-24 19:00:30 +0000126 if (!Repl)
127 filter.erase();
Douglas Gregor41f90302010-04-12 20:54:26 +0000128 else if (Repl != Orig) {
129
130 // C++ [temp.local]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000131 // A lookup that finds an injected-class-name (10.2) can result in an
Douglas Gregor41f90302010-04-12 20:54:26 +0000132 // ambiguity in certain cases (for example, if it is found in more than
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000133 // one base class). If all of the injected-class-names that are found
134 // refer to specializations of the same class template, and if the name
Richard Smith3f1b5d02011-05-05 21:57:07 +0000135 // is used as a template-name, the reference refers to the class
136 // template itself and not a specialization thereof, and is not
Douglas Gregor41f90302010-04-12 20:54:26 +0000137 // ambiguous.
Douglas Gregor41f90302010-04-12 20:54:26 +0000138 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
David Blaikie82e95a32014-11-19 07:49:47 +0000139 if (!ClassTemplates.insert(ClassTmpl).second) {
Douglas Gregor41f90302010-04-12 20:54:26 +0000140 filter.erase();
141 continue;
142 }
John McCallbd8062d2010-08-13 07:02:08 +0000143
144 // FIXME: we promote access to public here as a workaround to
145 // the fact that LookupResult doesn't let us remember that we
146 // found this template through a particular injected class name,
147 // which means we end up doing nasty things to the invariants.
148 // Pretending that access is public is *much* safer.
149 filter.replace(Repl, AS_public);
Douglas Gregor41f90302010-04-12 20:54:26 +0000150 }
John McCalle66edc12009-11-24 19:00:30 +0000151 }
152 filter.done();
153}
154
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000155bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
156 bool AllowFunctionTemplates) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000157 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000158 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000159 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +0000160
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000161 return false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000162}
163
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000164TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000165 CXXScopeSpec &SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000166 bool hasTemplateKeyword,
Richard Smithc08b6932018-04-27 02:00:13 +0000167 const UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +0000168 ParsedType ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000169 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000170 TemplateTy &TemplateResult,
171 bool &MemberOfUnknownSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000172 assert(getLangOpts().CPlusPlus && "No template names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000173
Douglas Gregor3cf81312009-11-03 23:16:33 +0000174 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000175 MemberOfUnknownSpecialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000176
Douglas Gregor3cf81312009-11-03 23:16:33 +0000177 switch (Name.getKind()) {
Faisal Vali2ab8c152017-12-30 04:15:27 +0000178 case UnqualifiedIdKind::IK_Identifier:
Douglas Gregor3cf81312009-11-03 23:16:33 +0000179 TName = DeclarationName(Name.Identifier);
180 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000181
Faisal Vali2ab8c152017-12-30 04:15:27 +0000182 case UnqualifiedIdKind::IK_OperatorFunctionId:
Douglas Gregor3cf81312009-11-03 23:16:33 +0000183 TName = Context.DeclarationNames.getCXXOperatorName(
184 Name.OperatorFunctionId.Operator);
185 break;
186
Faisal Vali2ab8c152017-12-30 04:15:27 +0000187 case UnqualifiedIdKind::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000188 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
189 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000190
Douglas Gregor3cf81312009-11-03 23:16:33 +0000191 default:
192 return TNK_Non_template;
193 }
Mike Stump11289f42009-09-09 15:08:12 +0000194
John McCallba7bf592010-08-24 05:47:05 +0000195 QualType ObjectType = ObjectTypePtr.get();
Mike Stump11289f42009-09-09 15:08:12 +0000196
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000197 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
Richard Smith79810042018-05-11 02:43:08 +0000198 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
199 MemberOfUnknownSpecialization))
200 return TNK_Non_template;
John McCallfb3f9ba2010-08-28 20:17:00 +0000201 if (R.empty()) return TNK_Non_template;
202 if (R.isAmbiguous()) {
203 // Suppress diagnostics; we'll redo this lookup later.
John McCalldcc71402010-08-13 02:23:42 +0000204 R.suppressDiagnostics();
John McCallfb3f9ba2010-08-28 20:17:00 +0000205
206 // FIXME: we might have ambiguous templates, in which case we
207 // should at least parse them properly!
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000208 return TNK_Non_template;
John McCalldcc71402010-08-13 02:23:42 +0000209 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000210
John McCalld28ae272009-12-02 08:04:21 +0000211 TemplateName Template;
212 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000213
John McCalld28ae272009-12-02 08:04:21 +0000214 unsigned ResultCount = R.end() - R.begin();
215 if (ResultCount > 1) {
216 // We assume that we'll preserve the qualifier from a function
217 // template name in other ways.
218 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
219 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000220
221 // We'll do this lookup again later.
222 R.suppressDiagnostics();
Richard Smithcbebd622018-05-14 20:52:48 +0000223 } else if (isa<UnresolvedUsingValueDecl>((*R.begin())->getUnderlyingDecl())) {
224 // We don't yet know whether this is a template-name or not.
225 MemberOfUnknownSpecialization = true;
226 return TNK_Non_template;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000227 } else {
John McCalld28ae272009-12-02 08:04:21 +0000228 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
229
230 if (SS.isSet() && !SS.isInvalid()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000231 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000232 Template = Context.getQualifiedTemplateName(Qualifier,
233 hasTemplateKeyword, TD);
John McCalld28ae272009-12-02 08:04:21 +0000234 } else {
235 Template = TemplateName(TD);
236 }
237
John McCalldcc71402010-08-13 02:23:42 +0000238 if (isa<FunctionTemplateDecl>(TD)) {
John McCalld28ae272009-12-02 08:04:21 +0000239 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000240
241 // We'll do this lookup again later.
242 R.suppressDiagnostics();
243 } else {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000244 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000245 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
Faisal Valia534f072018-04-26 00:42:40 +0000246 isa<BuiltinTemplateDecl>(TD));
Larisse Voufo39a1e502013-08-06 01:03:05 +0000247 TemplateKind =
Faisal Valia534f072018-04-26 00:42:40 +0000248 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
John McCalld28ae272009-12-02 08:04:21 +0000249 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000250 }
Mike Stump11289f42009-09-09 15:08:12 +0000251
John McCalld28ae272009-12-02 08:04:21 +0000252 TemplateResult = TemplateTy::make(Template);
253 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000254}
255
Richard Smith278890f2017-02-10 20:39:58 +0000256bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
257 SourceLocation NameLoc,
258 ParsedTemplateTy *Template) {
259 CXXScopeSpec SS;
260 bool MemberOfUnknownSpecialization = false;
261
262 // We could use redeclaration lookup here, but we don't need to: the
263 // syntactic form of a deduction guide is enough to identify it even
264 // if we can't look up the template name at all.
265 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
Richard Smith79810042018-05-11 02:43:08 +0000266 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
267 /*EnteringContext*/ false,
268 MemberOfUnknownSpecialization))
269 return false;
Richard Smith278890f2017-02-10 20:39:58 +0000270
271 if (R.empty()) return false;
272 if (R.isAmbiguous()) {
273 // FIXME: Diagnose an ambiguity if we find at least one template.
274 R.suppressDiagnostics();
275 return false;
276 }
277
278 // We only treat template-names that name type templates as valid deduction
279 // guide names.
280 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
281 if (!TD || !getAsTypeTemplateDecl(TD))
282 return false;
283
284 if (Template)
285 *Template = TemplateTy::make(TemplateName(TD));
286 return true;
287}
288
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000289bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
Douglas Gregor18473f32010-01-12 21:28:44 +0000290 SourceLocation IILoc,
291 Scope *S,
292 const CXXScopeSpec *SS,
293 TemplateTy &SuggestedTemplate,
294 TemplateNameKind &SuggestedKind) {
295 // We can't recover unless there's a dependent scope specifier preceding the
296 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000297 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000298 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
299 computeDeclContext(*SS))
300 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000301
Douglas Gregor18473f32010-01-12 21:28:44 +0000302 // The code is missing a 'template' keyword prior to the dependent template
303 // name.
304 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
305 Diag(IILoc, diag::err_template_kw_missing)
306 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000307 << FixItHint::CreateInsertion(IILoc, "template ");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000308 SuggestedTemplate
Douglas Gregor18473f32010-01-12 21:28:44 +0000309 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
310 SuggestedKind = TNK_Dependent_template_name;
311 return true;
312}
313
Richard Smith79810042018-05-11 02:43:08 +0000314bool Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000315 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000316 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000317 bool EnteringContext,
Richard Smith79810042018-05-11 02:43:08 +0000318 bool &MemberOfUnknownSpecialization,
319 SourceLocation TemplateKWLoc) {
John McCalle66edc12009-11-24 19:00:30 +0000320 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000321 MemberOfUnknownSpecialization = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000322 DeclContext *LookupCtx = nullptr;
Richard Smith79810042018-05-11 02:43:08 +0000323 bool IsDependent = false;
John McCalle66edc12009-11-24 19:00:30 +0000324 if (!ObjectType.isNull()) {
325 // This nested-name-specifier occurs in a member access expression, e.g.,
326 // x->B::f, and we are looking into the type of the object.
327 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
328 LookupCtx = computeDeclContext(ObjectType);
Richard Smith79810042018-05-11 02:43:08 +0000329 IsDependent = !LookupCtx;
330 assert((IsDependent || !ObjectType->isIncompleteType() ||
Richard Smith5ed79562013-06-07 20:03:01 +0000331 ObjectType->castAs<TagType>()->isBeingDefined()) &&
John McCalle66edc12009-11-24 19:00:30 +0000332 "Caller should have completed object type");
Simon Pilgrim6905d222016-12-30 22:55:33 +0000333
Douglas Gregorbf3a8262012-01-12 16:11:24 +0000334 // Template names cannot appear inside an Objective-C class or object type.
335 if (ObjectType->isObjCObjectOrInterfaceType()) {
336 Found.clear();
Richard Smith79810042018-05-11 02:43:08 +0000337 return false;
Douglas Gregorbf3a8262012-01-12 16:11:24 +0000338 }
John McCalle66edc12009-11-24 19:00:30 +0000339 } else if (SS.isSet()) {
340 // This nested-name-specifier occurs after another nested-name-specifier,
341 // so long into the context associated with the prior nested-name-specifier.
342 LookupCtx = computeDeclContext(SS, EnteringContext);
Richard Smith79810042018-05-11 02:43:08 +0000343 IsDependent = !LookupCtx;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000344
John McCalle66edc12009-11-24 19:00:30 +0000345 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000346 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
Richard Smith79810042018-05-11 02:43:08 +0000347 return true;
John McCalle66edc12009-11-24 19:00:30 +0000348 }
349
350 bool ObjectTypeSearchedInScope = false;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000351 bool AllowFunctionTemplatesInLookup = true;
John McCalle66edc12009-11-24 19:00:30 +0000352 if (LookupCtx) {
353 // Perform "qualified" name lookup into the declaration context we
354 // computed, which is either the type of the base of a member access
355 // expression or the declaration context associated with a prior
356 // nested-name-specifier.
357 LookupQualifiedName(Found, LookupCtx);
Simon Pilgrim6905d222016-12-30 22:55:33 +0000358
Richard Smith79810042018-05-11 02:43:08 +0000359 // FIXME: The C++ standard does not clearly specify what happens in the
360 // case where the object type is dependent, and implementations vary. In
361 // Clang, we treat a name after a . or -> as a template-name if lookup
362 // finds a non-dependent member or member of the current instantiation that
363 // is a type template, or finds no such members and lookup in the context
364 // of the postfix-expression finds a type template. In the latter case, the
365 // name is nonetheless dependent, and we may resolve it to a member of an
366 // unknown specialization when we come to instantiate the template.
367 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
John McCalle66edc12009-11-24 19:00:30 +0000368 }
369
Richard Smith79810042018-05-11 02:43:08 +0000370 if (!SS.isSet() && (ObjectType.isNull() || Found.empty())) {
371 // C++ [basic.lookup.classref]p1:
372 // In a class member access expression (5.2.5), if the . or -> token is
373 // immediately followed by an identifier followed by a <, the
374 // identifier must be looked up to determine whether the < is the
375 // beginning of a template argument list (14.2) or a less-than operator.
376 // The identifier is first looked up in the class of the object
377 // expression. If the identifier is not found, it is then looked up in
378 // the context of the entire postfix-expression and shall name a class
379 // template.
380 if (S)
381 LookupName(Found, S);
382
383 if (!ObjectType.isNull()) {
384 // FIXME: We should filter out all non-type templates here, particularly
385 // variable templates and concepts. But the exclusion of alias templates
386 // and template template parameters is a wording defect.
387 AllowFunctionTemplatesInLookup = false;
388 ObjectTypeSearchedInScope = true;
389 }
390
391 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
392 }
393
394 if (Found.empty() && !IsDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000395 // If we did not find any names, attempt to correct any typos.
396 DeclarationName Name = Found.getLookupName();
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000397 Found.clear();
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000398 // Simple filter callback that, for keywords, only accepts the C++ *_cast
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000399 auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
400 FilterCCC->WantTypeSpecifiers = false;
401 FilterCCC->WantExpressionKeywords = false;
402 FilterCCC->WantRemainingKeywords = false;
403 FilterCCC->WantCXXNamedCasts = true;
404 if (TypoCorrection Corrected = CorrectTypo(
405 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
406 std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000407 Found.setLookupName(Corrected.getCorrection());
Richard Smithde6d6c42015-12-29 19:43:10 +0000408 if (auto *ND = Corrected.getFoundDecl())
409 Found.addDecl(ND);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000410 FilterAcceptableTemplateNames(Found);
John McCalle9cccd82010-06-16 08:42:20 +0000411 if (!Found.empty()) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000412 if (LookupCtx) {
Richard Smithf9b15102013-08-17 00:46:16 +0000413 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
414 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000415 Name.getAsString() == CorrectedStr;
Richard Smithf9b15102013-08-17 00:46:16 +0000416 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
417 << Name << LookupCtx << DroppedSpecifier
418 << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000419 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000420 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000421 }
John McCalle9cccd82010-06-16 08:42:20 +0000422 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000423 } else {
Douglas Gregorc048c522010-06-29 19:27:42 +0000424 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000425 }
426 }
427
Richard Smith79810042018-05-11 02:43:08 +0000428 NamedDecl *ExampleLookupResult =
429 Found.empty() ? nullptr : Found.getRepresentativeDecl();
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000430 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000431 if (Found.empty()) {
Richard Smith79810042018-05-11 02:43:08 +0000432 if (IsDependent) {
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000433 MemberOfUnknownSpecialization = true;
Richard Smith79810042018-05-11 02:43:08 +0000434 return false;
435 }
436
437 // If a 'template' keyword was used, a lookup that finds only non-template
438 // names is an error.
439 if (ExampleLookupResult && TemplateKWLoc.isValid()) {
440 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
441 << Found.getLookupName() << SS.getRange();
Richard Smithcbebd622018-05-14 20:52:48 +0000442 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
Richard Smith79810042018-05-11 02:43:08 +0000443 diag::note_template_kw_refers_to_non_template)
444 << Found.getLookupName();
445 return true;
446 }
447
448 return false;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000449 }
John McCalle66edc12009-11-24 19:00:30 +0000450
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000451 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
Richard Smithe7d67f22013-09-03 21:22:41 +0000452 !getLangOpts().CPlusPlus11) {
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000453 // C++03 [basic.lookup.classref]p1:
John McCalle66edc12009-11-24 19:00:30 +0000454 // [...] If the lookup in the class of the object expression finds a
455 // template, the name is also looked up in the context of the entire
456 // postfix-expression and [...]
457 //
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000458 // Note: C++11 does not perform this second lookup.
John McCalle66edc12009-11-24 19:00:30 +0000459 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
460 LookupOrdinaryName);
461 LookupName(FoundOuter, S);
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000462 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000463
John McCalle66edc12009-11-24 19:00:30 +0000464 if (FoundOuter.empty()) {
465 // - if the name is not found, the name found in the class of the
466 // object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000467 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
468 FoundOuter.isAmbiguous()) {
John McCalle66edc12009-11-24 19:00:30 +0000469 // - if the name is found in the context of the entire
470 // postfix-expression and does not name a class template, the name
471 // found in the class of the object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000472 FoundOuter.clear();
John McCalle9cccd82010-06-16 08:42:20 +0000473 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000474 // - if the name found is a class template, it must refer to the same
475 // entity as the one found in the class of the object expression,
476 // otherwise the program is ill-formed.
477 if (!Found.isSingleResult() ||
478 Found.getFoundDecl()->getCanonicalDecl()
479 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000480 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000481 diag::ext_nested_name_member_ref_lookup_ambiguous)
482 << Found.getLookupName()
483 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000484 Diag(Found.getRepresentativeDecl()->getLocation(),
485 diag::note_ambig_member_ref_object_type)
486 << ObjectType;
487 Diag(FoundOuter.getFoundDecl()->getLocation(),
488 diag::note_ambig_member_ref_scope);
489
490 // Recover by taking the template that we found in the object
491 // expression's type.
492 }
493 }
494 }
Richard Smith79810042018-05-11 02:43:08 +0000495
496 return false;
John McCalle66edc12009-11-24 19:00:30 +0000497}
498
Richard Smith42bc73a2017-05-10 02:30:28 +0000499void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
500 SourceLocation Less,
501 SourceLocation Greater) {
502 if (TemplateName.isInvalid())
503 return;
504
505 DeclarationNameInfo NameInfo;
506 CXXScopeSpec SS;
507 LookupNameKind LookupKind;
508
509 DeclContext *LookupCtx = nullptr;
510 NamedDecl *Found = nullptr;
Richard Smithbf5bcf22018-06-26 23:20:26 +0000511 bool MissingTemplateKeyword = false;
Richard Smith42bc73a2017-05-10 02:30:28 +0000512
513 // Figure out what name we looked up.
Richard Smithbf5bcf22018-06-26 23:20:26 +0000514 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
515 NameInfo = DRE->getNameInfo();
516 SS.Adopt(DRE->getQualifierLoc());
517 LookupKind = LookupOrdinaryName;
518 Found = DRE->getFoundDecl();
519 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
Richard Smith42bc73a2017-05-10 02:30:28 +0000520 NameInfo = ME->getMemberNameInfo();
521 SS.Adopt(ME->getQualifierLoc());
522 LookupKind = LookupMemberName;
523 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
524 Found = ME->getMemberDecl();
Richard Smithbf5bcf22018-06-26 23:20:26 +0000525 } else if (auto *DSDRE =
526 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
527 NameInfo = DSDRE->getNameInfo();
528 SS.Adopt(DSDRE->getQualifierLoc());
529 MissingTemplateKeyword = true;
530 } else if (auto *DSME =
531 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
532 NameInfo = DSME->getMemberNameInfo();
533 SS.Adopt(DSME->getQualifierLoc());
534 MissingTemplateKeyword = true;
Richard Smith42bc73a2017-05-10 02:30:28 +0000535 } else {
Richard Smithbf5bcf22018-06-26 23:20:26 +0000536 llvm_unreachable("unexpected kind of potential template name");
537 }
538
539 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
540 // was missing.
541 if (MissingTemplateKeyword) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000542 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
543 << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
Richard Smithbf5bcf22018-06-26 23:20:26 +0000544 return;
Richard Smith42bc73a2017-05-10 02:30:28 +0000545 }
546
547 // Try to correct the name by looking for templates and C++ named casts.
548 struct TemplateCandidateFilter : CorrectionCandidateCallback {
549 TemplateCandidateFilter() {
550 WantTypeSpecifiers = false;
551 WantExpressionKeywords = false;
552 WantRemainingKeywords = false;
553 WantCXXNamedCasts = true;
554 };
555 bool ValidateCandidate(const TypoCorrection &Candidate) override {
556 if (auto *ND = Candidate.getCorrectionDecl())
557 return isAcceptableTemplateName(ND->getASTContext(), ND, true);
558 return Candidate.isKeyword();
559 }
560 };
561
562 DeclarationName Name = NameInfo.getName();
563 if (TypoCorrection Corrected =
564 CorrectTypo(NameInfo, LookupKind, S, &SS,
565 llvm::make_unique<TemplateCandidateFilter>(),
566 CTK_ErrorRecovery, LookupCtx)) {
567 auto *ND = Corrected.getFoundDecl();
568 if (ND)
569 ND = isAcceptableTemplateName(Context, ND,
570 /*AllowFunctionTemplates*/ true);
571 if (ND || Corrected.isKeyword()) {
572 if (LookupCtx) {
573 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
574 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
575 Name.getAsString() == CorrectedStr;
576 diagnoseTypo(Corrected,
577 PDiag(diag::err_non_template_in_member_template_id_suggest)
578 << Name << LookupCtx << DroppedSpecifier
Richard Smith52f8d192017-05-10 21:32:16 +0000579 << SS.getRange(), false);
Richard Smith42bc73a2017-05-10 02:30:28 +0000580 } else {
581 diagnoseTypo(Corrected,
582 PDiag(diag::err_non_template_in_template_id_suggest)
Richard Smith52f8d192017-05-10 21:32:16 +0000583 << Name, false);
Richard Smith42bc73a2017-05-10 02:30:28 +0000584 }
585 if (Found)
586 Diag(Found->getLocation(),
587 diag::note_non_template_in_template_id_found);
588 return;
589 }
590 }
591
592 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
593 << Name << SourceRange(Less, Greater);
594 if (Found)
595 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
596}
597
John McCallcd4b4772009-12-02 03:53:29 +0000598/// ActOnDependentIdExpression - Handle a dependent id-expression that
599/// was just parsed. This is only possible with an explicit scope
600/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000601ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000602Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000603 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000604 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000605 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000606 const TemplateArgumentListInfo *TemplateArgs) {
John McCall87fe5d52010-05-20 01:18:31 +0000607 DeclContext *DC = getFunctionLevelDeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000608
Reid Kleckner1af391df2016-03-11 18:59:12 +0000609 // C++11 [expr.prim.general]p12:
610 // An id-expression that denotes a non-static data member or non-static
611 // member function of a class can only be used:
612 // (...)
613 // - if that id-expression denotes a non-static data member and it
614 // appears in an unevaluated operand.
615 //
616 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
617 // CXXDependentScopeMemberExpr. The former can instantiate to either
618 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
619 // always a MemberExpr.
620 bool MightBeCxx11UnevalField =
621 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
622
Akira Hatanakad644e022016-12-16 03:19:41 +0000623 // Check if the nested name specifier is an enum type.
624 bool IsEnum = false;
625 if (NestedNameSpecifier *NNS = SS.getScopeRep())
626 IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
627
628 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
Reid Kleckner1af391df2016-03-11 18:59:12 +0000629 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
Brian Gesiak5488ab42019-01-11 01:54:53 +0000630 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000631
John McCalle66edc12009-11-24 19:00:30 +0000632 // Since the 'this' expression is synthesized, we don't need to
633 // perform the double-lookup check.
Craig Topperc3ec1492014-05-26 06:22:03 +0000634 NamedDecl *FirstQualifierInScope = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000635
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000636 return CXXDependentScopeMemberExpr::Create(
637 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
638 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
639 FirstQualifierInScope, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000640 }
641
Abramo Bagnara7945c982012-01-27 09:46:47 +0000642 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000643}
644
John McCalldadc5752010-08-24 06:29:42 +0000645ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000646Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000647 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000648 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000649 const TemplateArgumentListInfo *TemplateArgs) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000650 return DependentScopeDeclRefExpr::Create(
651 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
652 TemplateArgs);
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000653}
654
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000655
656/// Determine whether we would be unable to instantiate this template (because
657/// it either has no definition, or is in the process of being instantiated).
658bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
659 NamedDecl *Instantiation,
660 bool InstantiatedFromMember,
661 const NamedDecl *Pattern,
662 const NamedDecl *PatternDef,
663 TemplateSpecializationKind TSK,
664 bool Complain /*= true*/) {
Richard Smithedbc6e92016-10-14 21:41:24 +0000665 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
666 isa<VarDecl>(Instantiation));
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000667
Richard Smithedbc6e92016-10-14 21:41:24 +0000668 bool IsEntityBeingDefined = false;
669 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
670 IsEntityBeingDefined = TD->isBeingDefined();
671
672 if (PatternDef && !IsEntityBeingDefined) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000673 NamedDecl *SuggestedDef = nullptr;
674 if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
675 /*OnlyNeedComplete*/false)) {
676 // If we're allowed to diagnose this and recover, do so.
677 bool Recover = Complain && !isSFINAEContext();
678 if (Complain)
679 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
680 Sema::MissingImportKind::Definition, Recover);
681 return !Recover;
682 }
683 return false;
684 }
685
Richard Smith6f4e2e02016-08-23 19:41:39 +0000686 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
687 return true;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000688
Richard Smithedbc6e92016-10-14 21:41:24 +0000689 llvm::Optional<unsigned> Note;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000690 QualType InstantiationTy;
691 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
692 InstantiationTy = Context.getTypeDeclType(TD);
Richard Smith6f4e2e02016-08-23 19:41:39 +0000693 if (PatternDef) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000694 Diag(PointOfInstantiation,
695 diag::err_template_instantiate_within_definition)
Richard Smithedbc6e92016-10-14 21:41:24 +0000696 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000697 << InstantiationTy;
698 // Not much point in noting the template declaration here, since
699 // we're lexically inside it.
700 Instantiation->setInvalidDecl();
701 } else if (InstantiatedFromMember) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000702 if (isa<FunctionDecl>(Instantiation)) {
703 Diag(PointOfInstantiation,
704 diag::err_explicit_instantiation_undefined_member)
Richard Smithedbc6e92016-10-14 21:41:24 +0000705 << /*member function*/ 1 << Instantiation->getDeclName()
706 << Instantiation->getDeclContext();
707 Note = diag::note_explicit_instantiation_here;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000708 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000709 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
Richard Smith6f4e2e02016-08-23 19:41:39 +0000710 Diag(PointOfInstantiation,
711 diag::err_implicit_instantiate_member_undefined)
712 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000713 Note = diag::note_member_declared_at;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000714 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000715 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000716 if (isa<FunctionDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000717 Diag(PointOfInstantiation,
718 diag::err_explicit_instantiation_undefined_func_template)
719 << Pattern;
Richard Smithedbc6e92016-10-14 21:41:24 +0000720 Note = diag::note_explicit_instantiation_here;
721 } else if (isa<TagDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000722 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
723 << (TSK != TSK_ImplicitInstantiation)
724 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000725 Note = diag::note_template_decl_here;
726 } else {
727 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
728 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
729 Diag(PointOfInstantiation,
730 diag::err_explicit_instantiation_undefined_var_template)
731 << Instantiation;
732 Instantiation->setInvalidDecl();
733 } else
734 Diag(PointOfInstantiation,
735 diag::err_explicit_instantiation_undefined_member)
736 << /*static data member*/ 2 << Instantiation->getDeclName()
737 << Instantiation->getDeclContext();
738 Note = diag::note_explicit_instantiation_here;
739 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000740 }
Richard Smithedbc6e92016-10-14 21:41:24 +0000741 if (Note) // Diagnostics were emitted.
742 Diag(Pattern->getLocation(), Note.getValue());
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000743
744 // In general, Instantiation isn't marked invalid to get more than one
745 // error for multiple undefined instantiations. But the code that does
746 // explicit declaration -> explicit definition conversion can't handle
747 // invalid declarations, so mark as invalid in that case.
748 if (TSK == TSK_ExplicitInstantiationDeclaration)
749 Instantiation->setInvalidDecl();
750 return true;
751}
752
Douglas Gregor5101c242008-12-05 18:15:24 +0000753/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
754/// that the template parameter 'PrevDecl' is being shadowed by a new
755/// declaration at location Loc. Returns true to indicate that this is
756/// an error, and false otherwise.
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000757void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000758 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000759
760 // Microsoft Visual C++ permits template parameters to be shadowed.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000761 if (getLangOpts().MicrosoftExt)
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000762 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000763
764 // C++ [temp.local]p4:
765 // A template-parameter shall not be redeclared within its
766 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000767 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000768 << cast<NamedDecl>(PrevDecl)->getDeclName();
769 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregor5101c242008-12-05 18:15:24 +0000770}
771
Douglas Gregor463421d2009-03-03 04:44:36 +0000772/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000773/// the parameter D to reference the templated declaration and return a pointer
774/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000775TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
776 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
777 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000778 return Temp;
779 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000780 return nullptr;
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000781}
782
Douglas Gregoreb29d182011-01-05 17:40:24 +0000783ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
784 SourceLocation EllipsisLoc) const {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000785 assert(Kind == Template &&
Douglas Gregoreb29d182011-01-05 17:40:24 +0000786 "Only template template arguments can be pack expansions here");
787 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
788 "Template template argument pack expansion without packs");
789 ParsedTemplateArgument Result(*this);
790 Result.EllipsisLoc = EllipsisLoc;
791 return Result;
792}
793
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000794static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
795 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000796
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000797 switch (Arg.getKind()) {
798 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000799 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000800 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000801 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000802 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000803 return TemplateArgumentLoc(TemplateArgument(T), DI);
804 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000805
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000806 case ParsedTemplateArgument::NonType: {
807 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
808 return TemplateArgumentLoc(TemplateArgument(E), E);
809 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000810
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000811 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000812 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregore1d60df2011-01-14 23:41:42 +0000813 TemplateArgument TArg;
814 if (Arg.getEllipsisLoc().isValid())
David Blaikie05785d12013-02-20 22:23:23 +0000815 TArg = TemplateArgument(Template, Optional<unsigned int>());
Douglas Gregore1d60df2011-01-14 23:41:42 +0000816 else
817 TArg = Template;
818 return TemplateArgumentLoc(TArg,
Douglas Gregor9d802122011-03-02 17:09:35 +0000819 Arg.getScopeSpec().getWithLocInContext(
820 SemaRef.Context),
Douglas Gregoreb29d182011-01-05 17:40:24 +0000821 Arg.getLocation(),
822 Arg.getEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000823 }
824 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000825
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000826 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000827}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000828
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000829/// Translates template arguments as provided by the parser
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000830/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000831void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
832 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000833 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000834 TemplateArgs.addArgument(translateTemplateArgument(*this,
835 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000836}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000837
Richard Smithb80d5402013-06-25 22:21:36 +0000838static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
839 SourceLocation Loc,
840 IdentifierInfo *Name) {
841 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
Richard Smithbecb92d2017-10-10 22:33:17 +0000842 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
Richard Smithb80d5402013-06-25 22:21:36 +0000843 if (PrevDecl && PrevDecl->isTemplateParameter())
844 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
845}
846
Richard Smith77a9c602018-02-28 03:02:23 +0000847/// Convert a parsed type into a parsed template argument. This is mostly
848/// trivial, except that we may have parsed a C++17 deduced class template
849/// specialization type, in which case we should form a template template
850/// argument instead of a type template argument.
851ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
852 TypeSourceInfo *TInfo;
853 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
854 if (T.isNull())
855 return ParsedTemplateArgument();
856 assert(TInfo && "template argument with no location");
857
858 // If we might have formed a deduced template specialization type, convert
859 // it to a template template argument.
860 if (getLangOpts().CPlusPlus17) {
861 TypeLoc TL = TInfo->getTypeLoc();
862 SourceLocation EllipsisLoc;
863 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
864 EllipsisLoc = PET.getEllipsisLoc();
865 TL = PET.getPatternLoc();
866 }
867
868 CXXScopeSpec SS;
869 if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
870 SS.Adopt(ET.getQualifierLoc());
871 TL = ET.getNamedTypeLoc();
872 }
873
874 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
875 TemplateName Name = DTST.getTypePtr()->getTemplateName();
876 if (SS.isSet())
877 Name = Context.getQualifiedTemplateName(SS.getScopeRep(),
878 /*HasTemplateKeyword*/ false,
879 Name.getAsTemplateDecl());
880 ParsedTemplateArgument Result(SS, TemplateTy::make(Name),
881 DTST.getTemplateNameLoc());
882 if (EllipsisLoc.isValid())
883 Result = Result.getTemplatePackExpansion(EllipsisLoc);
884 return Result;
885 }
886 }
887
888 // This is a normal type template argument. Note, if the type template
889 // argument is an injected-class-name for a template, it has a dual nature
Fangrui Song6907ce22018-07-30 19:24:48 +0000890 // and can be used as either a type or a template. We handle that in
Richard Smith77a9c602018-02-28 03:02:23 +0000891 // convertTypeTemplateArgumentToTemplate.
892 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
893 ParsedType.get().getAsOpaquePtr(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000894 TInfo->getTypeLoc().getBeginLoc());
Richard Smith77a9c602018-02-28 03:02:23 +0000895}
896
Douglas Gregor5101c242008-12-05 18:15:24 +0000897/// ActOnTypeParameter - Called when a C++ template type parameter
898/// (e.g., "typename T") has been parsed. Typename specifies whether
899/// the keyword "typename" was used to declare the type parameter
900/// (otherwise, "class" was used), and KeyLoc is the location of the
901/// "class" or "typename" keyword. ParamName is the name of the
902/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth08836322011-05-01 00:51:33 +0000903/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000904/// If the type parameter has a default argument, it will be added
905/// later via ActOnTypeParameterDefault.
Faisal Valibe294032017-12-23 18:56:34 +0000906NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
John McCall48871652010-08-21 09:40:31 +0000907 SourceLocation EllipsisLoc,
908 SourceLocation KeyLoc,
909 IdentifierInfo *ParamName,
910 SourceLocation ParamNameLoc,
911 unsigned Depth, unsigned Position,
912 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000913 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000914 assert(S->isTemplateParamScope() &&
915 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000916
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000917 SourceLocation Loc = ParamNameLoc;
918 if (!ParamName)
919 Loc = KeyLoc;
920
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000921 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregor5101c242008-12-05 18:15:24 +0000922 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000923 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000924 KeyLoc, Loc, Depth, Position, ParamName,
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000925 Typename, IsParameterPack);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000926 Param->setAccess(AS_public);
Douglas Gregor5101c242008-12-05 18:15:24 +0000927
928 if (ParamName) {
Richard Smithb80d5402013-06-25 22:21:36 +0000929 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
930
Douglas Gregor5101c242008-12-05 18:15:24 +0000931 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000932 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000933 IdResolver.AddDecl(Param);
934 }
935
Douglas Gregorf5500772011-01-05 15:48:55 +0000936 // C++0x [temp.param]p9:
937 // A default template-argument may be specified for any kind of
938 // template-parameter that is not a template parameter pack.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000939 if (DefaultArg && IsParameterPack) {
Douglas Gregorf5500772011-01-05 15:48:55 +0000940 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
David Blaikieefdccaa2016-01-15 23:43:34 +0000941 DefaultArg = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000942 }
943
Douglas Gregordc13ded2010-07-01 00:00:45 +0000944 // Handle the default argument, if provided.
945 if (DefaultArg) {
946 TypeSourceInfo *DefaultTInfo;
947 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000948
Douglas Gregordc13ded2010-07-01 00:00:45 +0000949 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000950
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000951 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000952 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000953 UPPC_DefaultArgument))
954 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000955
Douglas Gregordc13ded2010-07-01 00:00:45 +0000956 // Check the template argument itself.
957 if (CheckTemplateArgument(Param, DefaultTInfo)) {
958 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000959 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000960 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000961
Richard Smith1469b912015-06-10 00:29:03 +0000962 Param->setDefaultArgument(DefaultTInfo);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000963 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000964
John McCall48871652010-08-21 09:40:31 +0000965 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000966}
967
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000968/// Check that the type of a non-type template parameter is
Douglas Gregor463421d2009-03-03 04:44:36 +0000969/// well-formed.
970///
971/// \returns the (possibly-promoted) parameter type if valid;
972/// otherwise, produces a diagnostic and returns a NULL type.
Richard Smith15361a22016-12-28 06:27:18 +0000973QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
974 SourceLocation Loc) {
975 if (TSI->getType()->isUndeducedType()) {
Erik Pilkington9f9462a2018-08-07 22:59:02 +0000976 // C++17 [temp.dep.expr]p3:
Richard Smith15361a22016-12-28 06:27:18 +0000977 // An id-expression is type-dependent if it contains
978 // - an identifier associated by name lookup with a non-type
979 // template-parameter declared with a type that contains a
980 // placeholder type (7.1.7.4),
981 TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
982 }
983
984 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
985}
986
987QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
988 SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000989 // We don't allow variably-modified types as the type of non-type template
990 // parameters.
991 if (T->isVariablyModifiedType()) {
992 Diag(Loc, diag::err_variably_modified_nontype_template_param)
993 << T;
994 return QualType();
995 }
996
Douglas Gregor463421d2009-03-03 04:44:36 +0000997 // C++ [temp.param]p4:
998 //
999 // A non-type template-parameter shall have one of the following
1000 // (optionally cv-qualified) types:
1001 //
1002 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +00001003 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +00001004 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +00001005 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +00001006 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +00001007 T->isReferenceType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +00001008 // -- pointer to member,
Douglas Gregor463421d2009-03-03 04:44:36 +00001009 T->isMemberPointerType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +00001010 // -- std::nullptr_t.
1011 T->isNullPtrType() ||
Douglas Gregor463421d2009-03-03 04:44:36 +00001012 // If T is a dependent type, we can't do the check now, so we
1013 // assume that it is well-formed.
Richard Smith5f274382016-09-28 23:55:27 +00001014 T->isDependentType() ||
1015 // Allow use of auto in template parameter declarations.
1016 T->isUndeducedType()) {
Richard Smithd0e1c952012-03-13 07:21:50 +00001017 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1018 // are ignored when determining its type.
1019 return T.getUnqualifiedType();
1020 }
1021
Douglas Gregor463421d2009-03-03 04:44:36 +00001022 // C++ [temp.param]p8:
1023 //
1024 // A non-type template-parameter of type "array of T" or
1025 // "function returning T" is adjusted to be of type "pointer to
1026 // T" or "pointer to function returning T", respectively.
Richard Smithd663fdd2014-12-17 20:42:37 +00001027 else if (T->isArrayType() || T->isFunctionType())
1028 return Context.getDecayedType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001029
Douglas Gregor463421d2009-03-03 04:44:36 +00001030 Diag(Loc, diag::err_template_nontype_parm_bad_type)
1031 << T;
1032
1033 return QualType();
1034}
1035
Faisal Valibe294032017-12-23 18:56:34 +00001036NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
John McCall48871652010-08-21 09:40:31 +00001037 unsigned Depth,
1038 unsigned Position,
1039 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +00001040 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +00001041 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Richard Smith15361a22016-12-28 06:27:18 +00001042
Faisal Valia223d1c2017-12-22 03:50:55 +00001043 // Check that we have valid decl-specifiers specified.
1044 auto CheckValidDeclSpecifiers = [this, &D] {
1045 // C++ [temp.param]
Fangrui Song6907ce22018-07-30 19:24:48 +00001046 // p1
Malcolm Parsonsfab36802018-04-16 08:31:08 +00001047 // template-parameter:
1048 // ...
1049 // parameter-declaration
Fangrui Song6907ce22018-07-30 19:24:48 +00001050 // p2
Faisal Valia223d1c2017-12-22 03:50:55 +00001051 // ... A storage class shall not be specified in a template-parameter
1052 // declaration.
Fangrui Song6907ce22018-07-30 19:24:48 +00001053 // [dcl.typedef]p1:
Faisal Valia223d1c2017-12-22 03:50:55 +00001054 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1055 // of a parameter-declaration
1056 const DeclSpec &DS = D.getDeclSpec();
1057 auto EmitDiag = [this](SourceLocation Loc) {
1058 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1059 << FixItHint::CreateRemoval(Loc);
1060 };
1061 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1062 EmitDiag(DS.getStorageClassSpecLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00001063
Sam McCall1371cba2017-12-22 07:09:51 +00001064 if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
Faisal Valia223d1c2017-12-22 03:50:55 +00001065 EmitDiag(DS.getThreadStorageClassSpecLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00001066
1067 // [dcl.inline]p1:
1068 // The inline specifier can be applied only to the declaration or
Faisal Valia223d1c2017-12-22 03:50:55 +00001069 // definition of a variable or function.
Fangrui Song6907ce22018-07-30 19:24:48 +00001070
Faisal Valia223d1c2017-12-22 03:50:55 +00001071 if (DS.isInlineSpecified())
1072 EmitDiag(DS.getInlineSpecLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00001073
Faisal Valia223d1c2017-12-22 03:50:55 +00001074 // [dcl.constexpr]p1:
Fangrui Song6907ce22018-07-30 19:24:48 +00001075 // The constexpr specifier shall be applied only to the definition of a
1076 // variable or variable template or the declaration of a function or
Faisal Valia223d1c2017-12-22 03:50:55 +00001077 // function template.
Fangrui Song6907ce22018-07-30 19:24:48 +00001078
Faisal Valia223d1c2017-12-22 03:50:55 +00001079 if (DS.isConstexprSpecified())
1080 EmitDiag(DS.getConstexprSpecLoc());
1081
1082 // [dcl.fct.spec]p1:
1083 // Function-specifiers can be used only in function declarations.
1084
1085 if (DS.isVirtualSpecified())
1086 EmitDiag(DS.getVirtualSpecLoc());
1087
1088 if (DS.isExplicitSpecified())
1089 EmitDiag(DS.getExplicitSpecLoc());
1090
1091 if (DS.isNoreturnSpecified())
1092 EmitDiag(DS.getNoreturnSpecLoc());
1093 };
1094
1095 CheckValidDeclSpecifiers();
Fangrui Song6907ce22018-07-30 19:24:48 +00001096
Richard Smith15361a22016-12-28 06:27:18 +00001097 if (TInfo->getType()->isUndeducedType()) {
1098 Diag(D.getIdentifierLoc(),
1099 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1100 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1101 }
Douglas Gregor5101c242008-12-05 18:15:24 +00001102
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001103 assert(S->isTemplateParamScope() &&
1104 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +00001105 bool Invalid = false;
1106
Richard Smith15361a22016-12-28 06:27:18 +00001107 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001108 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001109 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +00001110 Invalid = true;
1111 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001112
Richard Smithb80d5402013-06-25 22:21:36 +00001113 IdentifierInfo *ParamName = D.getIdentifier();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +00001114 bool IsParameterPack = D.hasEllipsis();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001115 NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
1116 Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1117 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1118 TInfo);
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001119 Param->setAccess(AS_public);
Richard Smithb80d5402013-06-25 22:21:36 +00001120
Douglas Gregor5101c242008-12-05 18:15:24 +00001121 if (Invalid)
1122 Param->setInvalidDecl();
1123
Richard Smithb80d5402013-06-25 22:21:36 +00001124 if (ParamName) {
1125 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1126 ParamName);
1127
Douglas Gregor5101c242008-12-05 18:15:24 +00001128 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +00001129 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +00001130 IdResolver.AddDecl(Param);
1131 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001132
Douglas Gregorf5500772011-01-05 15:48:55 +00001133 // C++0x [temp.param]p9:
1134 // A default template-argument may be specified for any kind of
1135 // template-parameter that is not a template parameter pack.
1136 if (Default && IsParameterPack) {
1137 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
Craig Topperc3ec1492014-05-26 06:22:03 +00001138 Default = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +00001139 }
1140
Douglas Gregordc13ded2010-07-01 00:00:45 +00001141 // Check the well-formedness of the default template argument, if provided.
Douglas Gregorda3cc0d2010-12-23 23:51:58 +00001142 if (Default) {
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001143 // Check for unexpanded parameter packs.
1144 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
1145 return Param;
1146
Douglas Gregordc13ded2010-07-01 00:00:45 +00001147 TemplateArgument Converted;
Richard Smithd663fdd2014-12-17 20:42:37 +00001148 ExprResult DefaultRes =
1149 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
John Wiegley01296292011-04-08 18:41:53 +00001150 if (DefaultRes.isInvalid()) {
Douglas Gregordc13ded2010-07-01 00:00:45 +00001151 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +00001152 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +00001153 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001154 Default = DefaultRes.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001155
Richard Smith1469b912015-06-10 00:29:03 +00001156 Param->setDefaultArgument(Default);
Douglas Gregordc13ded2010-07-01 00:00:45 +00001157 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001158
John McCall48871652010-08-21 09:40:31 +00001159 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +00001160}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001161
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001162/// ActOnTemplateTemplateParameter - Called when a C++ template template
James Dennett2a4d13c2012-06-15 07:13:21 +00001163/// parameter (e.g. T in template <template \<typename> class T> class array)
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001164/// has been parsed. S is the current scope.
Faisal Valibe294032017-12-23 18:56:34 +00001165NamedDecl *Sema::ActOnTemplateTemplateParameter(Scope* S,
John McCall48871652010-08-21 09:40:31 +00001166 SourceLocation TmpLoc,
Richard Trieu9becef62011-09-09 03:18:59 +00001167 TemplateParameterList *Params,
Douglas Gregorf5500772011-01-05 15:48:55 +00001168 SourceLocation EllipsisLoc,
John McCall48871652010-08-21 09:40:31 +00001169 IdentifierInfo *Name,
1170 SourceLocation NameLoc,
1171 unsigned Depth,
1172 unsigned Position,
1173 SourceLocation EqualLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +00001174 ParsedTemplateArgument Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001175 assert(S->isTemplateParamScope() &&
1176 "Template template parameter not in template parameter scope!");
1177
1178 // Construct the parameter object.
Douglas Gregorf5500772011-01-05 15:48:55 +00001179 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001180 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +00001181 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001182 NameLoc.isInvalid()? TmpLoc : NameLoc,
1183 Depth, Position, IsParameterPack,
Douglas Gregorf5500772011-01-05 15:48:55 +00001184 Name, Params);
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001185 Param->setAccess(AS_public);
Simon Pilgrim6905d222016-12-30 22:55:33 +00001186
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001187 // If the template template parameter has a name, then link the identifier
Douglas Gregordc13ded2010-07-01 00:00:45 +00001188 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001189 if (Name) {
Richard Smithb80d5402013-06-25 22:21:36 +00001190 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1191
John McCall48871652010-08-21 09:40:31 +00001192 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001193 IdResolver.AddDecl(Param);
1194 }
1195
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001196 if (Params->size() == 0) {
1197 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1198 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1199 Param->setInvalidDecl();
1200 }
1201
Douglas Gregorf5500772011-01-05 15:48:55 +00001202 // C++0x [temp.param]p9:
1203 // A default template-argument may be specified for any kind of
1204 // template-parameter that is not a template parameter pack.
1205 if (IsParameterPack && !Default.isInvalid()) {
1206 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1207 Default = ParsedTemplateArgument();
1208 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001209
Douglas Gregordc13ded2010-07-01 00:00:45 +00001210 if (!Default.isInvalid()) {
1211 // Check only that we have a template template argument. We don't want to
1212 // try to check well-formedness now, because our template template parameter
1213 // might have dependent types in its template parameters, which we wouldn't
1214 // be able to match now.
1215 //
1216 // If none of the template template parameter's template arguments mention
1217 // other template parameters, we could actually perform more checking here.
1218 // However, it isn't worth doing.
1219 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1220 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
Faisal Valib8b04f82016-03-26 20:46:45 +00001221 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
Douglas Gregordc13ded2010-07-01 00:00:45 +00001222 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00001223 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +00001224 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001225
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001226 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001227 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001228 DefaultArg.getArgument().getAsTemplate(),
1229 UPPC_DefaultArgument))
1230 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001231
Richard Smith1469b912015-06-10 00:29:03 +00001232 Param->setDefaultArgument(Context, DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +00001233 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001234
John McCall48871652010-08-21 09:40:31 +00001235 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +00001236}
1237
Hubert Tongf608c052016-04-29 18:05:37 +00001238/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1239/// constrained by RequiresClause, that contains the template parameters in
1240/// Params.
Richard Trieu9becef62011-09-09 03:18:59 +00001241TemplateParameterList *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001242Sema::ActOnTemplateParameterList(unsigned Depth,
1243 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001244 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001245 SourceLocation LAngleLoc,
Faisal Valif241b0d2017-08-25 18:24:20 +00001246 ArrayRef<NamedDecl *> Params,
Hubert Tongf608c052016-04-29 18:05:37 +00001247 SourceLocation RAngleLoc,
1248 Expr *RequiresClause) {
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001249 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001250 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001251
David Majnemer902f8c62015-12-27 07:16:27 +00001252 return TemplateParameterList::Create(
1253 Context, TemplateLoc, LAngleLoc,
Faisal Valif241b0d2017-08-25 18:24:20 +00001254 llvm::makeArrayRef(Params.data(), Params.size()),
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00001255 RAngleLoc, RequiresClause);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001256}
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001257
Bruno Ricci4224c872018-12-21 14:35:24 +00001258static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
1259 const CXXScopeSpec &SS) {
John McCall3e11ebe2010-03-15 10:12:16 +00001260 if (SS.isSet())
Bruno Ricci4224c872018-12-21 14:35:24 +00001261 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
John McCall3e11ebe2010-03-15 10:12:16 +00001262}
1263
Erich Keanec480f302018-07-12 21:09:05 +00001264DeclResult Sema::CheckClassTemplate(
1265 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1266 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1267 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1268 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1269 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1270 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
Mike Stump11289f42009-09-09 15:08:12 +00001271 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001272 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +00001273 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +00001274 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001275
1276 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001277 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001278 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001279
Abramo Bagnara6150c882010-05-11 21:36:43 +00001280 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1281 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001282
1283 // There is no such thing as an unnamed class template.
1284 if (!Name) {
1285 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001286 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001287 }
1288
Richard Smith6483d222012-04-21 01:27:54 +00001289 // Find any previous declaration with this name. For a friend with no
1290 // scope explicitly specified, we only look for tag declarations (per
1291 // C++11 [basic.lookup.elab]p2).
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001292 DeclContext *SemanticContext;
Richard Smith6483d222012-04-21 01:27:54 +00001293 LookupResult Previous(*this, Name, NameLoc,
1294 (SS.isEmpty() && TUK == TUK_Friend)
1295 ? LookupTagName : LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00001296 forRedeclarationInCurContext());
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001297 if (SS.isNotEmpty() && !SS.isInvalid()) {
1298 SemanticContext = computeDeclContext(SS, true);
1299 if (!SemanticContext) {
Douglas Gregor67daacb2012-03-30 16:20:47 +00001300 // FIXME: Horrible, horrible hack! We can't currently represent this
1301 // in the AST, and historically we have just ignored such friend
1302 // class templates, so don't complain here.
Richard Smithcd556eb2013-11-08 18:59:56 +00001303 Diag(NameLoc, TUK == TUK_Friend
1304 ? diag::warn_template_qualified_friend_ignored
1305 : diag::err_template_qualified_declarator_no_match)
Douglas Gregor67daacb2012-03-30 16:20:47 +00001306 << SS.getScopeRep() << SS.getRange();
Richard Smithcd556eb2013-11-08 18:59:56 +00001307 return TUK != TUK_Friend;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001308 }
Mike Stump11289f42009-09-09 15:08:12 +00001309
John McCall0b66eb32010-05-01 00:40:08 +00001310 if (RequireCompleteDeclContext(SS, SemanticContext))
1311 return true;
1312
Simon Pilgrim6905d222016-12-30 22:55:33 +00001313 // If we're adding a template to a dependent context, we may need to
1314 // rebuilding some of the types used within the template parameter list,
Douglas Gregor041b0842011-10-14 15:31:12 +00001315 // now that we know what the current instantiation is.
1316 if (SemanticContext->isDependentContext()) {
1317 ContextRAII SavedContext(*this, SemanticContext);
1318 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1319 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00001320 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
Richard Smithc660c8f2018-03-16 13:36:56 +00001321 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc, false);
Richard Smith6483d222012-04-21 01:27:54 +00001322
John McCall27b18f82009-11-17 02:14:36 +00001323 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001324 } else {
1325 SemanticContext = CurContext;
Richard Smith88fe69c2015-07-06 01:45:27 +00001326
1327 // C++14 [class.mem]p14:
1328 // If T is the name of a class, then each of the following shall have a
1329 // name different from T:
1330 // -- every member template of class T
1331 if (TUK != TUK_Friend &&
1332 DiagnoseClassNameShadow(SemanticContext,
1333 DeclarationNameInfo(Name, NameLoc)))
1334 return true;
1335
John McCall27b18f82009-11-17 02:14:36 +00001336 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001337 }
Mike Stump11289f42009-09-09 15:08:12 +00001338
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001339 if (Previous.isAmbiguous())
1340 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001341
Craig Topperc3ec1492014-05-26 06:22:03 +00001342 NamedDecl *PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001343 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001344 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001345
Serge Pavlove50bf752016-06-10 04:39:07 +00001346 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1347 // Maybe we will complain about the shadowed template parameter.
1348 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1349 // Just pretend that we didn't see the previous declaration.
1350 PrevDecl = nullptr;
1351 }
1352
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001353 // If there is a previous declaration with the same name, check
1354 // whether this is a valid redeclaration.
Richard Smithbecb92d2017-10-10 22:33:17 +00001355 ClassTemplateDecl *PrevClassTemplate =
1356 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001357
1358 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001359 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001360 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001361 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001362 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1363 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001364 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001365 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1366 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1367 PrevClassTemplate
1368 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1369 ->getSpecializedTemplate();
1370 }
1371 }
1372
John McCalld43784f2009-12-18 11:25:59 +00001373 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +00001374 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001375 // [...] When looking for a prior declaration of a class or a function
1376 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +00001377 // function is neither a qualified name nor a template-id, scopes outside
1378 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +00001379 if (!SS.isSet()) {
1380 DeclContext *OutermostContext = CurContext;
1381 while (!OutermostContext->isFileContext())
1382 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +00001383
Richard Smith61e582f2012-04-20 07:12:26 +00001384 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +00001385 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1386 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1387 SemanticContext = PrevDecl->getDeclContext();
1388 } else {
1389 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001390 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +00001391 // declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00001392 PrevDecl = PrevClassTemplate = nullptr;
Douglas Gregorb74b1032010-04-18 17:37:40 +00001393 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +00001394
1395 // Check that the chosen semantic context doesn't already contain a
1396 // declaration of this name as a non-tag type.
Richard Smithfc805ca2015-07-06 04:43:58 +00001397 Previous.clear(LookupOrdinaryName);
Richard Smith6483d222012-04-21 01:27:54 +00001398 DeclContext *LookupContext = SemanticContext;
1399 while (LookupContext->isTransparentContext())
1400 LookupContext = LookupContext->getLookupParent();
1401 LookupQualifiedName(Previous, LookupContext);
1402
1403 if (Previous.isAmbiguous())
1404 return true;
1405
1406 if (Previous.begin() != Previous.end())
1407 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +00001408 }
John McCall90d3bb92009-12-17 23:21:11 +00001409 }
Richard Smith72bcaec2013-12-05 04:30:04 +00001410 } else if (PrevDecl &&
Richard Smithfc805ca2015-07-06 04:43:58 +00001411 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1412 S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +00001413 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001414
Richard Smithfc805ca2015-07-06 04:43:58 +00001415 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1416 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1417 if (SS.isEmpty() &&
1418 !(PrevClassTemplate &&
1419 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1420 SemanticContext->getRedeclContext()))) {
1421 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1422 Diag(Shadow->getTargetDecl()->getLocation(),
1423 diag::note_using_decl_target);
1424 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1425 // Recover by ignoring the old declaration.
1426 PrevDecl = PrevClassTemplate = nullptr;
1427 }
1428 }
1429
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001430 // TODO Memory management; associated constraints are not always stored.
1431 Expr *const CurAC = formAssociatedConstraints(TemplateParams, nullptr);
1432
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001433 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +00001434 // Ensure that the template parameter lists are compatible. Skip this check
1435 // for a friend in a dependent context: the template parameter list itself
1436 // could be dependent.
1437 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1438 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001439 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001440 /*Complain=*/true,
1441 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001442 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001443
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001444 // Check for matching associated constraints on redeclarations.
1445 const Expr *const PrevAC = PrevClassTemplate->getAssociatedConstraints();
1446 const bool RedeclACMismatch = [&] {
1447 if (!(CurAC || PrevAC))
1448 return false; // Nothing to check; no mismatch.
1449 if (CurAC && PrevAC) {
1450 llvm::FoldingSetNodeID CurACInfo, PrevACInfo;
1451 CurAC->Profile(CurACInfo, Context, /*Canonical=*/true);
1452 PrevAC->Profile(PrevACInfo, Context, /*Canonical=*/true);
1453 if (CurACInfo == PrevACInfo)
1454 return false; // All good; no mismatch.
1455 }
1456 return true;
1457 }();
1458
1459 if (RedeclACMismatch) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001460 Diag(CurAC ? CurAC->getBeginLoc() : NameLoc,
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001461 diag::err_template_different_associated_constraints);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001462 Diag(PrevAC ? PrevAC->getBeginLoc() : PrevClassTemplate->getLocation(),
1463 diag::note_template_prev_declaration)
1464 << /*declaration*/ 0;
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001465 return true;
1466 }
1467
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001468 // C++ [temp.class]p4:
1469 // In a redeclaration, partial specialization, explicit
1470 // specialization or explicit instantiation of a class template,
1471 // the class-key shall agree in kind with the original class
1472 // template declaration (7.1.5.3).
1473 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +00001474 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001475 TUK == TUK_Definition, KWLoc, Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00001476 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00001477 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00001478 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001479 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00001480 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001481 }
1482
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001483 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +00001484 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001485 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001486 // If we have a prior definition that is not visible, treat this as
1487 // simply making that previous definition visible.
1488 NamedDecl *Hidden = nullptr;
1489 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
Richard Smithd9ba2242015-05-07 03:54:19 +00001490 SkipBody->ShouldSkip = true;
Richard Smithc4577662018-09-12 02:13:47 +00001491 SkipBody->Previous = Def;
Richard Smithbe3980b2015-03-27 00:41:57 +00001492 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1493 assert(Tmpl && "original definition of a class template is not a "
1494 "class template?");
Richard Smith858e0e02017-05-11 23:11:16 +00001495 makeMergedDefinitionVisible(Hidden);
1496 makeMergedDefinitionVisible(Tmpl);
Richard Smithc4577662018-09-12 02:13:47 +00001497 } else {
1498 Diag(NameLoc, diag::err_redefinition) << Name;
1499 Diag(Def->getLocation(), diag::note_previous_definition);
1500 // FIXME: Would it make sense to try to "forget" the previous
1501 // definition, as part of error recovery?
1502 return true;
Richard Smithbe3980b2015-03-27 00:41:57 +00001503 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001504 }
Serge Pavlove50bf752016-06-10 04:39:07 +00001505 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001506 } else if (PrevDecl) {
1507 // C++ [temp]p5:
1508 // A class template shall not have the same name as any other
1509 // template, class, function, object, enumeration, enumerator,
1510 // namespace, or type in the same scope (3.3), except as specified
1511 // in (14.5.4).
1512 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1513 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001514 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001515 }
1516
Douglas Gregordba32632009-02-10 19:49:53 +00001517 // Check the template parameter list of this declaration, possibly
1518 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001519 // template declaration. Skip this check for a friend in a dependent
1520 // context, because the template parameter list might be dependent.
1521 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001522 CheckTemplateParameterList(
1523 TemplateParams,
Richard Smithc4577662018-09-12 02:13:47 +00001524 PrevClassTemplate
1525 ? PrevClassTemplate->getMostRecentDecl()->getTemplateParameters()
1526 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001527 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1528 SemanticContext->isDependentContext())
1529 ? TPC_ClassTemplateMember
Richard Smithc4577662018-09-12 02:13:47 +00001530 : TUK == TUK_Friend ? TPC_FriendClassTemplate : TPC_ClassTemplate,
1531 SkipBody))
Douglas Gregordba32632009-02-10 19:49:53 +00001532 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001533
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001534 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001535 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001536 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001537 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1538 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001539 : diag::err_member_decl_does_not_match)
1540 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001541 Invalid = true;
1542 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001543 }
1544
Vassil Vassilev352e4412017-01-12 09:16:26 +00001545 // If this is a templated friend in a dependent context we should not put it
1546 // on the redecl chain. In some cases, the templated friend can be the most
1547 // recent declaration tricking the template instantiator to make substitutions
1548 // there.
1549 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1550 bool ShouldAddRedecl
1551 = !(TUK == TUK_Friend && CurContext->isDependentContext());
1552
Mike Stump11289f42009-09-09 15:08:12 +00001553 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001554 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Vassil Vassilev352e4412017-01-12 09:16:26 +00001555 PrevClassTemplate && ShouldAddRedecl ?
Craig Topperc3ec1492014-05-26 06:22:03 +00001556 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001557 /*DelayTypeCreation=*/true);
Bruno Ricci4224c872018-12-21 14:35:24 +00001558 SetNestedNameSpecifier(*this, NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001559 if (NumOuterTemplateParamLists > 0)
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001560 NewClass->setTemplateParameterListsInfo(
1561 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1562 NumOuterTemplateParamLists));
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001563
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001564 // Add alignment attributes if necessary; these attributes are checked when
1565 // the ASTContext lays out the structure.
Richard Smithc4577662018-09-12 02:13:47 +00001566 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
Eli Friedman0415f3e12012-08-08 21:08:34 +00001567 AddAlignmentAttributesForRecord(NewClass);
1568 AddMsStructLayoutForRecord(NewClass);
1569 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001570
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001571 // Attach the associated constraints when the declaration will not be part of
1572 // a decl chain.
1573 Expr *const ACtoAttach =
1574 PrevClassTemplate && ShouldAddRedecl ? nullptr : CurAC;
1575
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001576 ClassTemplateDecl *NewTemplate
1577 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1578 DeclarationName(Name), TemplateParams,
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001579 NewClass, ACtoAttach);
Vassil Vassilev352e4412017-01-12 09:16:26 +00001580
1581 if (ShouldAddRedecl)
1582 NewTemplate->setPreviousDecl(PrevClassTemplate);
1583
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001584 NewClass->setDescribedClassTemplate(NewTemplate);
Simon Pilgrim6905d222016-12-30 22:55:33 +00001585
Douglas Gregor21823bf2011-12-20 18:11:52 +00001586 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001587 NewTemplate->setModulePrivate();
Simon Pilgrim6905d222016-12-30 22:55:33 +00001588
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001589 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001590 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001591 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001592 assert(T->isDependentType() && "Class template type is not dependent?");
1593 (void)T;
1594
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001595 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001596 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001597 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001598 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1599 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001600
Anders Carlsson137108d2009-03-26 01:24:28 +00001601 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001602 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001603 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001604
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001605 // Set the lexical context of these templates
1606 NewClass->setLexicalDeclContext(CurContext);
1607 NewTemplate->setLexicalDeclContext(CurContext);
1608
Richard Smithc4577662018-09-12 02:13:47 +00001609 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001610 NewClass->startDefinition();
1611
Erich Keanec480f302018-07-12 21:09:05 +00001612 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001613
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001614 if (PrevClassTemplate)
1615 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1616
Rafael Espindola385c0422012-07-13 18:04:45 +00001617 AddPushedVisibilityAttribute(NewClass);
1618
Richard Smith234ff472014-08-23 00:49:01 +00001619 if (TUK != TUK_Friend) {
1620 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1621 Scope *Outer = S;
1622 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1623 Outer = Outer->getParent();
1624 PushOnScopeChains(NewTemplate, Outer);
1625 } else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001626 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001627 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001628 NewClass->setAccess(PrevClassTemplate->getAccess());
1629 }
John McCall27b5c252009-09-14 21:59:20 +00001630
Richard Smith64017682013-07-17 23:53:16 +00001631 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001632
John McCall27b5c252009-09-14 21:59:20 +00001633 // Friend templates are visible in fairly strange ways.
1634 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001635 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001636 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001637 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1638 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001639 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001640 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001641
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001642 FriendDecl *Friend = FriendDecl::Create(
1643 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
Douglas Gregor3dad8422009-09-26 06:47:28 +00001644 Friend->setAccess(AS_public);
1645 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001646 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001647
Richard Smithbecb92d2017-10-10 22:33:17 +00001648 if (PrevClassTemplate)
1649 CheckRedeclarationModuleOwnership(NewTemplate, PrevClassTemplate);
1650
Douglas Gregordba32632009-02-10 19:49:53 +00001651 if (Invalid) {
1652 NewTemplate->setInvalidDecl();
1653 NewClass->setInvalidDecl();
1654 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001655
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001656 ActOnDocumentableDecl(NewTemplate);
1657
Richard Smithc4577662018-09-12 02:13:47 +00001658 if (SkipBody && SkipBody->ShouldSkip)
1659 return SkipBody->Previous;
1660
John McCall48871652010-08-21 09:40:31 +00001661 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001662}
1663
Richard Smith32918772017-02-14 00:25:28 +00001664namespace {
Erik Pilkington69770d32018-07-27 21:23:48 +00001665/// Tree transform to "extract" a transformed type from a class template's
1666/// constructor to a deduction guide.
1667class ExtractTypeForDeductionGuide
1668 : public TreeTransform<ExtractTypeForDeductionGuide> {
1669public:
1670 typedef TreeTransform<ExtractTypeForDeductionGuide> Base;
1671 ExtractTypeForDeductionGuide(Sema &SemaRef) : Base(SemaRef) {}
1672
1673 TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); }
1674
1675 QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) {
1676 return TransformType(
1677 TLB,
1678 TL.getTypedefNameDecl()->getTypeSourceInfo()->getTypeLoc());
1679 }
1680};
1681
Richard Smith32918772017-02-14 00:25:28 +00001682/// Transform to convert portions of a constructor declaration into the
1683/// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
1684struct ConvertConstructorToDeductionGuideTransform {
1685 ConvertConstructorToDeductionGuideTransform(Sema &S,
1686 ClassTemplateDecl *Template)
1687 : SemaRef(S), Template(Template) {}
1688
1689 Sema &SemaRef;
1690 ClassTemplateDecl *Template;
1691
1692 DeclContext *DC = Template->getDeclContext();
1693 CXXRecordDecl *Primary = Template->getTemplatedDecl();
1694 DeclarationName DeductionGuideName =
1695 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
1696
1697 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
1698
1699 // Index adjustment to apply to convert depth-1 template parameters into
1700 // depth-0 template parameters.
1701 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
1702
1703 /// Transform a constructor declaration into a deduction guide.
Richard Smithbc491202017-02-17 20:05:37 +00001704 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
1705 CXXConstructorDecl *CD) {
Richard Smith32918772017-02-14 00:25:28 +00001706 SmallVector<TemplateArgument, 16> SubstArgs;
1707
Richard Smithb4f96252017-02-21 06:30:38 +00001708 LocalInstantiationScope Scope(SemaRef);
1709
Richard Smith32918772017-02-14 00:25:28 +00001710 // C++ [over.match.class.deduct]p1:
1711 // -- For each constructor of the class template designated by the
1712 // template-name, a function template with the following properties:
1713
1714 // -- The template parameters are the template parameters of the class
1715 // template followed by the template parameters (including default
1716 // template arguments) of the constructor, if any.
1717 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
1718 if (FTD) {
1719 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
1720 SmallVector<NamedDecl *, 16> AllParams;
1721 AllParams.reserve(TemplateParams->size() + InnerParams->size());
1722 AllParams.insert(AllParams.begin(),
1723 TemplateParams->begin(), TemplateParams->end());
1724 SubstArgs.reserve(InnerParams->size());
1725
1726 // Later template parameters could refer to earlier ones, so build up
1727 // a list of substituted template arguments as we go.
1728 for (NamedDecl *Param : *InnerParams) {
1729 MultiLevelTemplateArgumentList Args;
1730 Args.addOuterTemplateArguments(SubstArgs);
Richard Smithb4f96252017-02-21 06:30:38 +00001731 Args.addOuterRetainedLevel();
Richard Smith32918772017-02-14 00:25:28 +00001732 NamedDecl *NewParam = transformTemplateParameter(Param, Args);
1733 if (!NewParam)
1734 return nullptr;
1735 AllParams.push_back(NewParam);
1736 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
1737 SemaRef.Context.getInjectedTemplateArg(NewParam)));
1738 }
1739 TemplateParams = TemplateParameterList::Create(
1740 SemaRef.Context, InnerParams->getTemplateLoc(),
1741 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
1742 /*FIXME: RequiresClause*/ nullptr);
1743 }
1744
1745 // If we built a new template-parameter-list, track that we need to
1746 // substitute references to the old parameters into references to the
1747 // new ones.
1748 MultiLevelTemplateArgumentList Args;
1749 if (FTD) {
1750 Args.addOuterTemplateArguments(SubstArgs);
Richard Smithb4f96252017-02-21 06:30:38 +00001751 Args.addOuterRetainedLevel();
Richard Smith32918772017-02-14 00:25:28 +00001752 }
1753
Richard Smithbc491202017-02-17 20:05:37 +00001754 FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
Richard Smith32918772017-02-14 00:25:28 +00001755 .getAsAdjusted<FunctionProtoTypeLoc>();
1756 assert(FPTL && "no prototype for constructor declaration");
1757
1758 // Transform the type of the function, adjusting the return type and
1759 // replacing references to the old parameters with references to the
1760 // new ones.
1761 TypeLocBuilder TLB;
1762 SmallVector<ParmVarDecl*, 8> Params;
1763 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args);
1764 if (NewType.isNull())
1765 return nullptr;
1766 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
1767
Richard Smithbc491202017-02-17 20:05:37 +00001768 return buildDeductionGuide(TemplateParams, CD->isExplicit(), NewTInfo,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001769 CD->getBeginLoc(), CD->getLocation(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001770 CD->getEndLoc());
Richard Smith32918772017-02-14 00:25:28 +00001771 }
1772
1773 /// Build a deduction guide with the specified parameter types.
1774 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
1775 SourceLocation Loc = Template->getLocation();
1776
1777 // Build the requested type.
1778 FunctionProtoType::ExtProtoInfo EPI;
1779 EPI.HasTrailingReturn = true;
1780 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
1781 DeductionGuideName, EPI);
1782 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
1783
1784 FunctionProtoTypeLoc FPTL =
1785 TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
1786
1787 // Build the parameters, needed during deduction / substitution.
1788 SmallVector<ParmVarDecl*, 4> Params;
1789 for (auto T : ParamTypes) {
1790 ParmVarDecl *NewParam = ParmVarDecl::Create(
1791 SemaRef.Context, DC, Loc, Loc, nullptr, T,
1792 SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
1793 NewParam->setScopeInfo(0, Params.size());
1794 FPTL.setParam(Params.size(), NewParam);
1795 Params.push_back(NewParam);
1796 }
1797
1798 return buildDeductionGuide(Template->getTemplateParameters(), false, TSI,
1799 Loc, Loc, Loc);
1800 }
1801
1802private:
1803 /// Transform a constructor template parameter into a deduction guide template
1804 /// parameter, rebuilding any internal references to earlier parameters and
1805 /// renumbering as we go.
1806 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
1807 MultiLevelTemplateArgumentList &Args) {
1808 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
1809 // TemplateTypeParmDecl's index cannot be changed after creation, so
1810 // substitute it directly.
1811 auto *NewTTP = TemplateTypeParmDecl::Create(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001812 SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(),
1813 /*Depth*/ 0, Depth1IndexAdjustment + TTP->getIndex(),
Richard Smith32918772017-02-14 00:25:28 +00001814 TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
1815 TTP->isParameterPack());
1816 if (TTP->hasDefaultArgument()) {
1817 TypeSourceInfo *InstantiatedDefaultArg =
1818 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
1819 TTP->getDefaultArgumentLoc(), TTP->getDeclName());
1820 if (InstantiatedDefaultArg)
1821 NewTTP->setDefaultArgument(InstantiatedDefaultArg);
1822 }
Richard Smithb4f96252017-02-21 06:30:38 +00001823 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
1824 NewTTP);
Richard Smith32918772017-02-14 00:25:28 +00001825 return NewTTP;
1826 }
1827
1828 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
1829 return transformTemplateParameterImpl(TTP, Args);
1830
1831 return transformTemplateParameterImpl(
1832 cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
1833 }
1834 template<typename TemplateParmDecl>
1835 TemplateParmDecl *
1836 transformTemplateParameterImpl(TemplateParmDecl *OldParam,
1837 MultiLevelTemplateArgumentList &Args) {
1838 // Ask the template instantiator to do the heavy lifting for us, then adjust
1839 // the index of the parameter once it's done.
1840 auto *NewParam =
1841 cast_or_null<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
1842 assert(NewParam->getDepth() == 0 && "unexpected template param depth");
1843 NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
1844 return NewParam;
1845 }
1846
1847 QualType transformFunctionProtoType(TypeLocBuilder &TLB,
1848 FunctionProtoTypeLoc TL,
1849 SmallVectorImpl<ParmVarDecl*> &Params,
1850 MultiLevelTemplateArgumentList &Args) {
1851 SmallVector<QualType, 4> ParamTypes;
1852 const FunctionProtoType *T = TL.getTypePtr();
1853
1854 // -- The types of the function parameters are those of the constructor.
1855 for (auto *OldParam : TL.getParams()) {
Richard Smithc27b3d72017-02-14 01:49:59 +00001856 ParmVarDecl *NewParam = transformFunctionTypeParam(OldParam, Args);
Richard Smith32918772017-02-14 00:25:28 +00001857 if (!NewParam)
1858 return QualType();
1859 ParamTypes.push_back(NewParam->getType());
1860 Params.push_back(NewParam);
1861 }
1862
1863 // -- The return type is the class template specialization designated by
1864 // the template-name and template arguments corresponding to the
1865 // template parameters obtained from the class template.
1866 //
1867 // We use the injected-class-name type of the primary template instead.
1868 // This has the convenient property that it is different from any type that
1869 // the user can write in a deduction-guide (because they cannot enter the
1870 // context of the template), so implicit deduction guides can never collide
1871 // with explicit ones.
1872 QualType ReturnType = DeducedType;
1873 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
1874
1875 // Resolving a wording defect, we also inherit the variadicness of the
1876 // constructor.
1877 FunctionProtoType::ExtProtoInfo EPI;
1878 EPI.Variadic = T->isVariadic();
1879 EPI.HasTrailingReturn = true;
1880
1881 QualType Result = SemaRef.BuildFunctionType(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001882 ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI);
Richard Smith32918772017-02-14 00:25:28 +00001883 if (Result.isNull())
1884 return QualType();
1885
1886 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
1887 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
1888 NewTL.setLParenLoc(TL.getLParenLoc());
1889 NewTL.setRParenLoc(TL.getRParenLoc());
1890 NewTL.setExceptionSpecRange(SourceRange());
1891 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
1892 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
1893 NewTL.setParam(I, Params[I]);
1894
1895 return Result;
1896 }
1897
1898 ParmVarDecl *
1899 transformFunctionTypeParam(ParmVarDecl *OldParam,
1900 MultiLevelTemplateArgumentList &Args) {
1901 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
Richard Smith479ba8e2017-04-20 01:15:31 +00001902 TypeSourceInfo *NewDI;
Erik Pilkington69770d32018-07-27 21:23:48 +00001903 if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
Richard Smith479ba8e2017-04-20 01:15:31 +00001904 // Expand out the one and only element in each inner pack.
1905 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
1906 NewDI =
1907 SemaRef.SubstType(PackTL.getPatternLoc(), Args,
1908 OldParam->getLocation(), OldParam->getDeclName());
1909 if (!NewDI) return nullptr;
1910 NewDI =
1911 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
1912 PackTL.getTypePtr()->getNumExpansions());
1913 } else
1914 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
1915 OldParam->getDeclName());
Richard Smith32918772017-02-14 00:25:28 +00001916 if (!NewDI)
1917 return nullptr;
1918
Erik Pilkington69770d32018-07-27 21:23:48 +00001919 // Extract the type. This (for instance) replaces references to typedef
1920 // members of the current instantiations with the definitions of those
1921 // typedefs, avoiding triggering instantiation of the deduced type during
1922 // deduction.
1923 NewDI = ExtractTypeForDeductionGuide(SemaRef).transform(NewDI);
Richard Smithc27b3d72017-02-14 01:49:59 +00001924
Richard Smith32918772017-02-14 00:25:28 +00001925 // Resolving a wording defect, we also inherit default arguments from the
1926 // constructor.
1927 ExprResult NewDefArg;
1928 if (OldParam->hasDefaultArg()) {
Erik Pilkington69770d32018-07-27 21:23:48 +00001929 NewDefArg = SemaRef.SubstExpr(OldParam->getDefaultArg(), Args);
Richard Smith32918772017-02-14 00:25:28 +00001930 if (NewDefArg.isInvalid())
1931 return nullptr;
1932 }
1933
1934 ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
1935 OldParam->getInnerLocStart(),
1936 OldParam->getLocation(),
1937 OldParam->getIdentifier(),
1938 NewDI->getType(),
1939 NewDI,
1940 OldParam->getStorageClass(),
1941 NewDefArg.get());
1942 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
1943 OldParam->getFunctionScopeIndex());
Erik Pilkington69770d32018-07-27 21:23:48 +00001944 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);
Richard Smith32918772017-02-14 00:25:28 +00001945 return NewParam;
1946 }
1947
1948 NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams,
1949 bool Explicit, TypeSourceInfo *TInfo,
1950 SourceLocation LocStart, SourceLocation Loc,
1951 SourceLocation LocEnd) {
Richard Smithbc491202017-02-17 20:05:37 +00001952 DeclarationNameInfo Name(DeductionGuideName, Loc);
Richard Smithefa919a2017-02-16 21:29:21 +00001953 ArrayRef<ParmVarDecl *> Params =
1954 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
1955
Richard Smith32918772017-02-14 00:25:28 +00001956 // Build the implicit deduction guide template.
Richard Smithbc491202017-02-17 20:05:37 +00001957 auto *Guide =
1958 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, Explicit,
1959 Name, TInfo->getType(), TInfo, LocEnd);
Richard Smith32918772017-02-14 00:25:28 +00001960 Guide->setImplicit();
Richard Smithefa919a2017-02-16 21:29:21 +00001961 Guide->setParams(Params);
1962
1963 for (auto *Param : Params)
1964 Param->setDeclContext(Guide);
Richard Smith32918772017-02-14 00:25:28 +00001965
1966 auto *GuideTemplate = FunctionTemplateDecl::Create(
1967 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
1968 GuideTemplate->setImplicit();
1969 Guide->setDescribedFunctionTemplate(GuideTemplate);
1970
1971 if (isa<CXXRecordDecl>(DC)) {
1972 Guide->setAccess(AS_public);
1973 GuideTemplate->setAccess(AS_public);
1974 }
1975
1976 DC->addDecl(GuideTemplate);
1977 return GuideTemplate;
1978 }
1979};
1980}
1981
1982void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
1983 SourceLocation Loc) {
1984 DeclContext *DC = Template->getDeclContext();
1985 if (DC->isDependentContext())
1986 return;
1987
1988 ConvertConstructorToDeductionGuideTransform Transform(
1989 *this, cast<ClassTemplateDecl>(Template));
1990 if (!isCompleteType(Loc, Transform.DeducedType))
1991 return;
1992
1993 // Check whether we've already declared deduction guides for this template.
1994 // FIXME: Consider storing a flag on the template to indicate this.
1995 auto Existing = DC->lookup(Transform.DeductionGuideName);
1996 for (auto *D : Existing)
1997 if (D->isImplicit())
1998 return;
1999
2000 // In case we were expanding a pack when we attempted to declare deduction
2001 // guides, turn off pack expansion for everything we're about to do.
2002 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2003 // Create a template instantiation record to track the "instantiation" of
2004 // constructors into deduction guides.
2005 // FIXME: Add a kind for this to give more meaningful diagnostics. But can
2006 // this substitution process actually fail?
2007 InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
Volodymyr Sapsai2f649f32018-05-14 22:49:44 +00002008 if (BuildingDeductionGuides.isInvalid())
2009 return;
Richard Smith32918772017-02-14 00:25:28 +00002010
2011 // Convert declared constructors into deduction guide templates.
2012 // FIXME: Skip constructors for which deduction must necessarily fail (those
2013 // for which some class template parameter without a default argument never
2014 // appears in a deduced context).
2015 bool AddedAny = false;
Richard Smith32918772017-02-14 00:25:28 +00002016 for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
2017 D = D->getUnderlyingDecl();
2018 if (D->isInvalidDecl() || D->isImplicit())
2019 continue;
2020 D = cast<NamedDecl>(D->getCanonicalDecl());
2021
2022 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
Richard Smithbc491202017-02-17 20:05:37 +00002023 auto *CD =
2024 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
Richard Smith32918772017-02-14 00:25:28 +00002025 // Class-scope explicit specializations (MS extension) do not result in
2026 // deduction guides.
Richard Smithbc491202017-02-17 20:05:37 +00002027 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
Richard Smith32918772017-02-14 00:25:28 +00002028 continue;
2029
Richard Smithbc491202017-02-17 20:05:37 +00002030 Transform.transformConstructor(FTD, CD);
Richard Smith32918772017-02-14 00:25:28 +00002031 AddedAny = true;
Richard Smith32918772017-02-14 00:25:28 +00002032 }
2033
Faisal Vali81b756e2017-10-22 14:45:08 +00002034 // C++17 [over.match.class.deduct]
2035 // -- If C is not defined or does not declare any constructors, an
2036 // additional function template derived as above from a hypothetical
2037 // constructor C().
Richard Smith32918772017-02-14 00:25:28 +00002038 if (!AddedAny)
2039 Transform.buildSimpleDeductionGuide(None);
2040
Faisal Vali81b756e2017-10-22 14:45:08 +00002041 // -- An additional function template derived as above from a hypothetical
2042 // constructor C(C), called the copy deduction candidate.
2043 cast<CXXDeductionGuideDecl>(
2044 cast<FunctionTemplateDecl>(
2045 Transform.buildSimpleDeductionGuide(Transform.DeducedType))
2046 ->getTemplatedDecl())
2047 ->setIsCopyDeductionCandidate();
Richard Smith32918772017-02-14 00:25:28 +00002048}
2049
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002050/// Diagnose the presence of a default template argument on a
Douglas Gregored5731f2009-11-25 17:50:39 +00002051/// template parameter, which is ill-formed in certain contexts.
2052///
2053/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002054static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00002055 Sema::TemplateParamListContext TPC,
2056 SourceLocation ParamLoc,
2057 SourceRange DefArgRange) {
2058 switch (TPC) {
2059 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00002060 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00002061 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00002062 return false;
2063
2064 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00002065 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002066 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00002067 // A default template-argument shall not be specified in a
2068 // function template declaration or a function template
2069 // definition [...]
Simon Pilgrim6905d222016-12-30 22:55:33 +00002070 // If a friend function template declaration specifies a default
Douglas Gregora99fb4c2011-02-04 04:20:44 +00002071 // template-argument, that declaration shall be a definition and shall be
2072 // the only declaration of the function template in the translation unit.
2073 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002074 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002075 diag::warn_cxx98_compat_template_parameter_default_in_function_template
2076 : diag::ext_template_parameter_default_in_function_template)
2077 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00002078 return false;
2079
2080 case Sema::TPC_ClassTemplateMember:
2081 // C++0x [temp.param]p9:
2082 // A default template-argument shall not be specified in the
2083 // template-parameter-lists of the definition of a member of a
2084 // class template that appears outside of the member's class.
2085 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2086 << DefArgRange;
2087 return true;
2088
David Majnemerba8f17a2013-06-25 22:08:55 +00002089 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00002090 case Sema::TPC_FriendFunctionTemplate:
2091 // C++ [temp.param]p9:
2092 // A default template-argument shall not be specified in a
2093 // friend template declaration.
2094 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2095 << DefArgRange;
2096 return true;
2097
2098 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2099 // for friend function templates if there is only a single
2100 // declaration (and it is a definition). Strange!
2101 }
2102
David Blaikie8a40f702012-01-17 06:56:22 +00002103 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00002104}
2105
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002106/// Check for unexpanded parameter packs within the template parameters
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002107/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00002108static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2109 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00002110 // A template template parameter which is a parameter pack is also a pack
2111 // expansion.
2112 if (TTP->isParameterPack())
2113 return false;
2114
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002115 TemplateParameterList *Params = TTP->getTemplateParameters();
2116 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2117 NamedDecl *P = Params->getParam(I);
2118 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00002119 if (!NTTP->isParameterPack() &&
2120 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002121 NTTP->getTypeSourceInfo(),
2122 Sema::UPPC_NonTypeTemplateParameterType))
2123 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002124
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002125 continue;
2126 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002127
2128 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002129 = dyn_cast<TemplateTemplateParmDecl>(P))
2130 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2131 return true;
2132 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002133
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002134 return false;
2135}
2136
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002137/// Checks the validity of a template parameter list, possibly
Douglas Gregordba32632009-02-10 19:49:53 +00002138/// considering the template parameter list from a previous
2139/// declaration.
2140///
2141/// If an "old" template parameter list is provided, it must be
2142/// equivalent (per TemplateParameterListsAreEqual) to the "new"
2143/// template parameter list.
2144///
2145/// \param NewParams Template parameter list for a new template
2146/// declaration. This template parameter list will be updated with any
2147/// default arguments that are carried through from the previous
2148/// template parameter list.
2149///
2150/// \param OldParams If provided, template parameter list from a
2151/// previous declaration of the same template. Default template
2152/// arguments will be merged from the old template parameter list to
2153/// the new template parameter list.
2154///
Douglas Gregored5731f2009-11-25 17:50:39 +00002155/// \param TPC Describes the context in which we are checking the given
2156/// template parameter list.
2157///
Richard Smithc4577662018-09-12 02:13:47 +00002158/// \param SkipBody If we might have already made a prior merged definition
2159/// of this template visible, the corresponding body-skipping information.
2160/// Default argument redefinition is not an error when skipping such a body,
2161/// because (under the ODR) we can assume the default arguments are the same
2162/// as the prior merged definition.
2163///
Douglas Gregordba32632009-02-10 19:49:53 +00002164/// \returns true if an error occurred, false otherwise.
2165bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00002166 TemplateParameterList *OldParams,
Richard Smithc4577662018-09-12 02:13:47 +00002167 TemplateParamListContext TPC,
2168 SkipBodyInfo *SkipBody) {
Douglas Gregordba32632009-02-10 19:49:53 +00002169 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00002170
Douglas Gregordba32632009-02-10 19:49:53 +00002171 // C++ [temp.param]p10:
2172 // The set of default template-arguments available for use with a
2173 // template declaration or definition is obtained by merging the
2174 // default arguments from the definition (if in scope) and all
2175 // declarations in scope in the same way default function
2176 // arguments are (8.3.6).
2177 bool SawDefaultArgument = false;
2178 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00002179
Mike Stumpc89c8e32009-02-11 23:03:27 +00002180 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00002181 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00002182 if (OldParams)
2183 OldParam = OldParams->begin();
2184
Douglas Gregor0693def2011-01-27 01:40:17 +00002185 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00002186 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2187 NewParamEnd = NewParams->end();
2188 NewParam != NewParamEnd; ++NewParam) {
2189 // Variables used to diagnose redundant default arguments
2190 bool RedundantDefaultArg = false;
2191 SourceLocation OldDefaultLoc;
2192 SourceLocation NewDefaultLoc;
2193
David Blaikie651c73c2011-10-19 05:19:50 +00002194 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00002195 bool MissingDefaultArg = false;
2196
David Blaikie651c73c2011-10-19 05:19:50 +00002197 // Variable used to diagnose non-final parameter packs
2198 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00002199
Douglas Gregordba32632009-02-10 19:49:53 +00002200 if (TemplateTypeParmDecl *NewTypeParm
2201 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00002202 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002203 if (NewTypeParm->hasDefaultArgument() &&
2204 DiagnoseDefaultTemplateArgument(*this, TPC,
2205 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002206 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002207 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00002208 NewTypeParm->removeDefaultArgument();
2209
2210 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00002211 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002212 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Anders Carlsson327865d2009-06-12 23:20:15 +00002213 if (NewTypeParm->isParameterPack()) {
2214 assert(!NewTypeParm->hasDefaultArgument() &&
2215 "Parameter packs can't have a default argument!");
2216 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002217 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
Richard Smithc4577662018-09-12 02:13:47 +00002218 NewTypeParm->hasDefaultArgument() &&
2219 (!SkipBody || !SkipBody->ShouldSkip)) {
Douglas Gregordba32632009-02-10 19:49:53 +00002220 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2221 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2222 SawDefaultArgument = true;
2223 RedundantDefaultArg = true;
2224 PreviousDefaultArgLoc = NewDefaultLoc;
2225 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2226 // Merge the default argument from the old declaration to the
2227 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002228 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00002229 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2230 } else if (NewTypeParm->hasDefaultArgument()) {
2231 SawDefaultArgument = true;
2232 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2233 } else if (SawDefaultArgument)
2234 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00002235 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00002236 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002237 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002238 if (!NewNonTypeParm->isParameterPack() &&
2239 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002240 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002241 UPPC_NonTypeTemplateParameterType)) {
2242 Invalid = true;
2243 continue;
2244 }
2245
Douglas Gregored5731f2009-11-25 17:50:39 +00002246 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002247 if (NewNonTypeParm->hasDefaultArgument() &&
2248 DiagnoseDefaultTemplateArgument(*this, TPC,
2249 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002250 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00002251 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00002252 }
2253
Mike Stump12b8ce12009-08-04 21:02:39 +00002254 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00002255 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002256 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00002257 if (NewNonTypeParm->isParameterPack()) {
2258 assert(!NewNonTypeParm->hasDefaultArgument() &&
2259 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00002260 if (!NewNonTypeParm->isPackExpansion())
2261 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002262 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
Richard Smithc4577662018-09-12 02:13:47 +00002263 NewNonTypeParm->hasDefaultArgument() &&
2264 (!SkipBody || !SkipBody->ShouldSkip)) {
Douglas Gregordba32632009-02-10 19:49:53 +00002265 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2266 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2267 SawDefaultArgument = true;
2268 RedundantDefaultArg = true;
2269 PreviousDefaultArgLoc = NewDefaultLoc;
2270 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2271 // Merge the default argument from the old declaration to the
2272 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002273 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00002274 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2275 } else if (NewNonTypeParm->hasDefaultArgument()) {
2276 SawDefaultArgument = true;
2277 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2278 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002279 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00002280 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00002281 TemplateTemplateParmDecl *NewTemplateParm
2282 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002283
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002284 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00002285 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002286 Invalid = true;
2287 continue;
2288 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002289
David Blaikie651c73c2011-10-19 05:19:50 +00002290 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002291 if (NewTemplateParm->hasDefaultArgument() &&
2292 DiagnoseDefaultTemplateArgument(*this, TPC,
2293 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002294 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00002295 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00002296
2297 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00002298 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002299 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00002300 if (NewTemplateParm->isParameterPack()) {
2301 assert(!NewTemplateParm->hasDefaultArgument() &&
2302 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00002303 if (!NewTemplateParm->isPackExpansion())
2304 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002305 } else if (OldTemplateParm &&
2306 hasVisibleDefaultArgument(OldTemplateParm) &&
Richard Smithc4577662018-09-12 02:13:47 +00002307 NewTemplateParm->hasDefaultArgument() &&
2308 (!SkipBody || !SkipBody->ShouldSkip)) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002309 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2310 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002311 SawDefaultArgument = true;
2312 RedundantDefaultArg = true;
2313 PreviousDefaultArgLoc = NewDefaultLoc;
2314 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2315 // Merge the default argument from the old declaration to the
2316 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002317 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002318 PreviousDefaultArgLoc
2319 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002320 } else if (NewTemplateParm->hasDefaultArgument()) {
2321 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002322 PreviousDefaultArgLoc
2323 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002324 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002325 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00002326 }
2327
Richard Smith1fde8ec2012-09-07 02:06:42 +00002328 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00002329 // If a template parameter of a primary class template or alias template
2330 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002331 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00002332 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2333 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00002334 Diag((*NewParam)->getLocation(),
2335 diag::err_template_param_pack_must_be_last_template_parameter);
2336 Invalid = true;
2337 }
2338
Douglas Gregordba32632009-02-10 19:49:53 +00002339 if (RedundantDefaultArg) {
2340 // C++ [temp.param]p12:
2341 // A template-parameter shall not be given default arguments
2342 // by two different declarations in the same scope.
2343 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2344 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2345 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00002346 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00002347 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002348 // If a template-parameter of a class template has a default
2349 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00002350 // have a default template-argument supplied or be a template parameter
2351 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00002352 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00002353 diag::err_template_param_default_arg_missing);
2354 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2355 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00002356 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00002357 }
2358
2359 // If we have an old template parameter list that we're merging
2360 // in, move on to the next parameter.
2361 if (OldParams)
2362 ++OldParam;
2363 }
2364
Douglas Gregor0693def2011-01-27 01:40:17 +00002365 // We were missing some default arguments at the end of the list, so remove
2366 // all of the default arguments.
2367 if (RemoveDefaultArguments) {
2368 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2369 NewParamEnd = NewParams->end();
2370 NewParam != NewParamEnd; ++NewParam) {
2371 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2372 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002373 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00002374 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2375 NTTP->removeDefaultArgument();
2376 else
2377 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2378 }
2379 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002380
Douglas Gregordba32632009-02-10 19:49:53 +00002381 return Invalid;
2382}
Douglas Gregord32e0282009-02-09 23:23:08 +00002383
John McCalla020a012010-10-20 05:44:58 +00002384namespace {
2385
2386/// A class which looks for a use of a certain level of template
2387/// parameter.
2388struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2389 typedef RecursiveASTVisitor<DependencyChecker> super;
2390
2391 unsigned Depth;
Richard Smith57aae072016-12-28 02:37:25 +00002392
2393 // Whether we're looking for a use of a template parameter that makes the
2394 // overall construct type-dependent / a dependent type. This is strictly
2395 // best-effort for now; we may fail to match at all for a dependent type
2396 // in some cases if this is set.
2397 bool IgnoreNonTypeDependent;
2398
John McCalla020a012010-10-20 05:44:58 +00002399 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00002400 SourceLocation MatchLoc;
2401
Richard Smith13894182017-04-13 21:37:24 +00002402 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2403 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2404 Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00002405
Richard Smith57aae072016-12-28 02:37:25 +00002406 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
Richard Smith13894182017-04-13 21:37:24 +00002407 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2408 NamedDecl *ND = Params->getParam(0);
2409 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2410 Depth = PD->getDepth();
2411 } else if (NonTypeTemplateParmDecl *PD =
2412 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2413 Depth = PD->getDepth();
2414 } else {
2415 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2416 }
2417 }
John McCalla020a012010-10-20 05:44:58 +00002418
Richard Smith6056d5e2014-02-09 00:54:43 +00002419 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
Richard Smith13894182017-04-13 21:37:24 +00002420 if (ParmDepth >= Depth) {
John McCalla020a012010-10-20 05:44:58 +00002421 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00002422 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00002423 return true;
2424 }
2425 return false;
2426 }
2427
Richard Smith57aae072016-12-28 02:37:25 +00002428 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2429 // Prune out non-type-dependent expressions if requested. This can
2430 // sometimes result in us failing to find a template parameter reference
2431 // (if a value-dependent expression creates a dependent type), but this
2432 // mode is best-effort only.
2433 if (auto *E = dyn_cast_or_null<Expr>(S))
2434 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2435 return true;
2436 return super::TraverseStmt(S, Q);
2437 }
2438
2439 bool TraverseTypeLoc(TypeLoc TL) {
2440 if (IgnoreNonTypeDependent && !TL.isNull() &&
2441 !TL.getType()->isDependentType())
2442 return true;
2443 return super::TraverseTypeLoc(TL);
2444 }
2445
Richard Smith6056d5e2014-02-09 00:54:43 +00002446 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2447 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2448 }
2449
John McCalla020a012010-10-20 05:44:58 +00002450 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
Richard Smith57aae072016-12-28 02:37:25 +00002451 // For a best-effort search, keep looking until we find a location.
2452 return IgnoreNonTypeDependent || !Matches(T->getDepth());
John McCalla020a012010-10-20 05:44:58 +00002453 }
2454
2455 bool TraverseTemplateName(TemplateName N) {
2456 if (TemplateTemplateParmDecl *PD =
2457 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00002458 if (Matches(PD->getDepth()))
2459 return false;
John McCalla020a012010-10-20 05:44:58 +00002460 return super::TraverseTemplateName(N);
2461 }
2462
2463 bool VisitDeclRefExpr(DeclRefExpr *E) {
2464 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00002465 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2466 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00002467 return false;
John McCalla020a012010-10-20 05:44:58 +00002468 return super::VisitDeclRefExpr(E);
2469 }
Richard Smith6056d5e2014-02-09 00:54:43 +00002470
2471 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2472 return TraverseType(T->getReplacementType());
2473 }
2474
2475 bool
2476 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2477 return TraverseTemplateArgument(T->getArgumentPack());
2478 }
2479
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00002480 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2481 return TraverseType(T->getInjectedSpecializationType());
2482 }
John McCalla020a012010-10-20 05:44:58 +00002483};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002484} // end anonymous namespace
John McCalla020a012010-10-20 05:44:58 +00002485
Douglas Gregor972fe532011-05-10 18:27:06 +00002486/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00002487/// list.
2488static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00002489DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
Richard Smith57aae072016-12-28 02:37:25 +00002490 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
Douglas Gregor972fe532011-05-10 18:27:06 +00002491 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00002492 return Checker.Match;
2493}
2494
Douglas Gregor972fe532011-05-10 18:27:06 +00002495// Find the source range corresponding to the named type in the given
2496// nested-name-specifier, if any.
2497static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2498 QualType T,
2499 const CXXScopeSpec &SS) {
2500 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2501 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2502 if (const Type *CurType = NNS->getAsType()) {
2503 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2504 return NNSLoc.getTypeLoc().getSourceRange();
2505 } else
2506 break;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002507
Douglas Gregor972fe532011-05-10 18:27:06 +00002508 NNSLoc = NNSLoc.getPrefix();
2509 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002510
Douglas Gregor972fe532011-05-10 18:27:06 +00002511 return SourceRange();
2512}
2513
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002514/// Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00002515/// specifier, returning the template parameter list that applies to the
2516/// name.
2517///
2518/// \param DeclStartLoc the start of the declaration that has a scope
2519/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00002520///
Douglas Gregor972fe532011-05-10 18:27:06 +00002521/// \param DeclLoc The location of the declaration itself.
2522///
Douglas Gregord8d297c2009-07-21 23:53:31 +00002523/// \param SS the scope specifier that will be matched to the given template
2524/// parameter lists. This scope specifier precedes a qualified name that is
2525/// being declared.
2526///
Richard Smith4b55a9c2014-04-17 03:29:33 +00002527/// \param TemplateId The template-id following the scope specifier, if there
2528/// is one. Used to check for a missing 'template<>'.
2529///
Douglas Gregord8d297c2009-07-21 23:53:31 +00002530/// \param ParamLists the template parameter lists, from the outermost to the
2531/// innermost template parameter lists.
2532///
John McCalle820e5e2010-04-13 20:37:33 +00002533/// \param IsFriend Whether to apply the slightly different rules for
2534/// matching template parameters to scope specifiers in friend
2535/// declarations.
2536///
Richard Smithf445f192017-02-09 21:04:43 +00002537/// \param IsMemberSpecialization will be set true if the scope specifier
2538/// denotes a fully-specialized type, and therefore this is a declaration of
2539/// a member specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002540///
Mike Stump11289f42009-09-09 15:08:12 +00002541/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00002542/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00002543/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00002544/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00002545/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00002546/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002547TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2548 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00002549 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002550 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
Richard Smithf445f192017-02-09 21:04:43 +00002551 bool &IsMemberSpecialization, bool &Invalid) {
2552 IsMemberSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00002553 Invalid = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002554
Douglas Gregor972fe532011-05-10 18:27:06 +00002555 // The sequence of nested types to which we will match up the template
2556 // parameter lists. We first build this list by starting with the type named
2557 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002558 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00002559 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00002560 if (SS.getScopeRep()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002561 if (CXXRecordDecl *Record
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00002562 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2563 T = Context.getTypeDeclType(Record);
2564 else
2565 T = QualType(SS.getScopeRep()->getAsType(), 0);
2566 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002567
Douglas Gregor972fe532011-05-10 18:27:06 +00002568 // If we found an explicit specialization that prevents us from needing
2569 // 'template<>' headers, this will be set to the location of that
2570 // explicit specialization.
2571 SourceLocation ExplicitSpecLoc;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002572
Douglas Gregor972fe532011-05-10 18:27:06 +00002573 while (!T.isNull()) {
2574 NestedTypes.push_back(T);
Simon Pilgrim6905d222016-12-30 22:55:33 +00002575
Douglas Gregor972fe532011-05-10 18:27:06 +00002576 // Retrieve the parent of a record type.
2577 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2578 // If this type is an explicit specialization, we're done.
2579 if (ClassTemplateSpecializationDecl *Spec
2580 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002581 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002582 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2583 ExplicitSpecLoc = Spec->getLocation();
2584 break;
Douglas Gregor65911492009-11-23 12:11:45 +00002585 }
Douglas Gregor972fe532011-05-10 18:27:06 +00002586 } else if (Record->getTemplateSpecializationKind()
2587 == TSK_ExplicitSpecialization) {
2588 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00002589 break;
2590 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002591
Douglas Gregor972fe532011-05-10 18:27:06 +00002592 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2593 T = Context.getTypeDeclType(Parent);
2594 else
2595 T = QualType();
2596 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002597 }
2598
Douglas Gregor972fe532011-05-10 18:27:06 +00002599 if (const TemplateSpecializationType *TST
2600 = T->getAs<TemplateSpecializationType>()) {
2601 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2602 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2603 T = Context.getTypeDeclType(Parent);
2604 else
2605 T = QualType();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002606 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002607 }
Douglas Gregor972fe532011-05-10 18:27:06 +00002608 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002609
Douglas Gregor972fe532011-05-10 18:27:06 +00002610 // Look one step prior in a dependent template specialization type.
2611 if (const DependentTemplateSpecializationType *DependentTST
2612 = T->getAs<DependentTemplateSpecializationType>()) {
2613 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2614 T = QualType(NNS->getAsType(), 0);
2615 else
2616 T = QualType();
2617 continue;
2618 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002619
Douglas Gregor972fe532011-05-10 18:27:06 +00002620 // Look one step prior in a dependent name type.
2621 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2622 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2623 T = QualType(NNS->getAsType(), 0);
2624 else
2625 T = QualType();
2626 continue;
2627 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002628
Douglas Gregor972fe532011-05-10 18:27:06 +00002629 // Retrieve the parent of an enumeration type.
2630 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2631 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2632 // check here.
2633 EnumDecl *Enum = EnumT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002634
Douglas Gregor972fe532011-05-10 18:27:06 +00002635 // Get to the parent type.
2636 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2637 T = Context.getTypeDeclType(Parent);
2638 else
Simon Pilgrim6905d222016-12-30 22:55:33 +00002639 T = QualType();
Douglas Gregor972fe532011-05-10 18:27:06 +00002640 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002641 }
Mike Stump11289f42009-09-09 15:08:12 +00002642
Douglas Gregor972fe532011-05-10 18:27:06 +00002643 T = QualType();
2644 }
2645 // Reverse the nested types list, since we want to traverse from the outermost
2646 // to the innermost while checking template-parameter-lists.
2647 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00002648
Douglas Gregor972fe532011-05-10 18:27:06 +00002649 // C++0x [temp.expl.spec]p17:
2650 // A member or a member template may be nested within many
2651 // enclosing class templates. In an explicit specialization for
2652 // such a member, the member declaration shall be preceded by a
2653 // template<> for each enclosing class template that is
2654 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002655 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00002656
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002657 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00002658 if (SawNonEmptyTemplateParameterList) {
2659 Diag(DeclLoc, diag::err_specialize_member_of_template)
2660 << !Recovery << Range;
2661 Invalid = true;
Richard Smithf445f192017-02-09 21:04:43 +00002662 IsMemberSpecialization = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00002663 return true;
2664 }
2665
2666 return false;
2667 };
2668
2669 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2670 // Check that we can have an explicit specialization here.
2671 if (CheckExplicitSpecialization(Range, true))
2672 return true;
2673
2674 // We don't have a template header, but we should.
2675 SourceLocation ExpectedTemplateLoc;
2676 if (!ParamLists.empty())
2677 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2678 else
2679 ExpectedTemplateLoc = DeclStartLoc;
2680
2681 Diag(DeclLoc, diag::err_template_spec_needs_header)
2682 << Range
2683 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2684 return false;
2685 };
2686
Douglas Gregor972fe532011-05-10 18:27:06 +00002687 unsigned ParamIdx = 0;
2688 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2689 ++TypeIdx) {
2690 T = NestedTypes[TypeIdx];
Simon Pilgrim6905d222016-12-30 22:55:33 +00002691
Douglas Gregor972fe532011-05-10 18:27:06 +00002692 // Whether we expect a 'template<>' header.
2693 bool NeedEmptyTemplateHeader = false;
2694
2695 // Whether we expect a template header with parameters.
2696 bool NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002697
Douglas Gregor972fe532011-05-10 18:27:06 +00002698 // For a dependent type, the set of template parameters that we
2699 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00002700 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002701
Douglas Gregor373af9b2011-05-11 23:26:17 +00002702 // C++0x [temp.expl.spec]p15:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002703 // A member or a member template may be nested within many enclosing
2704 // class templates. In an explicit specialization for such a member, the
2705 // member declaration shall be preceded by a template<> for each
Douglas Gregor373af9b2011-05-11 23:26:17 +00002706 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00002707 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2708 if (ClassTemplatePartialSpecializationDecl *Partial
2709 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2710 ExpectedTemplateParams = Partial->getTemplateParameters();
2711 NeedNonemptyTemplateHeader = true;
2712 } else if (Record->isDependentType()) {
2713 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00002714 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00002715 ->getTemplateParameters();
2716 NeedNonemptyTemplateHeader = true;
2717 }
2718 } else if (ClassTemplateSpecializationDecl *Spec
2719 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2720 // C++0x [temp.expl.spec]p4:
2721 // Members of an explicitly specialized class template are defined
Simon Pilgrim6905d222016-12-30 22:55:33 +00002722 // in the same manner as members of normal classes, and not using
2723 // the template<> syntax.
Douglas Gregor972fe532011-05-10 18:27:06 +00002724 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2725 NeedEmptyTemplateHeader = true;
2726 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00002727 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002728 } else if (Record->getTemplateSpecializationKind()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002729 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00002730 != TSK_ExplicitSpecialization &&
2731 TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002732 IsMemberSpecialization = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002733
Douglas Gregor373af9b2011-05-11 23:26:17 +00002734 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002735 }
2736 } else if (const TemplateSpecializationType *TST
2737 = T->getAs<TemplateSpecializationType>()) {
Nico Weber28900612015-01-30 02:35:21 +00002738 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002739 ExpectedTemplateParams = Template->getTemplateParameters();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002740 NeedNonemptyTemplateHeader = true;
Douglas Gregor972fe532011-05-10 18:27:06 +00002741 }
2742 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2743 // FIXME: We actually could/should check the template arguments here
2744 // against the corresponding template parameter list.
2745 NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002746 }
2747
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002748 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002749 // In an explicit specialization declaration for a member of a class
2750 // template or a member template that ap- pears in namespace scope, the
2751 // member template and some of its enclosing class templates may remain
2752 // unspecialized, except that the declaration shall not explicitly
2753 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002754 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002755 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002756 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002757 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2758 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002759 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002760 } else
2761 SawNonEmptyTemplateParameterList = true;
2762 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002763
Douglas Gregor972fe532011-05-10 18:27:06 +00002764 if (NeedEmptyTemplateHeader) {
2765 // If we're on the last of the types, and we need a 'template<>' header
Richard Smithf445f192017-02-09 21:04:43 +00002766 // here, then it's a member specialization.
Douglas Gregor972fe532011-05-10 18:27:06 +00002767 if (TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002768 IsMemberSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002769
2770 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002771 if (ParamLists[ParamIdx]->size() > 0) {
2772 // The header has template parameters when it shouldn't. Complain.
Simon Pilgrim6905d222016-12-30 22:55:33 +00002773 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregor972fe532011-05-10 18:27:06 +00002774 diag::err_template_param_list_matches_nontemplate)
2775 << T
2776 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2777 ParamLists[ParamIdx]->getRAngleLoc())
2778 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2779 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002780 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002781 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002782
Douglas Gregor972fe532011-05-10 18:27:06 +00002783 // Consume this template header.
2784 ++ParamIdx;
2785 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002786 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002787
2788 if (!IsFriend)
2789 if (DiagnoseMissingExplicitSpecialization(
2790 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00002791 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002792
Douglas Gregor972fe532011-05-10 18:27:06 +00002793 continue;
2794 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002795
Douglas Gregor972fe532011-05-10 18:27:06 +00002796 if (NeedNonemptyTemplateHeader) {
2797 // In friend declarations we can have template-ids which don't
2798 // depend on the corresponding template parameter lists. But
2799 // assume that empty parameter lists are supposed to match this
2800 // template-id.
2801 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002802 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002803 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00002804 ExpectedTemplateParams = nullptr;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002805 else
Douglas Gregor972fe532011-05-10 18:27:06 +00002806 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002807 }
Douglas Gregored5731f2009-11-25 17:50:39 +00002808
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002809 if (ParamIdx < ParamLists.size()) {
2810 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00002811 if (ExpectedTemplateParams &&
2812 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2813 ExpectedTemplateParams,
2814 true, TPL_TemplateMatch))
2815 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002816
Douglas Gregor972fe532011-05-10 18:27:06 +00002817 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00002818 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00002819 TPC_ClassTemplateMember))
2820 Invalid = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002821
Douglas Gregor972fe532011-05-10 18:27:06 +00002822 ++ParamIdx;
2823 continue;
2824 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002825
Douglas Gregor972fe532011-05-10 18:27:06 +00002826 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2827 << T
2828 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2829 Invalid = true;
2830 continue;
2831 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00002832 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00002833
Douglas Gregord8d297c2009-07-21 23:53:31 +00002834 // If there were at least as many template-ids as there were template
2835 // parameter lists, then there are no template parameter lists remaining for
2836 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00002837 if (ParamIdx >= ParamLists.size()) {
2838 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00002839 // We don't have a template header for the declaration itself, but we
2840 // should.
Richard Smith11a80dc2014-04-17 03:52:20 +00002841 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2842 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00002843
2844 // Fabricate an empty template parameter list for the invented header.
2845 return TemplateParameterList::Create(Context, SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +00002846 SourceLocation(), None,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00002847 SourceLocation(), nullptr);
Richard Smith4b55a9c2014-04-17 03:29:33 +00002848 }
2849
Craig Topperc3ec1492014-05-26 06:22:03 +00002850 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002851 }
Mike Stump11289f42009-09-09 15:08:12 +00002852
Douglas Gregord8d297c2009-07-21 23:53:31 +00002853 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002854 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002855 bool HasAnyExplicitSpecHeader = false;
2856 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002857 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002858 if (ParamLists[I]->size() == 0)
2859 HasAnyExplicitSpecHeader = true;
2860 else
2861 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002862 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002863
Douglas Gregor972fe532011-05-10 18:27:06 +00002864 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002865 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2866 : diag::err_template_spec_extra_headers)
2867 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2868 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00002869
2870 // If there was a specialization somewhere, such that 'template<>' is
2871 // not required, and there were any 'template<>' headers, note where the
2872 // specialization occurred.
2873 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
Simon Pilgrim6905d222016-12-30 22:55:33 +00002874 Diag(ExplicitSpecLoc,
Douglas Gregor972fe532011-05-10 18:27:06 +00002875 diag::note_explicit_template_spec_does_not_need_header)
2876 << NestedTypes.back();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002877
Douglas Gregor972fe532011-05-10 18:27:06 +00002878 // We have a template parameter list with no corresponding scope, which
2879 // means that the resulting template declaration can't be instantiated
2880 // properly (we'll end up with dependent nodes when we shouldn't).
2881 if (!AllExplicitSpecHeaders)
2882 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002883 }
Mike Stump11289f42009-09-09 15:08:12 +00002884
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002885 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002886 // In an explicit specialization declaration for a member of a class
2887 // template or a member template that ap- pears in namespace scope, the
2888 // member template and some of its enclosing class templates may remain
2889 // unspecialized, except that the declaration shall not explicitly
2890 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002891 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00002892 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002893 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2894 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002895 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002896
Douglas Gregord8d297c2009-07-21 23:53:31 +00002897 // Return the last template parameter list, which corresponds to the
2898 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002899 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00002900}
2901
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002902void Sema::NoteAllFoundTemplates(TemplateName Name) {
2903 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2904 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002905 << (isa<FunctionTemplateDecl>(Template)
2906 ? 0
2907 : isa<ClassTemplateDecl>(Template)
2908 ? 1
2909 : isa<VarTemplateDecl>(Template)
2910 ? 2
2911 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2912 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002913 return;
2914 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002915
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002916 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002917 for (OverloadedTemplateStorage::iterator I = OST->begin(),
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002918 IEnd = OST->end();
2919 I != IEnd; ++I)
2920 Diag((*I)->getLocation(), diag::note_template_declared_here)
2921 << 0 << (*I)->getDeclName();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002922
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002923 return;
2924 }
2925}
2926
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002927static QualType
2928checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2929 const SmallVectorImpl<TemplateArgument> &Converted,
2930 SourceLocation TemplateLoc,
2931 TemplateArgumentListInfo &TemplateArgs) {
2932 ASTContext &Context = SemaRef.getASTContext();
2933 switch (BTD->getBuiltinTemplateKind()) {
Eric Fiselier6ad68552016-07-01 01:24:09 +00002934 case BTK__make_integer_seq: {
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002935 // Specializations of __make_integer_seq<S, T, N> are treated like
2936 // S<T, 0, ..., N-1>.
2937
2938 // C++14 [inteseq.intseq]p1:
2939 // T shall be an integer type.
2940 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2941 SemaRef.Diag(TemplateArgs[1].getLocation(),
2942 diag::err_integer_sequence_integral_element_type);
2943 return QualType();
2944 }
2945
2946 // C++14 [inteseq.make]p1:
2947 // If N is negative the program is ill-formed.
2948 TemplateArgument NumArgsArg = Converted[2];
2949 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2950 if (NumArgs < 0) {
2951 SemaRef.Diag(TemplateArgs[2].getLocation(),
2952 diag::err_integer_sequence_negative_length);
2953 return QualType();
2954 }
2955
2956 QualType ArgTy = NumArgsArg.getIntegralType();
2957 TemplateArgumentListInfo SyntheticTemplateArgs;
2958 // The type argument gets reused as the first template argument in the
2959 // synthetic template argument list.
2960 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2961 // Expand N into 0 ... N-1.
2962 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2963 I < NumArgs; ++I) {
2964 TemplateArgument TA(Context, I, ArgTy);
Richard Smith7873de02016-08-11 22:25:46 +00002965 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
2966 TA, ArgTy, TemplateArgs[2].getLocation()));
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002967 }
2968 // The first template argument will be reused as the template decl that
2969 // our synthetic template arguments will be applied to.
2970 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2971 TemplateLoc, SyntheticTemplateArgs);
2972 }
Eric Fiselier6ad68552016-07-01 01:24:09 +00002973
2974 case BTK__type_pack_element:
2975 // Specializations of
2976 // __type_pack_element<Index, T_1, ..., T_N>
2977 // are treated like T_Index.
2978 assert(Converted.size() == 2 &&
2979 "__type_pack_element should be given an index and a parameter pack");
2980
2981 // If the Index is out of bounds, the program is ill-formed.
2982 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
2983 llvm::APSInt Index = IndexArg.getAsIntegral();
2984 assert(Index >= 0 && "the index used with __type_pack_element should be of "
2985 "type std::size_t, and hence be non-negative");
2986 if (Index >= Ts.pack_size()) {
2987 SemaRef.Diag(TemplateArgs[0].getLocation(),
2988 diag::err_type_pack_element_out_of_bounds);
2989 return QualType();
2990 }
2991
2992 // We simply return the type at index `Index`.
2993 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
2994 return Nth->getAsType();
2995 }
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002996 llvm_unreachable("unexpected BuiltinTemplateDecl!");
2997}
2998
Douglas Gregor00fa10b2017-07-05 20:20:14 +00002999/// Determine whether this alias template is "enable_if_t".
3000static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3001 return AliasTemplate->getName().equals("enable_if_t");
3002}
3003
3004/// Collect all of the separable terms in the given condition, which
3005/// might be a conjunction.
3006///
3007/// FIXME: The right answer is to convert the logical expression into
3008/// disjunctive normal form, so we can find the first failed term
3009/// within each possible clause.
3010static void collectConjunctionTerms(Expr *Clause,
3011 SmallVectorImpl<Expr *> &Terms) {
3012 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3013 if (BinOp->getOpcode() == BO_LAnd) {
3014 collectConjunctionTerms(BinOp->getLHS(), Terms);
3015 collectConjunctionTerms(BinOp->getRHS(), Terms);
3016 }
3017
3018 return;
3019 }
3020
3021 Terms.push_back(Clause);
3022}
3023
Douglas Gregorbb33f572017-07-05 20:20:15 +00003024// The ranges-v3 library uses an odd pattern of a top-level "||" with
3025// a left-hand side that is value-dependent but never true. Identify
3026// the idiom and ignore that term.
3027static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3028 // Top-level '||'.
3029 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3030 if (!BinOp) return Cond;
3031
3032 if (BinOp->getOpcode() != BO_LOr) return Cond;
3033
3034 // With an inner '==' that has a literal on the right-hand side.
3035 Expr *LHS = BinOp->getLHS();
Douglas Gregorc0fe1f22017-07-05 21:12:37 +00003036 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
Douglas Gregorbb33f572017-07-05 20:20:15 +00003037 if (!InnerBinOp) return Cond;
3038
3039 if (InnerBinOp->getOpcode() != BO_EQ ||
3040 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3041 return Cond;
3042
3043 // If the inner binary operation came from a macro expansion named
3044 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3045 // of the '||', which is the real, user-provided condition.
Douglas Gregorc0fe1f22017-07-05 21:12:37 +00003046 SourceLocation Loc = InnerBinOp->getExprLoc();
Douglas Gregorbb33f572017-07-05 20:20:15 +00003047 if (!Loc.isMacroID()) return Cond;
3048
3049 StringRef MacroName = PP.getImmediateMacroName(Loc);
3050 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3051 return BinOp->getRHS();
3052
3053 return Cond;
3054}
3055
Clement Courbetf44c6f42018-12-11 08:39:11 +00003056namespace {
3057
3058// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3059// within failing boolean expression, such as substituting template parameters
3060// for actual types.
3061class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3062public:
3063 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3064 : Policy(P) {}
3065
3066 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3067 const auto *DR = dyn_cast<DeclRefExpr>(E);
3068 if (DR && DR->getQualifier()) {
3069 // If this is a qualified name, expand the template arguments in nested
3070 // qualifiers.
3071 DR->getQualifier()->print(OS, Policy, true);
3072 // Then print the decl itself.
3073 const ValueDecl *VD = DR->getDecl();
3074 OS << VD->getName();
3075 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3076 // This is a template variable, print the expanded template arguments.
3077 printTemplateArgumentList(OS, IV->getTemplateArgs().asArray(), Policy);
3078 }
3079 return true;
Clement Courbet9d432e02018-12-04 07:59:57 +00003080 }
Clement Courbetf44c6f42018-12-11 08:39:11 +00003081 return false;
Clement Courbet9d432e02018-12-04 07:59:57 +00003082 }
Clement Courbetf44c6f42018-12-11 08:39:11 +00003083
3084private:
3085 const PrintingPolicy Policy;
3086};
3087
3088} // end anonymous namespace
Clement Courbet9d432e02018-12-04 07:59:57 +00003089
Douglas Gregor672281a2017-09-14 23:38:42 +00003090std::pair<Expr *, std::string>
Clement Courbetf44c6f42018-12-11 08:39:11 +00003091Sema::findFailedBooleanCondition(Expr *Cond) {
Douglas Gregor672281a2017-09-14 23:38:42 +00003092 Cond = lookThroughRangesV3Condition(PP, Cond);
Douglas Gregorbb33f572017-07-05 20:20:15 +00003093
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003094 // Separate out all of the terms in a conjunction.
3095 SmallVector<Expr *, 4> Terms;
3096 collectConjunctionTerms(Cond, Terms);
3097
3098 // Determine which term failed.
3099 Expr *FailedCond = nullptr;
3100 for (Expr *Term : Terms) {
Douglas Gregor672281a2017-09-14 23:38:42 +00003101 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3102
Clement Courbetd8720412018-12-10 08:53:17 +00003103 // Literals are uninteresting.
3104 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3105 isa<IntegerLiteral>(TermAsWritten))
3106 continue;
3107
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003108 // The initialization of the parameter from the argument is
3109 // a constant-evaluated context.
3110 EnterExpressionEvaluationContext ConstantEvaluated(
Douglas Gregor672281a2017-09-14 23:38:42 +00003111 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003112
3113 bool Succeeded;
Douglas Gregor672281a2017-09-14 23:38:42 +00003114 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003115 !Succeeded) {
Douglas Gregor672281a2017-09-14 23:38:42 +00003116 FailedCond = TermAsWritten;
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003117 break;
3118 }
3119 }
Clement Courbetf44c6f42018-12-11 08:39:11 +00003120 if (!FailedCond)
Clement Courbetd8720412018-12-10 08:53:17 +00003121 FailedCond = Cond->IgnoreParenImpCasts();
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003122
3123 std::string Description;
3124 {
3125 llvm::raw_string_ostream Out(Description);
Clement Courbetfb2c74d2018-12-20 09:05:15 +00003126 PrintingPolicy Policy = getPrintingPolicy();
3127 Policy.PrintCanonicalTypes = true;
3128 FailedBooleanConditionPrinterHelper Helper(Policy);
3129 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003130 }
3131 return { FailedCond, Description };
3132}
3133
Douglas Gregordc572a32009-03-30 22:58:21 +00003134QualType Sema::CheckTemplateIdType(TemplateName Name,
3135 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003136 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00003137 DependentTemplateName *DTN
3138 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00003139 if (DTN && DTN->isIdentifier())
3140 // When building a template-id where the template-name is dependent,
3141 // assume the template is a type template. Either our assumption is
3142 // correct, or the code is ill-formed and will be diagnosed when the
3143 // dependent name is substituted.
3144 return Context.getDependentTemplateSpecializationType(ETK_None,
3145 DTN->getQualifier(),
3146 DTN->getIdentifier(),
3147 TemplateArgs);
3148
Douglas Gregordc572a32009-03-30 22:58:21 +00003149 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00003150 if (!Template || isa<FunctionTemplateDecl>(Template) ||
Faisal Valia534f072018-04-26 00:42:40 +00003151 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00003152 // We might have a substituted template template parameter pack. If so,
3153 // build a template specialization type for it.
3154 if (Name.getAsSubstTemplateTemplateParmPack())
3155 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003156
Douglas Gregor8b6070b2011-03-04 21:37:14 +00003157 Diag(TemplateLoc, diag::err_template_id_not_a_type)
3158 << Name;
3159 NoteAllFoundTemplates(Name);
3160 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00003161 }
Douglas Gregordc572a32009-03-30 22:58:21 +00003162
Douglas Gregorc40290e2009-03-09 23:48:35 +00003163 // Check that the template argument list is well-formed for this
3164 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003165 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00003166 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00003167 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00003168 return QualType();
3169
Douglas Gregorc40290e2009-03-09 23:48:35 +00003170 QualType CanonType;
3171
Douglas Gregor678d76c2011-07-01 01:22:09 +00003172 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00003173 if (TypeAliasTemplateDecl *AliasTemplate =
3174 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00003175 // Find the canonical type for this type alias template specialization.
3176 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3177 if (Pattern->isInvalidDecl())
3178 return QualType();
3179
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003180 TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack,
3181 Converted);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003182
3183 // Only substitute for the innermost template argument list.
3184 MultiLevelTemplateArgumentList TemplateArgLists;
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003185 TemplateArgLists.addOuterTemplateArguments(&StackTemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00003186 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
3187 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00003188 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003189
Richard Smith802c4b72012-08-23 06:16:52 +00003190 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003191 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003192 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003193 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00003194
Richard Smith3f1b5d02011-05-05 21:57:07 +00003195 CanonType = SubstType(Pattern->getUnderlyingType(),
3196 TemplateArgLists, AliasTemplate->getLocation(),
3197 AliasTemplate->getDeclName());
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003198 if (CanonType.isNull()) {
3199 // If this was enable_if and we failed to find the nested type
3200 // within enable_if in a SFINAE context, dig out the specific
3201 // enable_if condition that failed and present that instead.
3202 if (isEnableIfAliasTemplate(AliasTemplate)) {
3203 if (auto DeductionInfo = isSFINAEContext()) {
3204 if (*DeductionInfo &&
3205 (*DeductionInfo)->hasSFINAEDiagnostic() &&
3206 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3207 diag::err_typename_nested_not_found_enable_if &&
3208 TemplateArgs[0].getArgument().getKind()
3209 == TemplateArgument::Expression) {
3210 Expr *FailedCond;
3211 std::string FailedDescription;
3212 std::tie(FailedCond, FailedDescription) =
Clement Courbetf44c6f42018-12-11 08:39:11 +00003213 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003214
3215 // Remove the old SFINAE diagnostic.
3216 PartialDiagnosticAt OldDiag =
3217 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3218 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3219
3220 // Add a new SFINAE diagnostic specifying which condition
3221 // failed.
3222 (*DeductionInfo)->addSFINAEDiagnostic(
3223 OldDiag.first,
3224 PDiag(diag::err_typename_nested_not_found_requirement)
3225 << FailedDescription
3226 << FailedCond->getSourceRange());
3227 }
3228 }
3229 }
3230
Richard Smith3f1b5d02011-05-05 21:57:07 +00003231 return QualType();
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003232 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00003233 } else if (Name.isDependent() ||
3234 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00003235 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00003236 // This class template specialization is a dependent
3237 // type. Therefore, its canonical type is another class template
3238 // specialization type that contains all of the converted
3239 // arguments in canonical form. This ensures that, e.g., A<T> and
3240 // A<T, T> have identical types when A is declared as:
3241 //
3242 // template<typename T, typename U = T> struct A;
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00003243 CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
John McCall2408e322010-04-27 00:57:59 +00003244
3245 // This might work out to be a current instantiation, in which
3246 // case the canonical type needs to be the InjectedClassNameType.
3247 //
3248 // TODO: in theory this could be a simple hashtable lookup; most
3249 // changes to CurContext don't change the set of current
3250 // instantiations.
3251 if (isa<ClassTemplateDecl>(Template)) {
3252 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3253 // If we get out to a namespace, we're done.
3254 if (Ctx->isFileContext()) break;
3255
3256 // If this isn't a record, keep looking.
3257 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3258 if (!Record) continue;
3259
3260 // Look for one of the two cases with InjectedClassNameTypes
3261 // and check whether it's the same template.
3262 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3263 !Record->getDescribedClassTemplate())
3264 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003265
John McCall2408e322010-04-27 00:57:59 +00003266 // Fetch the injected class name type and check whether its
3267 // injected type is equal to the type we just built.
3268 QualType ICNT = Context.getTypeDeclType(Record);
3269 QualType Injected = cast<InjectedClassNameType>(ICNT)
3270 ->getInjectedSpecializationType();
3271
3272 if (CanonType != Injected->getCanonicalTypeInternal())
3273 continue;
3274
3275 // If so, the canonical type of this TST is the injected
3276 // class name type of the record we just found.
3277 assert(ICNT.isCanonical());
3278 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00003279 break;
3280 }
3281 }
Mike Stump11289f42009-09-09 15:08:12 +00003282 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00003283 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00003284 // Find the class template specialization declaration that
3285 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00003286 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00003287 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00003288 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003289 if (!Decl) {
3290 // This is the first time we have referenced this class template
3291 // specialization. Create the canonical declaration and add it to
3292 // the set of specializations.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003293 Decl = ClassTemplateSpecializationDecl::Create(
3294 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3295 ClassTemplate->getDeclContext(),
3296 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3297 ClassTemplate->getLocation(), ClassTemplate, Converted, nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003298 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00003299 if (ClassTemplate->isOutOfLine())
3300 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00003301 }
3302
Erich Keanea32910d2017-03-23 18:51:54 +00003303 if (Decl->getSpecializationKind() == TSK_Undeclared) {
3304 MultiLevelTemplateArgumentList TemplateArgLists;
3305 TemplateArgLists.addOuterTemplateArguments(Converted);
3306 InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(),
3307 Decl);
3308 }
3309
Chandler Carruth2acfb222013-09-27 22:14:40 +00003310 // Diagnose uses of this specialization.
3311 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3312
Douglas Gregorc40290e2009-03-09 23:48:35 +00003313 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00003314 assert(isa<RecordType>(CanonType) &&
3315 "type of non-dependent specialization is not a RecordType");
David Majnemerd9b1a4f2015-11-04 03:40:30 +00003316 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3317 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
3318 TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003319 }
Mike Stump11289f42009-09-09 15:08:12 +00003320
Douglas Gregorc40290e2009-03-09 23:48:35 +00003321 // Build the fully-sugared type for this class template
3322 // specialization, which refers back to the class template
3323 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00003324 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003325}
3326
John McCallfaf5fb42010-08-26 23:41:50 +00003327TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003328Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Richard Smith74f02342017-01-19 21:00:13 +00003329 TemplateTy TemplateD, IdentifierInfo *TemplateII,
3330 SourceLocation TemplateIILoc,
Mike Stump11289f42009-09-09 15:08:12 +00003331 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00003332 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnara4244b432012-01-27 08:46:19 +00003333 SourceLocation RAngleLoc,
Richard Smith62559bd2017-02-01 21:36:38 +00003334 bool IsCtorOrDtorName, bool IsClassName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00003335 if (SS.isInvalid())
3336 return true;
3337
Richard Smith62559bd2017-02-01 21:36:38 +00003338 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3339 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3340
3341 // C++ [temp.res]p3:
3342 // A qualified-id that refers to a type and in which the
3343 // nested-name-specifier depends on a template-parameter (14.6.2)
3344 // shall be prefixed by the keyword typename to indicate that the
3345 // qualified-id denotes a type, forming an
3346 // elaborated-type-specifier (7.1.5.3).
3347 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
Richard Smith3411fbf2017-02-01 21:41:18 +00003348 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
Richard Smith62559bd2017-02-01 21:36:38 +00003349 << SS.getScopeRep() << TemplateII->getName();
3350 // Recover as if 'typename' were specified.
3351 // FIXME: This is not quite correct recovery as we don't transform SS
3352 // into the corresponding dependent form (and we don't diagnose missing
3353 // 'template' keywords within SS as a result).
3354 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3355 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3356 TemplateArgsIn, RAngleLoc);
3357 }
3358
3359 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3360 // it's not actually allowed to be used as a type in most cases. Because
3361 // we annotate it before we know whether it's valid, we have to check for
3362 // this case here.
3363 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
Richard Smith74f02342017-01-19 21:00:13 +00003364 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3365 Diag(TemplateIILoc,
3366 TemplateKWLoc.isInvalid()
3367 ? diag::err_out_of_line_qualified_id_type_names_constructor
3368 : diag::ext_out_of_line_qualified_id_type_names_constructor)
3369 << TemplateII << 0 /*injected-class-name used as template name*/
3370 << 1 /*if any keyword was present, it was 'template'*/;
3371 }
3372 }
3373
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003374 TemplateName Template = TemplateD.get();
Douglas Gregor8bf42052009-02-09 18:46:07 +00003375
Douglas Gregorc40290e2009-03-09 23:48:35 +00003376 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003377 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003378 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00003379
Douglas Gregor5a064722011-02-28 17:23:35 +00003380 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00003381 QualType T
3382 = Context.getDependentTemplateSpecializationType(ETK_None,
3383 DTN->getQualifier(),
3384 DTN->getIdentifier(),
3385 TemplateArgs);
3386 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00003387 TypeLocBuilder TLB;
3388 DependentTemplateSpecializationTypeLoc SpecTL
3389 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003390 SpecTL.setElaboratedKeywordLoc(SourceLocation());
3391 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00003392 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00003393 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00003394 SpecTL.setLAngleLoc(LAngleLoc);
3395 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00003396 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3397 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3398 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3399 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003400
Richard Smith74f02342017-01-19 21:00:13 +00003401 QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003402 if (Result.isNull())
3403 return true;
3404
Douglas Gregore7c20652011-03-02 00:47:37 +00003405 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003406 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00003407 TemplateSpecializationTypeLoc SpecTL
3408 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003409 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00003410 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003411 SpecTL.setLAngleLoc(LAngleLoc);
3412 SpecTL.setRAngleLoc(RAngleLoc);
3413 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3414 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00003415
Abramo Bagnara4244b432012-01-27 08:46:19 +00003416 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
3417 // constructor or destructor name (in such a case, the scope specifier
3418 // will be attached to the enclosing Decl or Expr node).
3419 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00003420 // Create an elaborated-type-specifier containing the nested-name-specifier.
3421 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
3422 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00003423 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00003424 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3425 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003426
Douglas Gregore7c20652011-03-02 00:47:37 +00003427 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00003428}
John McCall06f6fe8d2009-09-04 01:14:41 +00003429
Douglas Gregore7c20652011-03-02 00:47:37 +00003430TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00003431 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00003432 SourceLocation TagLoc,
3433 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003434 SourceLocation TemplateKWLoc,
3435 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00003436 SourceLocation TemplateLoc,
3437 SourceLocation LAngleLoc,
3438 ASTTemplateArgsPtr TemplateArgsIn,
3439 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003440 TemplateName Template = TemplateD.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00003441
Douglas Gregore7c20652011-03-02 00:47:37 +00003442 // Translate the parser's template argument list in our AST format.
3443 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3444 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003445
Douglas Gregore7c20652011-03-02 00:47:37 +00003446 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00003447 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00003448 ElaboratedTypeKeyword Keyword
3449 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00003450
Douglas Gregore7c20652011-03-02 00:47:37 +00003451 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3452 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
Simon Pilgrim6905d222016-12-30 22:55:33 +00003453 DTN->getQualifier(),
3454 DTN->getIdentifier(),
Douglas Gregore7c20652011-03-02 00:47:37 +00003455 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003456
3457 // Build type-source information.
Douglas Gregore7c20652011-03-02 00:47:37 +00003458 TypeLocBuilder TLB;
3459 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003460 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3461 SpecTL.setElaboratedKeywordLoc(TagLoc);
3462 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00003463 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003464 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003465 SpecTL.setLAngleLoc(LAngleLoc);
3466 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003467 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3468 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3469 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3470 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00003471
3472 if (TypeAliasTemplateDecl *TAT =
3473 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3474 // C++0x [dcl.type.elab]p2:
3475 // If the identifier resolves to a typedef-name or the simple-template-id
3476 // resolves to an alias template specialization, the
3477 // elaborated-type-specifier is ill-formed.
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00003478 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3479 << TAT << NTK_TypeAliasTemplate << TagKind;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003480 Diag(TAT->getLocation(), diag::note_declared_at);
3481 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003482
Douglas Gregore7c20652011-03-02 00:47:37 +00003483 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3484 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00003485 return TypeResult(true);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003486
Douglas Gregore7c20652011-03-02 00:47:37 +00003487 // Check the tag kind
3488 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00003489 RecordDecl *D = RT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00003490
John McCalld8fe9af2009-09-08 17:47:29 +00003491 IdentifierInfo *Id = D->getIdentifier();
3492 assert(Id && "templated class must have an identifier");
Simon Pilgrim6905d222016-12-30 22:55:33 +00003493
Richard Trieucaa33d32011-06-10 03:11:26 +00003494 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00003495 TagLoc, Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00003496 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00003497 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00003498 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00003499 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00003500 }
3501 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003502
Douglas Gregore7c20652011-03-02 00:47:37 +00003503 // Provide source-location information for the template specialization.
3504 TypeLocBuilder TLB;
3505 TemplateSpecializationTypeLoc SpecTL
3506 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003507 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003508 SpecTL.setTemplateNameLoc(TemplateLoc);
3509 SpecTL.setLAngleLoc(LAngleLoc);
3510 SpecTL.setRAngleLoc(RAngleLoc);
3511 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3512 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00003513
Douglas Gregore7c20652011-03-02 00:47:37 +00003514 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003515 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00003516 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3517 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00003518 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003519 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3520 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003521}
3522
Larisse Voufo39a1e502013-08-06 01:03:05 +00003523static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3524 NamedDecl *PrevDecl,
3525 SourceLocation Loc,
3526 bool IsPartialSpecialization);
3527
3528static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003529
Richard Smith300e0c32013-09-24 04:49:23 +00003530static bool isTemplateArgumentTemplateParameter(
3531 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3532 switch (Arg.getKind()) {
3533 case TemplateArgument::Null:
3534 case TemplateArgument::NullPtr:
3535 case TemplateArgument::Integral:
3536 case TemplateArgument::Declaration:
3537 case TemplateArgument::Pack:
3538 case TemplateArgument::TemplateExpansion:
3539 return false;
3540
3541 case TemplateArgument::Type: {
3542 QualType Type = Arg.getAsType();
3543 const TemplateTypeParmType *TPT =
3544 Arg.getAsType()->getAs<TemplateTypeParmType>();
3545 return TPT && !Type.hasQualifiers() &&
3546 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3547 }
3548
3549 case TemplateArgument::Expression: {
3550 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3551 if (!DRE || !DRE->getDecl())
3552 return false;
3553 const NonTypeTemplateParmDecl *NTTP =
3554 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3555 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3556 }
3557
3558 case TemplateArgument::Template:
3559 const TemplateTemplateParmDecl *TTP =
3560 dyn_cast_or_null<TemplateTemplateParmDecl>(
3561 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
3562 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3563 }
3564 llvm_unreachable("unexpected kind of template argument");
3565}
3566
3567static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
3568 ArrayRef<TemplateArgument> Args) {
3569 if (Params->size() != Args.size())
3570 return false;
3571
3572 unsigned Depth = Params->getDepth();
3573
3574 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3575 TemplateArgument Arg = Args[I];
3576
3577 // If the parameter is a pack expansion, the argument must be a pack
3578 // whose only element is a pack expansion.
3579 if (Params->getParam(I)->isParameterPack()) {
3580 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3581 !Arg.pack_begin()->isPackExpansion())
3582 return false;
3583 Arg = Arg.pack_begin()->getPackExpansionPattern();
3584 }
3585
3586 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3587 return false;
3588 }
3589
3590 return true;
3591}
3592
Richard Smith4b55a9c2014-04-17 03:29:33 +00003593/// Convert the parser's template argument list representation into our form.
3594static TemplateArgumentListInfo
3595makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
3596 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
3597 TemplateId.RAngleLoc);
3598 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
3599 TemplateId.NumArgs);
3600 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
3601 return TemplateArgs;
3602}
3603
Richard Smith0e617ec2016-12-27 07:56:27 +00003604template<typename PartialSpecDecl>
3605static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3606 if (Partial->getDeclContext()->isDependentContext())
3607 return;
3608
3609 // FIXME: Get the TDK from deduction in order to provide better diagnostics
3610 // for non-substitution-failure issues?
3611 TemplateDeductionInfo Info(Partial->getLocation());
3612 if (S.isMoreSpecializedThanPrimary(Partial, Info))
3613 return;
3614
3615 auto *Template = Partial->getSpecializedTemplate();
3616 S.Diag(Partial->getLocation(),
Richard Smithfa4a09d2016-12-27 20:03:09 +00003617 diag::ext_partial_spec_not_more_specialized_than_primary)
3618 << isa<VarTemplateDecl>(Template);
Richard Smith0e617ec2016-12-27 07:56:27 +00003619
3620 if (Info.hasSFINAEDiagnostic()) {
3621 PartialDiagnosticAt Diag = {SourceLocation(),
3622 PartialDiagnostic::NullDiagnostic()};
3623 Info.takeSFINAEDiagnostic(Diag);
3624 SmallString<128> SFINAEArgString;
3625 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3626 S.Diag(Diag.first,
3627 diag::note_partial_spec_not_more_specialized_than_primary)
3628 << SFINAEArgString;
3629 }
3630
3631 S.Diag(Template->getLocation(), diag::note_template_decl_here);
3632}
3633
Richard Smith4e05eaa2017-02-16 00:36:47 +00003634static void
3635noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
3636 const llvm::SmallBitVector &DeducibleParams) {
3637 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3638 if (!DeducibleParams[I]) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00003639 NamedDecl *Param = TemplateParams->getParam(I);
Richard Smith4e05eaa2017-02-16 00:36:47 +00003640 if (Param->getDeclName())
3641 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3642 << Param->getDeclName();
3643 else
3644 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3645 << "(anonymous)";
3646 }
3647 }
3648}
3649
3650
Richard Smith57aae072016-12-28 02:37:25 +00003651template<typename PartialSpecDecl>
3652static void checkTemplatePartialSpecialization(Sema &S,
3653 PartialSpecDecl *Partial) {
3654 // C++1z [temp.class.spec]p8: (DR1495)
3655 // - The specialization shall be more specialized than the primary
3656 // template (14.5.5.2).
3657 checkMoreSpecializedThanPrimary(S, Partial);
3658
3659 // C++ [temp.class.spec]p8: (DR1315)
3660 // - Each template-parameter shall appear at least once in the
3661 // template-id outside a non-deduced context.
3662 // C++1z [temp.class.spec.match]p3 (P0127R2)
3663 // If the template arguments of a partial specialization cannot be
3664 // deduced because of the structure of its template-parameter-list
3665 // and the template-id, the program is ill-formed.
3666 auto *TemplateParams = Partial->getTemplateParameters();
3667 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3668 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3669 TemplateParams->getDepth(), DeducibleParams);
3670
3671 if (!DeducibleParams.all()) {
3672 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3673 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3674 << isa<VarTemplatePartialSpecializationDecl>(Partial)
3675 << (NumNonDeducible > 1)
3676 << SourceRange(Partial->getLocation(),
3677 Partial->getTemplateArgsAsWritten()->RAngleLoc);
Richard Smith4e05eaa2017-02-16 00:36:47 +00003678 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
Richard Smith57aae072016-12-28 02:37:25 +00003679 }
3680}
3681
3682void Sema::CheckTemplatePartialSpecialization(
3683 ClassTemplatePartialSpecializationDecl *Partial) {
3684 checkTemplatePartialSpecialization(*this, Partial);
3685}
3686
3687void Sema::CheckTemplatePartialSpecialization(
3688 VarTemplatePartialSpecializationDecl *Partial) {
3689 checkTemplatePartialSpecialization(*this, Partial);
3690}
3691
Richard Smith4e05eaa2017-02-16 00:36:47 +00003692void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
3693 // C++1z [temp.param]p11:
3694 // A template parameter of a deduction guide template that does not have a
3695 // default-argument shall be deducible from the parameter-type-list of the
3696 // deduction guide template.
3697 auto *TemplateParams = TD->getTemplateParameters();
3698 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3699 MarkDeducedTemplateParameters(TD, DeducibleParams);
3700 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3701 // A parameter pack is deducible (to an empty pack).
3702 auto *Param = TemplateParams->getParam(I);
3703 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3704 DeducibleParams[I] = true;
3705 }
3706
3707 if (!DeducibleParams.all()) {
3708 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3709 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3710 << (NumNonDeducible > 1);
3711 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3712 }
3713}
3714
Larisse Voufo39a1e502013-08-06 01:03:05 +00003715DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00003716 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00003717 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00003718 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003719 // D must be variable template id.
Faisal Vali2ab8c152017-12-30 04:15:27 +00003720 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00003721 "Variable template specialization is declared with a template it.");
3722
3723 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00003724 TemplateArgumentListInfo TemplateArgs =
3725 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003726 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3727 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3728 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00003729
Richard Smithbeef3452014-01-16 23:39:20 +00003730 TemplateName Name = TemplateId->Template.get();
3731
3732 // The template-id must name a variable template.
3733 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00003734 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3735 if (!VarTemplate) {
3736 NamedDecl *FnTemplate;
3737 if (auto *OTS = Name.getAsOverloadedTemplate())
3738 FnTemplate = *OTS->begin();
3739 else
3740 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3741 if (FnTemplate)
3742 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3743 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00003744 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3745 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00003746 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003747
3748 // Check for unexpanded parameter packs in any of the template arguments.
3749 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3750 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3751 UPPC_PartialSpecialization))
3752 return true;
3753
3754 // Check that the template argument list is well-formed for this
3755 // template.
3756 SmallVector<TemplateArgument, 4> Converted;
3757 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
3758 false, Converted))
3759 return true;
3760
Larisse Voufo39a1e502013-08-06 01:03:05 +00003761 // Find the variable template (partial) specialization declaration that
3762 // corresponds to these arguments.
3763 if (IsPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00003764 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
3765 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00003766 return true;
3767
Richard Smith57aae072016-12-28 02:37:25 +00003768 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
3769 // also do them during instantiation.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003770 bool InstantiationDependent;
3771 if (!Name.isDependent() &&
3772 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00003773 TemplateArgs.arguments(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00003774 InstantiationDependent)) {
3775 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3776 << VarTemplate->getDeclName();
3777 IsPartialSpecialization = false;
3778 }
Richard Smith300e0c32013-09-24 04:49:23 +00003779
3780 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
3781 Converted)) {
3782 // C++ [temp.class.spec]p9b3:
3783 //
3784 // -- The argument list of the specialization shall not be identical
3785 // to the implicit argument list of the primary template.
3786 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3787 << /*variable template*/ 1
3788 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
3789 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
3790 // FIXME: Recover from this by treating the declaration as a redeclaration
3791 // of the primary template.
3792 return true;
3793 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003794 }
3795
Craig Topperc3ec1492014-05-26 06:22:03 +00003796 void *InsertPos = nullptr;
3797 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003798
3799 if (IsPartialSpecialization)
3800 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00003801 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003802 else
Craig Topper7e0daca2014-06-26 04:58:53 +00003803 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003804
Craig Topperc3ec1492014-05-26 06:22:03 +00003805 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003806
3807 // Check whether we can declare a variable template specialization in
3808 // the current scope.
3809 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
3810 TemplateNameLoc,
3811 IsPartialSpecialization))
3812 return true;
3813
3814 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3815 // Since the only prior variable template specialization with these
3816 // arguments was referenced but not declared, reuse that
3817 // declaration node as our own, updating its source location and
3818 // the list of outer template parameters to reflect our new declaration.
3819 Specialization = PrevDecl;
3820 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00003821 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003822 } else if (IsPartialSpecialization) {
3823 // Create a new class template partial specialization declaration node.
3824 VarTemplatePartialSpecializationDecl *PrevPartial =
3825 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003826 VarTemplatePartialSpecializationDecl *Partial =
3827 VarTemplatePartialSpecializationDecl::Create(
3828 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
3829 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
David Majnemer8b622692016-07-03 21:17:51 +00003830 Converted, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003831
3832 if (!PrevPartial)
3833 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
3834 Specialization = Partial;
3835
3836 // If we are providing an explicit specialization of a member variable
3837 // template specialization, make a note of that.
3838 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00003839 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00003840
Richard Smith57aae072016-12-28 02:37:25 +00003841 CheckTemplatePartialSpecialization(Partial);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003842 } else {
3843 // Create a new class template specialization declaration node for
3844 // this explicit specialization or friend declaration.
3845 Specialization = VarTemplateSpecializationDecl::Create(
3846 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
David Majnemer8b622692016-07-03 21:17:51 +00003847 VarTemplate, DI->getType(), DI, SC, Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003848 Specialization->setTemplateArgsInfo(TemplateArgs);
3849
3850 if (!PrevDecl)
3851 VarTemplate->AddSpecialization(Specialization, InsertPos);
3852 }
3853
3854 // C++ [temp.expl.spec]p6:
3855 // If a template, a member template or the member of a class template is
3856 // explicitly specialized then that specialization shall be declared
3857 // before the first use of that specialization that would cause an implicit
3858 // instantiation to take place, in every translation unit in which such a
3859 // use occurs; no diagnostic is required.
3860 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3861 bool Okay = false;
3862 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
3863 // Is there any previous explicit specialization declaration?
3864 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3865 Okay = true;
3866 break;
3867 }
3868 }
3869
3870 if (!Okay) {
3871 SourceRange Range(TemplateNameLoc, RAngleLoc);
3872 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3873 << Name << Range;
3874
3875 Diag(PrevDecl->getPointOfInstantiation(),
3876 diag::note_instantiation_required_here)
3877 << (PrevDecl->getTemplateSpecializationKind() !=
3878 TSK_ImplicitInstantiation);
3879 return true;
3880 }
3881 }
3882
3883 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
3884 Specialization->setLexicalDeclContext(CurContext);
3885
3886 // Add the specialization into its lexical context, so that it can
3887 // be seen when iterating through the list of declarations in that
3888 // context. However, specializations are not found by name lookup.
3889 CurContext->addDecl(Specialization);
3890
3891 // Note that this is an explicit specialization.
3892 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
3893
3894 if (PrevDecl) {
3895 // Check that this isn't a redefinition of this specialization,
3896 // merging with previous declarations.
3897 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00003898 forRedeclarationInCurContext());
Larisse Voufo39a1e502013-08-06 01:03:05 +00003899 PrevSpec.addDecl(PrevDecl);
3900 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00003901 } else if (Specialization->isStaticDataMember() &&
3902 Specialization->isOutOfLine()) {
3903 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00003904 }
3905
3906 // Link instantiations of static data members back to the template from
3907 // which they were instantiated.
3908 if (Specialization->isStaticDataMember())
3909 Specialization->setInstantiationOfStaticDataMember(
3910 VarTemplate->getTemplatedDecl(),
3911 Specialization->getSpecializationKind());
3912
3913 return Specialization;
3914}
3915
3916namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003917/// A partial specialization whose template arguments have matched
Larisse Voufo39a1e502013-08-06 01:03:05 +00003918/// a given template-id.
3919struct PartialSpecMatchResult {
3920 VarTemplatePartialSpecializationDecl *Partial;
3921 TemplateArgumentList *Args;
3922};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003923} // end anonymous namespace
Larisse Voufo39a1e502013-08-06 01:03:05 +00003924
3925DeclResult
3926Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
3927 SourceLocation TemplateNameLoc,
3928 const TemplateArgumentListInfo &TemplateArgs) {
3929 assert(Template && "A variable template id without template?");
3930
3931 // Check that the template argument list is well-formed for this template.
3932 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003933 if (CheckTemplateArgumentList(
3934 Template, TemplateNameLoc,
3935 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00003936 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00003937 return true;
3938
3939 // Find the variable template specialization declaration that
3940 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00003941 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003942 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Richard Smith6739a102016-05-05 00:56:12 +00003943 Converted, InsertPos)) {
3944 checkSpecializationVisibility(TemplateNameLoc, Spec);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003945 // If we already have a variable template specialization, return it.
3946 return Spec;
Richard Smith6739a102016-05-05 00:56:12 +00003947 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003948
3949 // This is the first time we have referenced this variable template
3950 // specialization. Create the canonical declaration and add it to
3951 // the set of specializations, based on the closest partial specialization
3952 // that it represents. That is,
3953 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
3954 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00003955 Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003956 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
3957 bool AmbiguousPartialSpec = false;
3958 typedef PartialSpecMatchResult MatchResult;
3959 SmallVector<MatchResult, 4> Matched;
3960 SourceLocation PointOfInstantiation = TemplateNameLoc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003961 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
3962 /*ForTakingAddress=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003963
3964 // 1. Attempt to find the closest partial specialization that this
3965 // specializes, if any.
3966 // If any of the template arguments is dependent, then this is probably
3967 // a placeholder for an incomplete declarative context; which must be
3968 // complete by instantiation time. Thus, do not search through the partial
3969 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00003970 // TODO: Unify with InstantiateClassTemplateSpecialization()?
3971 // Perhaps better after unification of DeduceTemplateArguments() and
3972 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00003973 bool InstantiationDependent = false;
3974 if (!TemplateSpecializationType::anyDependentTemplateArguments(
3975 TemplateArgs, InstantiationDependent)) {
3976
3977 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3978 Template->getPartialSpecializations(PartialSpecs);
3979
3980 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3981 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3982 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3983
3984 if (TemplateDeductionResult Result =
3985 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
3986 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00003987 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00003988 FailedCandidates.addCandidate().set(
3989 DeclAccessPair::make(Template, AS_public), Partial,
3990 MakeDeductionFailureInfo(Context, Result, Info));
Larisse Voufo39a1e502013-08-06 01:03:05 +00003991 (void)Result;
3992 } else {
3993 Matched.push_back(PartialSpecMatchResult());
3994 Matched.back().Partial = Partial;
3995 Matched.back().Args = Info.take();
3996 }
3997 }
3998
Larisse Voufo39a1e502013-08-06 01:03:05 +00003999 if (Matched.size() >= 1) {
4000 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4001 if (Matched.size() == 1) {
4002 // -- If exactly one matching specialization is found, the
4003 // instantiation is generated from that specialization.
4004 // We don't need to do anything for this.
4005 } else {
4006 // -- If more than one matching specialization is found, the
4007 // partial order rules (14.5.4.2) are used to determine
4008 // whether one of the specializations is more specialized
4009 // than the others. If none of the specializations is more
4010 // specialized than all of the other matching
4011 // specializations, then the use of the variable template is
4012 // ambiguous and the program is ill-formed.
4013 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4014 PEnd = Matched.end();
4015 P != PEnd; ++P) {
4016 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4017 PointOfInstantiation) ==
4018 P->Partial)
4019 Best = P;
4020 }
4021
4022 // Determine if the best partial specialization is more specialized than
4023 // the others.
4024 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4025 PEnd = Matched.end();
4026 P != PEnd; ++P) {
4027 if (P != Best && getMoreSpecializedPartialSpecialization(
4028 P->Partial, Best->Partial,
4029 PointOfInstantiation) != Best->Partial) {
4030 AmbiguousPartialSpec = true;
4031 break;
4032 }
4033 }
4034 }
4035
4036 // Instantiate using the best variable template partial specialization.
4037 InstantiationPattern = Best->Partial;
4038 InstantiationArgs = Best->Args;
4039 } else {
4040 // -- If no match is found, the instantiation is generated
4041 // from the primary template.
4042 // InstantiationPattern = Template->getTemplatedDecl();
4043 }
4044 }
4045
Larisse Voufo39a1e502013-08-06 01:03:05 +00004046 // 2. Create the canonical declaration.
Richard Smith6739a102016-05-05 00:56:12 +00004047 // Note that we do not instantiate a definition until we see an odr-use
4048 // in DoMarkVarDeclReferenced().
Larisse Voufo39a1e502013-08-06 01:03:05 +00004049 // FIXME: LateAttrs et al.?
4050 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4051 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
4052 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
4053 if (!Decl)
4054 return true;
4055
4056 if (AmbiguousPartialSpec) {
4057 // Partial ordering did not produce a clear winner. Complain.
4058 Decl->setInvalidDecl();
4059 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4060 << Decl;
4061
4062 // Print the matching partial specializations.
Yaron Keren1cb81462016-11-16 13:45:34 +00004063 for (MatchResult P : Matched)
4064 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4065 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4066 *P.Args);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004067 return true;
4068 }
4069
4070 if (VarTemplatePartialSpecializationDecl *D =
4071 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4072 Decl->setInstantiationOf(D, InstantiationArgs);
4073
Richard Smith6739a102016-05-05 00:56:12 +00004074 checkSpecializationVisibility(TemplateNameLoc, Decl);
4075
Larisse Voufo39a1e502013-08-06 01:03:05 +00004076 assert(Decl && "No variable template specialization?");
4077 return Decl;
4078}
4079
4080ExprResult
4081Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
4082 const DeclarationNameInfo &NameInfo,
4083 VarTemplateDecl *Template, SourceLocation TemplateLoc,
4084 const TemplateArgumentListInfo *TemplateArgs) {
4085
4086 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4087 *TemplateArgs);
4088 if (Decl.isInvalid())
4089 return ExprError();
4090
4091 VarDecl *Var = cast<VarDecl>(Decl.get());
4092 if (!Var->getTemplateSpecializationKind())
4093 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
4094 NameInfo.getLoc());
4095
4096 // Build an ordinary singleton decl ref.
4097 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00004098 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004099}
4100
Richard Smithecad88d2018-04-26 01:08:00 +00004101void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4102 SourceLocation Loc) {
4103 Diag(Loc, diag::err_template_missing_args)
4104 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4105 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4106 Diag(TD->getLocation(), diag::note_template_decl_here)
4107 << TD->getTemplateParameters()->getSourceRange();
4108 }
4109}
4110
John McCalldadc5752010-08-24 06:29:42 +00004111ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004112 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00004113 LookupResult &R,
4114 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00004115 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00004116 // FIXME: Can we do any checking at this point? I guess we could check the
4117 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00004118 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00004119 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00004120 // foo<int> could identify a single function unambiguously
4121 // This approach does NOT work, since f<int>(1);
4122 // gets resolved prior to resorting to overload resolution
4123 // i.e., template<class T> void f(double);
4124 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00004125
4126 // These should be filtered out by our callers.
4127 assert(!R.empty() && "empty lookup results when building templateid");
4128 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4129
Richard Smith04100942018-04-26 02:10:22 +00004130 // Non-function templates require a template argument list.
4131 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4132 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4133 diagnoseMissingTemplateArguments(TemplateName(TD), R.getNameLoc());
4134 return ExprError();
4135 }
4136 }
4137
Richard Smith0bf96f92018-04-25 22:58:55 +00004138 auto AnyDependentArguments = [&]() -> bool {
4139 bool InstantiationDependent;
4140 return TemplateArgs &&
4141 TemplateSpecializationType::anyDependentTemplateArguments(
4142 *TemplateArgs, InstantiationDependent);
4143 };
4144
Larisse Voufo39a1e502013-08-06 01:03:05 +00004145 // In C++1y, check variable template ids.
Richard Smith0bf96f92018-04-25 22:58:55 +00004146 if (R.getAsSingle<VarTemplateDecl>() && !AnyDependentArguments()) {
Richard Smithd7d11ef2014-02-03 20:09:56 +00004147 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
4148 R.getAsSingle<VarTemplateDecl>(),
4149 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004150 }
4151
John McCall58cc69d2010-01-27 01:50:18 +00004152 // We don't want lookup warnings at this point.
4153 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004154
John McCalle66edc12009-11-24 19:00:30 +00004155 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00004156 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00004157 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00004158 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004159 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004160 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00004161 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00004162
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004163 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00004164}
4165
John McCalle66edc12009-11-24 19:00:30 +00004166// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00004167ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004168Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004169 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004170 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00004171 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004172
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00004173 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00004174 DeclContext *DC;
4175 if (!(DC = computeDeclContext(SS, false)) ||
4176 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00004177 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00004178 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004179
Douglas Gregor786123d2010-05-21 23:18:07 +00004180 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004181 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Richard Smith79810042018-05-11 02:43:08 +00004182 if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(),
4183 /*Entering*/false, MemberOfUnknownSpecialization,
4184 TemplateKWLoc))
4185 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004186
John McCalle66edc12009-11-24 19:00:30 +00004187 if (R.isAmbiguous())
4188 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004189
John McCalle66edc12009-11-24 19:00:30 +00004190 if (R.empty()) {
Richard Smith79810042018-05-11 02:43:08 +00004191 Diag(NameInfo.getLoc(), diag::err_no_member)
4192 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00004193 return ExprError();
4194 }
4195
4196 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004197 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00004198 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00004199 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00004200 Diag(Temp->getLocation(), diag::note_referenced_class_template);
4201 return ExprError();
4202 }
4203
Abramo Bagnara7945c982012-01-27 09:46:47 +00004204 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00004205}
4206
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004207/// Form a dependent template name.
Douglas Gregorb67535d2009-03-31 00:43:58 +00004208///
4209/// This action forms a dependent template name given the template
4210/// name and its (presumably dependent) scope specifier. For
4211/// example, given "MetaFun::template apply", the scope specifier \p
4212/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
4213/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004214TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00004215 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004216 SourceLocation TemplateKWLoc,
Richard Smithc08b6932018-04-27 02:00:13 +00004217 const UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00004218 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00004219 bool EnteringContext,
Richard Smithfd3dae02017-01-20 00:20:39 +00004220 TemplateTy &Result,
4221 bool AllowInjectedClassName) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004222 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4223 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004224 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004225 diag::warn_cxx98_compat_template_outside_of_template :
4226 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004227 << FixItHint::CreateRemoval(TemplateKWLoc);
4228
Craig Topperc3ec1492014-05-26 06:22:03 +00004229 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00004230 if (SS.isSet())
4231 LookupCtx = computeDeclContext(SS, EnteringContext);
4232 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00004233 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00004234 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00004235 // C++0x [temp.names]p5:
4236 // If a name prefixed by the keyword template is not the name of
4237 // a template, the program is ill-formed. [Note: the keyword
4238 // template may not be applied to non-template members of class
4239 // templates. -end note ] [ Note: as is the case with the
4240 // typename prefix, the template prefix is allowed in cases
4241 // where it is not strictly necessary; i.e., when the
4242 // nested-name-specifier or the expression on the left of the ->
4243 // or . is not dependent on a template-parameter, or the use
4244 // does not appear in the scope of a template. -end note]
4245 //
4246 // Note: C++03 was more strict here, because it banned the use of
4247 // the "template" keyword prior to a template-name that was not a
4248 // dependent name. C++ DR468 relaxed this requirement (the
4249 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00004250 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00004251 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00004252 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00004253 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00004254 MemberOfUnknownSpecialization);
Richard Smith79810042018-05-11 02:43:08 +00004255 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization) {
Douglas Gregorbb119652010-06-16 23:00:59 +00004256 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00004257 } else if (TNK == TNK_Non_template) {
Richard Smith79810042018-05-11 02:43:08 +00004258 // Do the lookup again to determine if this is a "nothing found" case or
4259 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
4260 // need to do this.
4261 DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004262 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
Richard Smith79810042018-05-11 02:43:08 +00004263 LookupOrdinaryName);
4264 bool MOUS;
4265 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext,
4266 MOUS, TemplateKWLoc))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004267 Diag(Name.getBeginLoc(), diag::err_no_member)
Richard Smith79810042018-05-11 02:43:08 +00004268 << DNI.getName() << LookupCtx << SS.getRange();
Douglas Gregorbb119652010-06-16 23:00:59 +00004269 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00004270 } else {
4271 // We found something; return it.
Richard Smithfd3dae02017-01-20 00:20:39 +00004272 auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
4273 if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
Faisal Vali2ab8c152017-12-30 04:15:27 +00004274 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4275 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
Richard Smithfd3dae02017-01-20 00:20:39 +00004276 // C++14 [class.qual]p2:
4277 // In a lookup in which function names are not ignored and the
4278 // nested-name-specifier nominates a class C, if the name specified
4279 // [...] is the injected-class-name of C, [...] the name is instead
4280 // considered to name the constructor
4281 //
4282 // We don't get here if naming the constructor would be valid, so we
4283 // just reject immediately and recover by treating the
4284 // injected-class-name as naming the template.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004285 Diag(Name.getBeginLoc(),
Richard Smithfd3dae02017-01-20 00:20:39 +00004286 diag::ext_out_of_line_qualified_id_type_names_constructor)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004287 << Name.Identifier
4288 << 0 /*injected-class-name used as template name*/
4289 << 1 /*'template' keyword was used*/;
Richard Smithfd3dae02017-01-20 00:20:39 +00004290 }
Douglas Gregorbb119652010-06-16 23:00:59 +00004291 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00004292 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00004293 }
4294
Aaron Ballman4a979672014-01-03 13:56:08 +00004295 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004296
Douglas Gregor3cf81312009-11-03 23:16:33 +00004297 switch (Name.getKind()) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00004298 case UnqualifiedIdKind::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004299 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00004300 Name.Identifier));
4301 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004302
Faisal Vali2ab8c152017-12-30 04:15:27 +00004303 case UnqualifiedIdKind::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00004304 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00004305 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00004306 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00004307
Faisal Vali2ab8c152017-12-30 04:15:27 +00004308 case UnqualifiedIdKind::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00004309 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00004310
Douglas Gregor3cf81312009-11-03 23:16:33 +00004311 default:
4312 break;
4313 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004314
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004315 Diag(Name.getBeginLoc(), diag::err_template_kw_refers_to_non_template)
4316 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
4317 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00004318 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00004319}
4320
Mike Stump11289f42009-09-09 15:08:12 +00004321bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00004322 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004323 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00004324 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00004325 QualType ArgType;
4326 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00004327
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004328 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004329 switch(Arg.getKind()) {
4330 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004331 // C++ [temp.arg.type]p1:
4332 // A template-argument for a template-parameter which is a
4333 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00004334 ArgType = Arg.getAsType();
4335 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004336 break;
Richard Smith77a9c602018-02-28 03:02:23 +00004337 case TemplateArgument::Template:
4338 case TemplateArgument::TemplateExpansion: {
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004339 // We have a template type parameter but the template argument
4340 // is a template without any arguments.
4341 SourceRange SR = AL.getSourceRange();
Richard Smith77a9c602018-02-28 03:02:23 +00004342 TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
Richard Smithecad88d2018-04-26 01:08:00 +00004343 diagnoseMissingTemplateArguments(Name, SR.getEnd());
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004344 return true;
4345 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004346 case TemplateArgument::Expression: {
4347 // We have a template type parameter but the template argument is an
4348 // expression; see if maybe it is missing the "typename" keyword.
4349 CXXScopeSpec SS;
4350 DeclarationNameInfo NameInfo;
4351
4352 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
4353 SS.Adopt(ArgExpr->getQualifierLoc());
4354 NameInfo = ArgExpr->getNameInfo();
4355 } else if (DependentScopeDeclRefExpr *ArgExpr =
4356 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4357 SS.Adopt(ArgExpr->getQualifierLoc());
4358 NameInfo = ArgExpr->getNameInfo();
4359 } else if (CXXDependentScopeMemberExpr *ArgExpr =
4360 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00004361 if (ArgExpr->isImplicitAccess()) {
4362 SS.Adopt(ArgExpr->getQualifierLoc());
4363 NameInfo = ArgExpr->getMemberNameInfo();
4364 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004365 }
4366
Reid Kleckner377c1592014-06-10 23:29:48 +00004367 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004368 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4369 LookupParsedName(Result, CurScope, &SS);
4370
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00004371 if (Result.getAsSingle<TypeDecl>() ||
4372 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00004373 LookupResult::NotFoundInCurrentInstantiation) {
4374 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004375 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00004376 Diag(Loc, getLangOpts().MSVCCompat
4377 ? diag::ext_ms_template_type_arg_missing_typename
4378 : diag::err_template_arg_must_be_type_suggest)
4379 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004380 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00004381
4382 // Recover by synthesizing a type using the location information that we
4383 // already have.
4384 ArgType =
4385 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
4386 TypeLocBuilder TLB;
4387 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
4388 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4389 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4390 TL.setNameLoc(NameInfo.getLoc());
4391 TSI = TLB.getTypeSourceInfo(Context, ArgType);
4392
4393 // Overwrite our input TemplateArgumentLoc so that we can recover
4394 // properly.
4395 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
4396 TemplateArgumentLocInfo(TSI));
4397
4398 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004399 }
4400 }
4401 // fallthrough
Galina Kistanova3779cb32017-06-07 06:25:05 +00004402 LLVM_FALLTHROUGH;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004403 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004404 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004405 // We have a template type parameter but the template argument
4406 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00004407 SourceRange SR = AL.getSourceRange();
4408 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004409 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00004410
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004411 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004412 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004413 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004414
Reid Kleckner377c1592014-06-10 23:29:48 +00004415 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004416 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004417
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004418 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00004419 ArgType = Context.getCanonicalType(ArgType);
Simon Pilgrim6905d222016-12-30 22:55:33 +00004420
Douglas Gregore46db902011-06-17 22:11:49 +00004421 // Objective-C ARC:
4422 // If an explicitly-specified template argument type is a lifetime type
4423 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004424 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00004425 ArgType->isObjCLifetimeType() &&
4426 !ArgType.getObjCLifetime()) {
4427 Qualifiers Qs;
4428 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
4429 ArgType = Context.getQualifiedType(ArgType, Qs);
4430 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00004431
Douglas Gregore46db902011-06-17 22:11:49 +00004432 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004433 return false;
4434}
4435
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004436/// Substitute template arguments into the default template argument for
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004437/// the given template type parameter.
4438///
4439/// \param SemaRef the semantic analysis object for which we are performing
4440/// the substitution.
4441///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004442/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004443/// for.
4444///
4445/// \param TemplateLoc the location of the template name that started the
4446/// template-id we are checking.
4447///
4448/// \param RAngleLoc the location of the right angle bracket ('>') that
4449/// terminates the template-id.
4450///
4451/// \param Param the template template parameter whose default we are
4452/// substituting into.
4453///
4454/// \param Converted the list of template arguments provided for template
4455/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004456/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00004457static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004458SubstDefaultTemplateArgument(Sema &SemaRef,
4459 TemplateDecl *Template,
4460 SourceLocation TemplateLoc,
4461 SourceLocation RAngleLoc,
4462 TemplateTypeParmDecl *Param,
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00004463 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00004464 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004465
4466 // If the argument type is dependent, instantiate it now based
4467 // on the previously-computed template arguments.
Erik Pilkingtonba88e212018-11-12 21:31:06 +00004468 if (ArgType->getType()->isInstantiationDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004469 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00004470 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004471 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004472 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00004473 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004474
David Majnemer8b622692016-07-03 21:17:51 +00004475 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004476
4477 // Only substitute for the innermost template argument list.
4478 MultiLevelTemplateArgumentList TemplateArgLists;
4479 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4480 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4481 TemplateArgLists.addOuterTemplateArguments(None);
4482
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00004483 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00004484 ArgType =
4485 SemaRef.SubstType(ArgType, TemplateArgLists,
4486 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004487 }
4488
4489 return ArgType;
4490}
4491
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004492/// Substitute template arguments into the default template argument for
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004493/// the given non-type template parameter.
4494///
4495/// \param SemaRef the semantic analysis object for which we are performing
4496/// the substitution.
4497///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004498/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004499/// for.
4500///
4501/// \param TemplateLoc the location of the template name that started the
4502/// template-id we are checking.
4503///
4504/// \param RAngleLoc the location of the right angle bracket ('>') that
4505/// terminates the template-id.
4506///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004507/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004508/// substituting into.
4509///
4510/// \param Converted the list of template arguments provided for template
4511/// parameters that precede \p Param in the template parameter list.
4512///
4513/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00004514static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004515SubstDefaultTemplateArgument(Sema &SemaRef,
4516 TemplateDecl *Template,
4517 SourceLocation TemplateLoc,
4518 SourceLocation RAngleLoc,
4519 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004520 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004521 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00004522 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004523 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004524 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004525 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004526
David Majnemer8b622692016-07-03 21:17:51 +00004527 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004528
4529 // Only substitute for the innermost template argument list.
4530 MultiLevelTemplateArgumentList TemplateArgLists;
4531 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4532 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4533 TemplateArgLists.addOuterTemplateArguments(None);
4534
Faisal Valid143a0c2017-04-01 21:30:49 +00004535 EnterExpressionEvaluationContext ConstantEvaluated(
4536 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00004537 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004538}
4539
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004540/// Substitute template arguments into the default template argument for
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004541/// the given template template parameter.
4542///
4543/// \param SemaRef the semantic analysis object for which we are performing
4544/// the substitution.
4545///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004546/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004547/// for.
4548///
4549/// \param TemplateLoc the location of the template name that started the
4550/// template-id we are checking.
4551///
4552/// \param RAngleLoc the location of the right angle bracket ('>') that
4553/// terminates the template-id.
4554///
4555/// \param Param the template template parameter whose default we are
4556/// substituting into.
4557///
4558/// \param Converted the list of template arguments provided for template
4559/// parameters that precede \p Param in the template parameter list.
4560///
Simon Pilgrim6905d222016-12-30 22:55:33 +00004561/// \param QualifierLoc Will be set to the nested-name-specifier (with
Douglas Gregordf846d12011-03-02 18:46:51 +00004562/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00004563///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004564/// \returns the substituted template argument, or NULL if an error occurred.
4565static TemplateName
4566SubstDefaultTemplateArgument(Sema &SemaRef,
4567 TemplateDecl *Template,
4568 SourceLocation TemplateLoc,
4569 SourceLocation RAngleLoc,
4570 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004571 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00004572 NestedNameSpecifierLoc &QualifierLoc) {
Richard Smith54f18e82016-08-31 02:15:21 +00004573 Sema::InstantiatingTemplate Inst(
4574 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
4575 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004576 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004577 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004578
David Majnemer8b622692016-07-03 21:17:51 +00004579 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004580
4581 // Only substitute for the innermost template argument list.
4582 MultiLevelTemplateArgumentList TemplateArgLists;
4583 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4584 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4585 TemplateArgLists.addOuterTemplateArguments(None);
4586
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00004587 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00004588 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00004589 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00004590 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00004591 QualifierLoc =
4592 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00004593 if (!QualifierLoc)
4594 return TemplateName();
4595 }
David Majnemer89189202013-08-28 23:48:32 +00004596
4597 return SemaRef.SubstTemplateName(
4598 QualifierLoc,
4599 Param->getDefaultArgument().getArgument().getAsTemplate(),
4600 Param->getDefaultArgument().getTemplateNameLoc(),
4601 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004602}
4603
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004604/// If the given template parameter has a default template
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004605/// argument, substitute into that default template argument and
4606/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004607TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004608Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
4609 SourceLocation TemplateLoc,
4610 SourceLocation RAngleLoc,
4611 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00004612 SmallVectorImpl<TemplateArgument>
4613 &Converted,
4614 bool &HasDefaultArg) {
4615 HasDefaultArg = false;
4616
4617 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004618 if (!hasVisibleDefaultArgument(TypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004619 return TemplateArgumentLoc();
4620
Richard Smithc87b9382013-07-04 01:01:24 +00004621 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00004622 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004623 TemplateLoc,
4624 RAngleLoc,
4625 TypeParm,
4626 Converted);
4627 if (DI)
4628 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4629
4630 return TemplateArgumentLoc();
4631 }
4632
4633 if (NonTypeTemplateParmDecl *NonTypeParm
4634 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004635 if (!hasVisibleDefaultArgument(NonTypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004636 return TemplateArgumentLoc();
4637
Richard Smithc87b9382013-07-04 01:01:24 +00004638 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00004639 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00004640 TemplateLoc,
4641 RAngleLoc,
4642 NonTypeParm,
4643 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004644 if (Arg.isInvalid())
4645 return TemplateArgumentLoc();
4646
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004647 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004648 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
4649 }
4650
4651 TemplateTemplateParmDecl *TempTempParm
4652 = cast<TemplateTemplateParmDecl>(Param);
Richard Smith95d83952015-06-10 20:36:34 +00004653 if (!hasVisibleDefaultArgument(TempTempParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004654 return TemplateArgumentLoc();
4655
Richard Smithc87b9382013-07-04 01:01:24 +00004656 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00004657 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004658 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004659 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004660 RAngleLoc,
4661 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00004662 Converted,
4663 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004664 if (TName.isNull())
4665 return TemplateArgumentLoc();
4666
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004667 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00004668 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004669 TempTempParm->getDefaultArgument().getTemplateNameLoc());
4670}
4671
Richard Smith11255ec2017-01-18 19:19:22 +00004672/// Convert a template-argument that we parsed as a type into a template, if
4673/// possible. C++ permits injected-class-names to perform dual service as
4674/// template template arguments and as template type arguments.
4675static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
4676 // Extract and step over any surrounding nested-name-specifier.
4677 NestedNameSpecifierLoc QualLoc;
4678 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4679 if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
4680 return TemplateArgumentLoc();
4681
4682 QualLoc = ETLoc.getQualifierLoc();
4683 TLoc = ETLoc.getNamedTypeLoc();
4684 }
4685
4686 // If this type was written as an injected-class-name, it can be used as a
4687 // template template argument.
4688 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4689 return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
4690 QualLoc, InjLoc.getNameLoc());
4691
4692 // If this type was written as an injected-class-name, it may have been
4693 // converted to a RecordType during instantiation. If the RecordType is
4694 // *not* wrapped in a TemplateSpecializationType and denotes a class
4695 // template specialization, it must have come from an injected-class-name.
4696 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
4697 if (auto *CTSD =
4698 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
4699 return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
4700 QualLoc, RecLoc.getNameLoc());
4701
4702 return TemplateArgumentLoc();
4703}
4704
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004705/// Check that the given template argument corresponds to the given
Douglas Gregorda0fb532009-11-11 19:31:23 +00004706/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004707///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004708/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004709/// checked.
4710///
Richard Trieu15b66532015-01-24 02:48:32 +00004711/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004712///
4713/// \param Template The template in which the template argument resides.
4714///
4715/// \param TemplateLoc The location of the template name for the template
4716/// whose argument list we're matching.
4717///
4718/// \param RAngleLoc The location of the right angle bracket ('>') that closes
4719/// the template argument list.
4720///
4721/// \param ArgumentPackIndex The index into the argument pack where this
4722/// argument will be placed. Only valid if the parameter is a parameter pack.
4723///
4724/// \param Converted The checked, converted argument will be added to the
4725/// end of this small vector.
4726///
4727/// \param CTAK Describes how we arrived at this particular template argument:
4728/// explicitly written, deduced, etc.
4729///
4730/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004731bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00004732 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00004733 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004734 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004735 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004736 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004737 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00004738 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00004739 // Check template type parameters.
4740 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004741 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004742
Douglas Gregoreebed722009-11-11 19:41:09 +00004743 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004744 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004745 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00004746 // with the template arguments we've seen thus far. But if the
4747 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004748 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004749 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
4750 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004751
Richard Smith5d331022018-03-08 01:07:33 +00004752 // FIXME: Do we need to substitute into parameters here if they're
4753 // instantiation-dependent but not dependent?
Peter Collingbourne01687632010-12-10 17:08:53 +00004754 if (NTTPType->isDependentType() &&
4755 !isa<TemplateTemplateParmDecl>(Template) &&
4756 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004757 // Do substitution on the type of the non-type template parameter.
4758 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00004759 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004760 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004761 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004762 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004763
4764 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00004765 Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004766 NTTPType = SubstType(NTTPType,
4767 MultiLevelTemplateArgumentList(TemplateArgs),
4768 NTTP->getLocation(),
4769 NTTP->getDeclName());
4770 // If that worked, check the non-type template parameter type
4771 // for validity.
4772 if (!NTTPType.isNull())
4773 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
4774 NTTP->getLocation());
4775 if (NTTPType.isNull())
4776 return true;
4777 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004778
Douglas Gregorda0fb532009-11-11 19:31:23 +00004779 switch (Arg.getArgument().getKind()) {
4780 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00004781 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004782
Douglas Gregorda0fb532009-11-11 19:31:23 +00004783 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004784 TemplateArgument Result;
Erich Keanec90bb6d2018-05-07 17:05:20 +00004785 unsigned CurSFINAEErrors = NumSFINAEErrors;
John Wiegley01296292011-04-08 18:41:53 +00004786 ExprResult Res =
4787 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
4788 Result, CTAK);
4789 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00004790 return true;
Erich Keanec90bb6d2018-05-07 17:05:20 +00004791 // If the current template argument causes an error, give up now.
4792 if (CurSFINAEErrors < NumSFINAEErrors)
4793 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004794
Richard Trieu15b66532015-01-24 02:48:32 +00004795 // If the resulting expression is new, then use it in place of the
4796 // old expression in the template argument.
4797 if (Res.get() != Arg.getArgument().getAsExpr()) {
4798 TemplateArgument TA(Res.get());
4799 Arg = TemplateArgumentLoc(TA, Res.get());
4800 }
4801
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004802 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004803 break;
4804 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004805
Douglas Gregorda0fb532009-11-11 19:31:23 +00004806 case TemplateArgument::Declaration:
4807 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00004808 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00004809 // We've already checked this template argument, so just copy
4810 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004811 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00004812 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004813
Douglas Gregorda0fb532009-11-11 19:31:23 +00004814 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004815 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00004816 // We were given a template template argument. It may not be ill-formed;
4817 // see below.
4818 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004819 = Arg.getArgument().getAsTemplateOrTemplatePattern()
4820 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004821 // We have a template argument such as \c T::template X, which we
4822 // parsed as a template template argument. However, since we now
4823 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004824 // template name into an expression.
4825
4826 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
4827 Arg.getTemplateNameLoc());
4828
Douglas Gregor3a43fd62011-02-25 20:49:16 +00004829 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00004830 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00004831 // FIXME: the template-template arg was a DependentTemplateName,
4832 // so it was provided with a template keyword. However, its source
4833 // location is not stored in the template argument structure.
4834 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004835 ExprResult E = DependentScopeDeclRefExpr::Create(
4836 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
4837 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004838
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004839 // If we parsed the template argument as a pack expansion, create a
4840 // pack expansion expression.
4841 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004842 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00004843 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004844 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004845 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004846
Douglas Gregorda0fb532009-11-11 19:31:23 +00004847 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004848 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00004849 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00004850 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004851
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004852 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004853 break;
4854 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004855
Douglas Gregorda0fb532009-11-11 19:31:23 +00004856 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00004857 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00004858 // therefore cannot be a non-type template argument.
4859 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
4860 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004861
Douglas Gregorda0fb532009-11-11 19:31:23 +00004862 Diag(Param->getLocation(), diag::note_template_param_here);
4863 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004864
Douglas Gregorda0fb532009-11-11 19:31:23 +00004865 case TemplateArgument::Type: {
4866 // We have a non-type template parameter but the template
4867 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004868
Douglas Gregorda0fb532009-11-11 19:31:23 +00004869 // C++ [temp.arg]p2:
4870 // In a template-argument, an ambiguity between a type-id and
4871 // an expression is resolved to a type-id, regardless of the
4872 // form of the corresponding template-parameter.
4873 //
4874 // We warn specifically about this case, since it can be rather
4875 // confusing for users.
4876 QualType T = Arg.getArgument().getAsType();
4877 SourceRange SR = Arg.getSourceRange();
4878 if (T->isFunctionType())
4879 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
4880 else
4881 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
4882 Diag(Param->getLocation(), diag::note_template_param_here);
4883 return true;
4884 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004885
Douglas Gregorda0fb532009-11-11 19:31:23 +00004886 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004887 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004888 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004889
Douglas Gregorda0fb532009-11-11 19:31:23 +00004890 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004891 }
4892
4893
Douglas Gregorda0fb532009-11-11 19:31:23 +00004894 // Check template template parameters.
4895 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004896
Richard Smith5d331022018-03-08 01:07:33 +00004897 TemplateParameterList *Params = TempParm->getTemplateParameters();
4898 if (TempParm->isExpandedParameterPack())
4899 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
4900
Douglas Gregorda0fb532009-11-11 19:31:23 +00004901 // Substitute into the template parameter list of the template
4902 // template parameter, since previously-supplied template arguments
4903 // may appear within the template template parameter.
Richard Smith5d331022018-03-08 01:07:33 +00004904 //
4905 // FIXME: Skip this if the parameters aren't instantiation-dependent.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004906 {
4907 // Set up a template instantiation context.
4908 LocalInstantiationScope Scope(*this);
4909 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00004910 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004911 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004912 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004913 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004914
David Majnemer8b622692016-07-03 21:17:51 +00004915 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
Richard Smith5d331022018-03-08 01:07:33 +00004916 Params = SubstTemplateParams(Params, CurContext,
4917 MultiLevelTemplateArgumentList(TemplateArgs));
4918 if (!Params)
Douglas Gregorda0fb532009-11-11 19:31:23 +00004919 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00004920 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004921
Richard Smith11255ec2017-01-18 19:19:22 +00004922 // C++1z [temp.local]p1: (DR1004)
4923 // When [the injected-class-name] is used [...] as a template-argument for
4924 // a template template-parameter [...] it refers to the class template
4925 // itself.
4926 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
4927 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
4928 Arg.getTypeSourceInfo()->getTypeLoc());
4929 if (!ConvertedArg.getArgument().isNull())
4930 Arg = ConvertedArg;
4931 }
4932
Douglas Gregorda0fb532009-11-11 19:31:23 +00004933 switch (Arg.getArgument().getKind()) {
4934 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00004935 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004936
Douglas Gregorda0fb532009-11-11 19:31:23 +00004937 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004938 case TemplateArgument::TemplateExpansion:
Richard Smith5d331022018-03-08 01:07:33 +00004939 if (CheckTemplateTemplateArgument(Params, Arg))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004940 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004941
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004942 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00004943 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004944
Douglas Gregorda0fb532009-11-11 19:31:23 +00004945 case TemplateArgument::Expression:
4946 case TemplateArgument::Type:
4947 // We have a template template parameter but the template
4948 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004949 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004950 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00004951 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004952
Douglas Gregorda0fb532009-11-11 19:31:23 +00004953 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00004954 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004955 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00004956 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00004957 case TemplateArgument::NullPtr:
4958 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004959
Douglas Gregorda0fb532009-11-11 19:31:23 +00004960 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004961 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004962 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004963
Douglas Gregorda0fb532009-11-11 19:31:23 +00004964 return false;
4965}
4966
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004967/// Check whether the template parameter is a pack expansion, and if so,
Richard Smith1fde8ec2012-09-07 02:06:42 +00004968/// determine the number of parameters produced by that expansion. For instance:
4969///
4970/// \code
4971/// template<typename ...Ts> struct A {
4972/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
4973/// };
4974/// \endcode
4975///
4976/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
4977/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00004978static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00004979 if (NonTypeTemplateParmDecl *NTTP
4980 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4981 if (NTTP->isExpandedParameterPack())
4982 return NTTP->getNumExpansionTypes();
4983 }
4984
4985 if (TemplateTemplateParmDecl *TTP
4986 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
4987 if (TTP->isExpandedParameterPack())
4988 return TTP->getNumExpansionTemplateParameters();
4989 }
4990
David Blaikie7a30dc52013-02-21 01:47:18 +00004991 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00004992}
4993
Richard Smith35c1df52015-06-17 20:16:32 +00004994/// Diagnose a missing template argument.
4995template<typename TemplateParmDecl>
4996static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
4997 TemplateDecl *TD,
4998 const TemplateParmDecl *D,
4999 TemplateArgumentListInfo &Args) {
5000 // Dig out the most recent declaration of the template parameter; there may be
5001 // declarations of the template that are more recent than TD.
5002 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
5003 ->getTemplateParameters()
5004 ->getParam(D->getIndex()));
5005
5006 // If there's a default argument that's not visible, diagnose that we're
5007 // missing a module import.
5008 llvm::SmallVector<Module*, 8> Modules;
5009 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
5010 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
5011 D->getDefaultArgumentLoc(), Modules,
5012 Sema::MissingImportKind::DefaultArgument,
Richard Smith6739a102016-05-05 00:56:12 +00005013 /*Recover*/true);
Richard Smith35c1df52015-06-17 20:16:32 +00005014 return true;
5015 }
5016
5017 // FIXME: If there's a more recent default argument that *is* visible,
5018 // diagnose that it was declared too late.
5019
Richard Smith4a8f3512018-07-19 19:00:37 +00005020 TemplateParameterList *Params = TD->getTemplateParameters();
5021
5022 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5023 << /*not enough args*/0
5024 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD))
5025 << TD;
5026 S.Diag(TD->getLocation(), diag::note_template_decl_here)
5027 << Params->getSourceRange();
5028 return true;
Richard Smith35c1df52015-06-17 20:16:32 +00005029}
5030
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005031/// Check that the given template argument list is well-formed
Douglas Gregord32e0282009-02-09 23:23:08 +00005032/// for specializing the given template.
Richard Smith11255ec2017-01-18 19:19:22 +00005033bool Sema::CheckTemplateArgumentList(
5034 TemplateDecl *Template, SourceLocation TemplateLoc,
5035 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
5036 SmallVectorImpl<TemplateArgument> &Converted,
5037 bool UpdateArgsWithConversions) {
Richard Trieu15b66532015-01-24 02:48:32 +00005038 // Make a copy of the template arguments for processing. Only make the
5039 // changes at the end when successful in matching the arguments to the
5040 // template.
5041 TemplateArgumentListInfo NewArgs = TemplateArgs;
5042
Erich Keaneaf0795b2017-10-24 01:39:56 +00005043 // Make sure we get the template parameter list from the most
5044 // recentdeclaration, since that is the only one that has is guaranteed to
5045 // have all the default template argument information.
5046 TemplateParameterList *Params =
5047 cast<TemplateDecl>(Template->getMostRecentDecl())
5048 ->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00005049
Richard Trieu15b66532015-01-24 02:48:32 +00005050 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00005051
Mike Stump11289f42009-09-09 15:08:12 +00005052 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00005053 // [...] The type and form of each template-argument specified in
5054 // a template-id shall match the type and form specified for the
5055 // corresponding parameter declared by the template in its
5056 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00005057 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005058 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00005059 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00005060 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00005061 for (TemplateParameterList::iterator Param = Params->begin(),
5062 ParamEnd = Params->end();
5063 Param != ParamEnd; /* increment in loop */) {
5064 // If we have an expanded parameter pack, make sure we don't have too
5065 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00005066 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00005067 if (*Expansions == ArgumentPack.size()) {
5068 // We're done with this parameter pack. Pack up its arguments and add
5069 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00005070 Converted.push_back(
Benjamin Kramercce63472015-08-05 09:40:22 +00005071 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00005072 ArgumentPack.clear();
5073
Richard Smith1fde8ec2012-09-07 02:06:42 +00005074 // This argument is assigned to the next parameter.
5075 ++Param;
5076 continue;
5077 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5078 // Not enough arguments for this parameter pack.
5079 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
Richard Smith4a8f3512018-07-19 19:00:37 +00005080 << /*not enough args*/0
Richard Smith0c062b42017-01-14 02:19:59 +00005081 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
Richard Smith1fde8ec2012-09-07 02:06:42 +00005082 << Template;
5083 Diag(Template->getLocation(), diag::note_template_decl_here)
5084 << Params->getSourceRange();
5085 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00005086 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00005087 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005088
Richard Smith1fde8ec2012-09-07 02:06:42 +00005089 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00005090 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00005091 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005092 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00005093 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00005094 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005095
Richard Smith96d71c32014-11-12 23:38:38 +00005096 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00005097 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00005098 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
5099 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00005100 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00005101 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00005102 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00005103 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00005104 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00005105 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00005106 Diag((*Param)->getLocation(), diag::note_template_param_here);
5107 return true;
5108 }
5109
Richard Smith1fde8ec2012-09-07 02:06:42 +00005110 // We're now done with this argument.
5111 ++ArgIdx;
5112
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005113 if ((*Param)->isTemplateParameterPack()) {
5114 // The template parameter was a template parameter pack, so take the
5115 // deduced argument and place it on the argument pack. Note that we
5116 // stay on the same template parameter so that we can deduce more
5117 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00005118 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005119 } else {
5120 // Move to the next template parameter.
5121 ++Param;
5122 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00005123
Richard Smith96d71c32014-11-12 23:38:38 +00005124 // If we just saw a pack expansion into a non-pack, then directly convert
5125 // the remaining arguments, because we don't know what parameters they'll
5126 // match up with.
5127 if (PackExpansionIntoNonPack) {
5128 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00005129 // If we were part way through filling in an expanded parameter pack,
5130 // fall back to just producing individual arguments.
5131 Converted.insert(Converted.end(),
5132 ArgumentPack.begin(), ArgumentPack.end());
5133 ArgumentPack.clear();
5134 }
5135
5136 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00005137 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00005138 ++ArgIdx;
5139 }
5140
Richard Smith1fde8ec2012-09-07 02:06:42 +00005141 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00005142 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00005143
Douglas Gregor84d49a22009-11-11 21:54:23 +00005144 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005145 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005146
Douglas Gregor2f157c92011-06-03 02:59:40 +00005147 // If we're checking a partial template argument list, we're done.
5148 if (PartialTemplateArgs) {
5149 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
Benjamin Kramercce63472015-08-05 09:40:22 +00005150 Converted.push_back(
5151 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5152
Richard Smith1fde8ec2012-09-07 02:06:42 +00005153 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00005154 }
5155
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005156 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005157 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00005158 if ((*Param)->isTemplateParameterPack()) {
5159 assert(!getExpandedPackSize(*Param) &&
5160 "Should have dealt with this already");
5161
5162 // A non-expanded parameter pack before the end of the parameter list
5163 // only occurs for an ill-formed template parameter list, unless we've
5164 // got a partial argument list for a function template, so just bail out.
5165 if (Param + 1 != ParamEnd)
5166 return true;
5167
Benjamin Kramercce63472015-08-05 09:40:22 +00005168 Converted.push_back(
5169 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00005170 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00005171
5172 ++Param;
5173 continue;
5174 }
5175
Douglas Gregor8e072612012-02-03 07:34:46 +00005176 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00005177 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005178
Douglas Gregor84d49a22009-11-11 21:54:23 +00005179 // Retrieve the default template argument from the template
5180 // parameter. For each kind of template parameter, we substitute the
5181 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005182 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00005183 // the default argument.
5184 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00005185 if (!hasVisibleDefaultArgument(TTP))
Richard Smith35c1df52015-06-17 20:16:32 +00005186 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
5187 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005188
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005189 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00005190 Template,
5191 TemplateLoc,
5192 RAngleLoc,
5193 TTP,
5194 Converted);
5195 if (!ArgType)
5196 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005197
Douglas Gregor84d49a22009-11-11 21:54:23 +00005198 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
5199 ArgType);
5200 } else if (NonTypeTemplateParmDecl *NTTP
5201 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00005202 if (!hasVisibleDefaultArgument(NTTP))
Richard Smith35c1df52015-06-17 20:16:32 +00005203 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
5204 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005205
John McCalldadc5752010-08-24 06:29:42 +00005206 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005207 TemplateLoc,
5208 RAngleLoc,
5209 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00005210 Converted);
5211 if (E.isInvalid())
5212 return true;
5213
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005214 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00005215 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
5216 } else {
5217 TemplateTemplateParmDecl *TempParm
5218 = cast<TemplateTemplateParmDecl>(*Param);
5219
Richard Smith95d83952015-06-10 20:36:34 +00005220 if (!hasVisibleDefaultArgument(TempParm))
Richard Smith35c1df52015-06-17 20:16:32 +00005221 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
5222 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005223
Douglas Gregordf846d12011-03-02 18:46:51 +00005224 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00005225 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005226 TemplateLoc,
5227 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00005228 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00005229 Converted,
5230 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005231 if (Name.isNull())
5232 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005233
Douglas Gregor9d802122011-03-02 17:09:35 +00005234 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
5235 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00005236 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005237
Douglas Gregor84d49a22009-11-11 21:54:23 +00005238 // Introduce an instantiation record that describes where we are using
Richard Smith54f18e82016-08-31 02:15:21 +00005239 // the default template argument. We're not actually instantiating a
5240 // template here, we just create this object to put a note into the
5241 // context stack.
Alp Tokerd4a72d52013-10-08 08:09:04 +00005242 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
5243 SourceRange(TemplateLoc, RAngleLoc));
5244 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00005245 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005246
Douglas Gregor84d49a22009-11-11 21:54:23 +00005247 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00005248 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00005249 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00005250 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005251
Richard Trieu15b66532015-01-24 02:48:32 +00005252 // Core issue 150 (assumed resolution): if this is a template template
5253 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00005254 // template definition.
5255 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00005256 NewArgs.addArgument(Arg);
5257
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005258 // Move to the next template parameter and argument.
5259 ++Param;
5260 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00005261 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005262
Richard Smith07f79912014-06-06 16:00:50 +00005263 // If we're performing a partial argument substitution, allow any trailing
5264 // pack expansions; they might be empty. This can happen even if
5265 // PartialTemplateArgs is false (the list of arguments is complete but
5266 // still dependent).
5267 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5268 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00005269 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
5270 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00005271 }
5272
Douglas Gregor8e072612012-02-03 07:34:46 +00005273 // If we have any leftover arguments, then there were too many arguments.
5274 // Complain and fail.
Richard Smith4a8f3512018-07-19 19:00:37 +00005275 if (ArgIdx < NumArgs) {
5276 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5277 << /*too many args*/1
5278 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5279 << Template
5280 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
5281 Diag(Template->getLocation(), diag::note_template_decl_here)
5282 << Params->getSourceRange();
5283 return true;
5284 }
Richard Trieu15b66532015-01-24 02:48:32 +00005285
5286 // No problems found with the new argument list, propagate changes back
5287 // to caller.
Richard Smith11255ec2017-01-18 19:19:22 +00005288 if (UpdateArgsWithConversions)
5289 TemplateArgs = std::move(NewArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005290
Richard Smith1fde8ec2012-09-07 02:06:42 +00005291 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00005292}
5293
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005294namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005295 class UnnamedLocalNoLinkageFinder
5296 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005297 {
5298 Sema &S;
5299 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005300
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005301 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005302
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005303 public:
5304 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5305
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005306 bool Visit(QualType T) {
Daniel Jasper5cad6852017-01-02 22:55:45 +00005307 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005308 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005309
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005310#define TYPE(Class, Parent) \
5311 bool Visit##Class##Type(const Class##Type *);
5312#define ABSTRACT_TYPE(Class, Parent) \
5313 bool Visit##Class##Type(const Class##Type *) { return false; }
5314#define NON_CANONICAL_TYPE(Class, Parent) \
5315 bool Visit##Class##Type(const Class##Type *) { return false; }
5316#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005317
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005318 bool VisitTagDecl(const TagDecl *Tag);
5319 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5320 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005321} // end anonymous namespace
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005322
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005323bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005324 return false;
5325}
5326
5327bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5328 return Visit(T->getElementType());
5329}
5330
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005331bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005332 return Visit(T->getPointeeType());
5333}
5334
5335bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005336 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005337 return Visit(T->getPointeeType());
5338}
5339
5340bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005341 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005342 return Visit(T->getPointeeType());
5343}
5344
5345bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005346 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005347 return Visit(T->getPointeeType());
5348}
5349
5350bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005351 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005352 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5353}
5354
5355bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005356 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005357 return Visit(T->getElementType());
5358}
5359
5360bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005361 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005362 return Visit(T->getElementType());
5363}
5364
5365bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005366 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005367 return Visit(T->getElementType());
5368}
5369
5370bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005371 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005372 return Visit(T->getElementType());
5373}
5374
5375bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005376 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005377 return Visit(T->getElementType());
5378}
5379
Andrew Gozillon572bbb02017-10-02 06:25:51 +00005380bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
5381 const DependentAddressSpaceType *T) {
5382 return Visit(T->getPointeeType());
5383}
5384
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005385bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5386 return Visit(T->getElementType());
5387}
5388
Erich Keanef702b022018-07-13 19:46:04 +00005389bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
5390 const DependentVectorType *T) {
5391 return Visit(T->getElementType());
5392}
5393
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005394bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5395 return Visit(T->getElementType());
5396}
5397
5398bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5399 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005400 for (const auto &A : T->param_types()) {
5401 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005402 return true;
5403 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005404
Alp Toker314cc812014-01-25 16:55:45 +00005405 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005406}
5407
5408bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5409 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00005410 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005411}
5412
5413bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5414 const UnresolvedUsingType*) {
5415 return false;
5416}
5417
5418bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5419 return false;
5420}
5421
5422bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5423 return Visit(T->getUnderlyingType());
5424}
5425
5426bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5427 return false;
5428}
5429
Alexis Hunte852b102011-05-24 22:41:36 +00005430bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5431 const UnaryTransformType*) {
5432 return false;
5433}
5434
Richard Smith30482bc2011-02-20 03:19:35 +00005435bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5436 return Visit(T->getDeducedType());
5437}
5438
Richard Smith600b5262017-01-26 20:40:47 +00005439bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5440 const DeducedTemplateSpecializationType *T) {
5441 return Visit(T->getDeducedType());
5442}
5443
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005444bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5445 return VisitTagDecl(T->getDecl());
5446}
5447
5448bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5449 return VisitTagDecl(T->getDecl());
5450}
5451
5452bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5453 const TemplateTypeParmType*) {
5454 return false;
5455}
5456
Douglas Gregorada4b792011-01-14 02:55:32 +00005457bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5458 const SubstTemplateTypeParmPackType *) {
5459 return false;
5460}
5461
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005462bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
5463 const TemplateSpecializationType*) {
5464 return false;
5465}
5466
5467bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
5468 const InjectedClassNameType* T) {
5469 return VisitTagDecl(T->getDecl());
5470}
5471
5472bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
5473 const DependentNameType* T) {
5474 return VisitNestedNameSpecifier(T->getQualifier());
5475}
5476
5477bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
5478 const DependentTemplateSpecializationType* T) {
5479 return VisitNestedNameSpecifier(T->getQualifier());
5480}
5481
Douglas Gregord2fa7662010-12-20 02:24:11 +00005482bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
5483 const PackExpansionType* T) {
5484 return Visit(T->getPattern());
5485}
5486
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005487bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5488 return false;
5489}
5490
5491bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
5492 const ObjCInterfaceType *) {
5493 return false;
5494}
5495
5496bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
5497 const ObjCObjectPointerType *) {
5498 return false;
5499}
5500
Eli Friedman0dfb8892011-10-06 23:00:33 +00005501bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
5502 return Visit(T->getValueType());
5503}
5504
Xiuli Pan9c14e282016-01-09 12:53:17 +00005505bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
5506 return false;
5507}
5508
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005509bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
5510 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005511 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005512 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00005513 diag::warn_cxx98_compat_template_arg_local_type :
5514 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005515 << S.Context.getTypeDeclType(Tag) << SR;
5516 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005517 }
5518
John McCall5ea95772013-03-09 00:54:27 +00005519 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005520 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005521 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00005522 diag::warn_cxx98_compat_template_arg_unnamed_type :
5523 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005524 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
5525 return true;
5526 }
5527
5528 return false;
5529}
5530
5531bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5532 NestedNameSpecifier *NNS) {
5533 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5534 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005535
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005536 switch (NNS->getKind()) {
5537 case NestedNameSpecifier::Identifier:
5538 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005539 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005540 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00005541 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005542 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005543
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005544 case NestedNameSpecifier::TypeSpec:
5545 case NestedNameSpecifier::TypeSpecWithTemplate:
5546 return Visit(QualType(NNS->getAsType(), 0));
5547 }
David Blaikie8a40f702012-01-17 06:56:22 +00005548 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005549}
5550
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005551/// Check a template argument against its corresponding
Douglas Gregord32e0282009-02-09 23:23:08 +00005552/// template type parameter.
5553///
5554/// This routine implements the semantics of C++ [temp.arg.type]. It
5555/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005556bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00005557 TypeSourceInfo *ArgInfo) {
5558 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00005559 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00005560 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00005561
5562 if (Arg->isVariablyModifiedType()) {
5563 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005564 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005565 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00005566 }
5567
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005568 // C++03 [temp.arg.type]p2:
5569 // A local type, a type with no linkage, an unnamed type or a type
5570 // compounded from any of these types shall not be used as a
5571 // template-argument for a template type-parameter.
5572 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00005573 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005574 // a warning.
Daniel Jasper5cad6852017-01-02 22:55:45 +00005575 if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005576 UnnamedLocalNoLinkageFinder Finder(*this, SR);
5577 (void)Finder.Visit(Context.getCanonicalType(Arg));
5578 }
5579
Douglas Gregord32e0282009-02-09 23:23:08 +00005580 return false;
5581}
5582
Douglas Gregor20fdef32012-04-10 17:08:25 +00005583enum NullPointerValueKind {
5584 NPV_NotNullPointer,
5585 NPV_NullPointer,
5586 NPV_Error
5587};
5588
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005589/// Determine whether the given template argument is a null pointer
Douglas Gregor20fdef32012-04-10 17:08:25 +00005590/// value of the appropriate type.
5591static NullPointerValueKind
5592isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
Reid Klecknercd016d82017-07-07 22:04:29 +00005593 QualType ParamType, Expr *Arg,
5594 Decl *Entity = nullptr) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00005595 if (Arg->isValueDependent() || Arg->isTypeDependent())
5596 return NPV_NotNullPointer;
David Majnemer69c3ddc2015-09-11 20:18:09 +00005597
Reid Klecknercd016d82017-07-07 22:04:29 +00005598 // dllimport'd entities aren't constant but are available inside of template
5599 // arguments.
5600 if (Entity && Entity->hasAttr<DLLImportAttr>())
5601 return NPV_NotNullPointer;
5602
Richard Smithdb0ac552015-12-18 22:40:25 +00005603 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
David Majnemerb54368c2015-09-11 20:55:29 +00005604 llvm_unreachable(
5605 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
David Majnemer69c3ddc2015-09-11 20:18:09 +00005606
David Majnemer5c734ad2014-08-14 00:49:23 +00005607 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00005608 return NPV_NotNullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005609
Douglas Gregor20fdef32012-04-10 17:08:25 +00005610 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00005611 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
5612 if (ArgRV.isInvalid())
5613 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005614 Arg = ArgRV.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005615
Douglas Gregor20fdef32012-04-10 17:08:25 +00005616 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005617 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00005618 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005619 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00005620 EvalResult.HasSideEffects) {
5621 SourceLocation DiagLoc = Arg->getExprLoc();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005622
Douglas Gregor350880c2012-04-10 19:03:30 +00005623 // If our only note is the usual "invalid subexpression" note, just point
5624 // the caret at its location rather than producing an essentially
5625 // redundant note.
5626 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5627 diag::note_invalid_subexpr_in_const_expr) {
5628 DiagLoc = Notes[0].first;
5629 Notes.clear();
5630 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005631
Douglas Gregor350880c2012-04-10 19:03:30 +00005632 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5633 << Arg->getType() << Arg->getSourceRange();
5634 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5635 S.Diag(Notes[I].first, Notes[I].second);
Simon Pilgrim6905d222016-12-30 22:55:33 +00005636
Douglas Gregor350880c2012-04-10 19:03:30 +00005637 S.Diag(Param->getLocation(), diag::note_template_param_here);
5638 return NPV_Error;
5639 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005640
Douglas Gregor20fdef32012-04-10 17:08:25 +00005641 // C++11 [temp.arg.nontype]p1:
5642 // - an address constant expression of type std::nullptr_t
5643 if (Arg->getType()->isNullPtrType())
5644 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005645
Douglas Gregor20fdef32012-04-10 17:08:25 +00005646 // - a constant expression that evaluates to a null pointer value (4.10); or
5647 // - a constant expression that evaluates to a null member pointer value
5648 // (4.11); or
5649 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
5650 (EvalResult.Val.isMemberPointer() &&
5651 !EvalResult.Val.getMemberPointerDecl())) {
5652 // If our expression has an appropriate type, we've succeeded.
5653 bool ObjCLifetimeConversion;
5654 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5655 S.IsQualificationConversion(Arg->getType(), ParamType, false,
5656 ObjCLifetimeConversion))
5657 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005658
Douglas Gregor20fdef32012-04-10 17:08:25 +00005659 // The types didn't match, but we know we got a null pointer; complain,
5660 // then recover as if the types were correct.
5661 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
5662 << Arg->getType() << ParamType << Arg->getSourceRange();
5663 S.Diag(Param->getLocation(), diag::note_template_param_here);
5664 return NPV_NullPointer;
5665 }
5666
5667 // If we don't have a null pointer value, but we do have a NULL pointer
5668 // constant, suggest a cast to the appropriate type.
5669 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
5670 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
5671 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005672 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005673 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getEndLoc()),
Alp Tokerb6cc5922014-05-03 03:45:55 +00005674 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00005675 S.Diag(Param->getLocation(), diag::note_template_param_here);
5676 return NPV_NullPointer;
5677 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005678
Douglas Gregor20fdef32012-04-10 17:08:25 +00005679 // FIXME: If we ever want to support general, address-constant expressions
5680 // as non-type template arguments, we should return the ExprResult here to
5681 // be interpreted by the caller.
5682 return NPV_NotNullPointer;
5683}
5684
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005685/// Checks whether the given template argument is compatible with its
David Majnemer61c39a12013-08-23 05:39:39 +00005686/// template parameter.
5687static bool CheckTemplateArgumentIsCompatibleWithParameter(
5688 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
5689 Expr *Arg, QualType ArgType) {
5690 bool ObjCLifetimeConversion;
5691 if (ParamType->isPointerType() &&
5692 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
5693 S.IsQualificationConversion(ArgType, ParamType, false,
5694 ObjCLifetimeConversion)) {
5695 // For pointer-to-object types, qualification conversions are
5696 // permitted.
5697 } else {
5698 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
5699 if (!ParamRef->getPointeeType()->isFunctionType()) {
5700 // C++ [temp.arg.nontype]p5b3:
5701 // For a non-type template-parameter of type reference to
5702 // object, no conversions apply. The type referred to by the
5703 // reference may be more cv-qualified than the (otherwise
5704 // identical) type of the template- argument. The
5705 // template-parameter is bound directly to the
5706 // template-argument, which shall be an lvalue.
5707
5708 // FIXME: Other qualifiers?
5709 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
5710 unsigned ArgQuals = ArgType.getCVRQualifiers();
5711
5712 if ((ParamQuals | ArgQuals) != ParamQuals) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005713 S.Diag(Arg->getBeginLoc(),
David Majnemer61c39a12013-08-23 05:39:39 +00005714 diag::err_template_arg_ref_bind_ignores_quals)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005715 << ParamType << Arg->getType() << Arg->getSourceRange();
David Majnemer61c39a12013-08-23 05:39:39 +00005716 S.Diag(Param->getLocation(), diag::note_template_param_here);
5717 return true;
5718 }
5719 }
5720 }
5721
5722 // At this point, the template argument refers to an object or
5723 // function with external linkage. We now need to check whether the
5724 // argument and parameter types are compatible.
5725 if (!S.Context.hasSameUnqualifiedType(ArgType,
5726 ParamType.getNonReferenceType())) {
5727 // We can't perform this conversion or binding.
5728 if (ParamType->isReferenceType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005729 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
5730 << ParamType << ArgIn->getType() << Arg->getSourceRange();
David Majnemer61c39a12013-08-23 05:39:39 +00005731 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005732 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
5733 << ArgIn->getType() << ParamType << Arg->getSourceRange();
David Majnemer61c39a12013-08-23 05:39:39 +00005734 S.Diag(Param->getLocation(), diag::note_template_param_here);
5735 return true;
5736 }
5737 }
5738
5739 return false;
5740}
5741
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005742/// Checks whether the given template argument is the address
Douglas Gregorccb07762009-02-11 19:52:55 +00005743/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005744static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00005745CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
5746 NonTypeTemplateParmDecl *Param,
5747 QualType ParamType,
5748 Expr *ArgIn,
5749 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005750 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005751 Expr *Arg = ArgIn;
5752 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00005753
Douglas Gregorb242683d2010-04-01 18:32:35 +00005754 bool AddressTaken = false;
5755 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00005756 if (S.getLangOpts().MicrosoftExt) {
5757 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
5758 // dereference and address-of operators.
5759 Arg = Arg->IgnoreParenCasts();
5760
5761 bool ExtWarnMSTemplateArg = false;
5762 UnaryOperatorKind FirstOpKind;
5763 SourceLocation FirstOpLoc;
5764 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5765 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
5766 if (UnOpKind == UO_Deref)
5767 ExtWarnMSTemplateArg = true;
5768 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
5769 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
5770 if (!AddrOpLoc.isValid()) {
5771 FirstOpKind = UnOpKind;
5772 FirstOpLoc = UnOp->getOperatorLoc();
5773 }
5774 } else
5775 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005776 }
David Majnemer61c39a12013-08-23 05:39:39 +00005777 if (FirstOpLoc.isValid()) {
5778 if (ExtWarnMSTemplateArg)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005779 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
5780 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00005781
David Majnemer61c39a12013-08-23 05:39:39 +00005782 if (FirstOpKind == UO_AddrOf)
5783 AddressTaken = true;
5784 else if (Arg->getType()->isPointerType()) {
5785 // We cannot let pointers get dereferenced here, that is obviously not a
5786 // constant expression.
5787 assert(FirstOpKind == UO_Deref);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005788 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
5789 << Arg->getSourceRange();
David Majnemer61c39a12013-08-23 05:39:39 +00005790 }
5791 }
5792 } else {
5793 // See through any implicit casts we added to fix the type.
5794 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00005795
David Majnemer61c39a12013-08-23 05:39:39 +00005796 // C++ [temp.arg.nontype]p1:
5797 //
5798 // A template-argument for a non-type, non-template
5799 // template-parameter shall be one of: [...]
5800 //
5801 // -- the address of an object or function with external
5802 // linkage, including function templates and function
5803 // template-ids but excluding non-static class members,
5804 // expressed as & id-expression where the & is optional if
5805 // the name refers to a function or array, or if the
5806 // corresponding template-parameter is a reference; or
5807
5808 // In C++98/03 mode, give an extension warning on any extra parentheses.
5809 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5810 bool ExtraParens = false;
5811 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5812 if (!Invalid && !ExtraParens) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005813 S.Diag(Arg->getBeginLoc(),
David Majnemer61c39a12013-08-23 05:39:39 +00005814 S.getLangOpts().CPlusPlus11
5815 ? diag::warn_cxx98_compat_template_arg_extra_parens
5816 : diag::ext_template_arg_extra_parens)
5817 << Arg->getSourceRange();
5818 ExtraParens = true;
5819 }
5820
5821 Arg = Parens->getSubExpr();
5822 }
5823
5824 while (SubstNonTypeTemplateParmExpr *subst =
5825 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5826 Arg = subst->getReplacement()->IgnoreImpCasts();
5827
5828 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5829 if (UnOp->getOpcode() == UO_AddrOf) {
5830 Arg = UnOp->getSubExpr();
5831 AddressTaken = true;
5832 AddrOpLoc = UnOp->getOperatorLoc();
5833 }
5834 }
5835
5836 while (SubstNonTypeTemplateParmExpr *subst =
5837 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5838 Arg = subst->getReplacement()->IgnoreImpCasts();
5839 }
John McCall7c454bb2011-07-15 05:09:51 +00005840
David Majnemer07910d62014-06-26 07:48:46 +00005841 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
5842 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5843
5844 // If our parameter has pointer type, check for a null template value.
5845 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
Reid Klecknercd016d82017-07-07 22:04:29 +00005846 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
5847 Entity)) {
David Majnemer07910d62014-06-26 07:48:46 +00005848 case NPV_NullPointer:
5849 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005850 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5851 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00005852 return false;
5853
5854 case NPV_Error:
5855 return true;
5856
5857 case NPV_NotNullPointer:
5858 break;
5859 }
5860 }
5861
Chandler Carruth724a8a12010-01-31 10:01:20 +00005862 // Stop checking the precise nature of the argument if it is value dependent,
5863 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00005864 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005865 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00005866 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005867 }
David Majnemer61c39a12013-08-23 05:39:39 +00005868
5869 if (isa<CXXUuidofExpr>(Arg)) {
5870 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
5871 ArgIn, Arg, ArgType))
5872 return true;
5873
5874 Converted = TemplateArgument(ArgIn);
5875 return false;
5876 }
5877
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005878 if (!DRE) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005879 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
5880 << Arg->getSourceRange();
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005881 S.Diag(Param->getLocation(), diag::note_template_param_here);
5882 return true;
5883 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00005884
Douglas Gregorccb07762009-02-11 19:52:55 +00005885 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00005886 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005887 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
5888 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005889 S.Diag(Param->getLocation(), diag::note_template_param_here);
5890 return true;
5891 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005892
5893 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00005894 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005895 if (!Method->isStatic()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005896 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
5897 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005898 S.Diag(Param->getLocation(), diag::note_template_param_here);
5899 return true;
5900 }
Richard Smith9380e0e2012-04-04 21:11:30 +00005901 }
Mike Stump11289f42009-09-09 15:08:12 +00005902
Richard Smith9380e0e2012-04-04 21:11:30 +00005903 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
5904 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00005905
Richard Smith9380e0e2012-04-04 21:11:30 +00005906 // A non-type template argument must refer to an object or function.
5907 if (!Func && !Var) {
5908 // We found something, but we don't know specifically what it is.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005909 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
5910 << Arg->getSourceRange();
Richard Smith9380e0e2012-04-04 21:11:30 +00005911 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
5912 return true;
5913 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005914
Richard Smith9380e0e2012-04-04 21:11:30 +00005915 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00005916 if (Entity->getFormalLinkage() == InternalLinkage) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005917 S.Diag(Arg->getBeginLoc(),
5918 S.getLangOpts().CPlusPlus11
5919 ? diag::warn_cxx98_compat_template_arg_object_internal
5920 : diag::ext_template_arg_object_internal)
5921 << !Func << Entity << Arg->getSourceRange();
Richard Smith9380e0e2012-04-04 21:11:30 +00005922 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5923 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00005924 } else if (!Entity->hasLinkage()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005925 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
5926 << !Func << Entity << Arg->getSourceRange();
Richard Smith9380e0e2012-04-04 21:11:30 +00005927 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5928 << !Func;
5929 return true;
5930 }
5931
5932 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005933 // If the template parameter has pointer type, the function decays.
5934 if (ParamType->isPointerType() && !AddressTaken)
5935 ArgType = S.Context.getPointerType(Func->getType());
5936 else if (AddressTaken && ParamType->isReferenceType()) {
5937 // If we originally had an address-of operator, but the
5938 // parameter has reference type, complain and (if things look
5939 // like they will work) drop the address-of operator.
5940 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
5941 ParamType.getNonReferenceType())) {
5942 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5943 << ParamType;
5944 S.Diag(Param->getLocation(), diag::note_template_param_here);
5945 return true;
5946 }
5947
5948 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5949 << ParamType
5950 << FixItHint::CreateRemoval(AddrOpLoc);
5951 S.Diag(Param->getLocation(), diag::note_template_param_here);
5952
5953 ArgType = Func->getType();
5954 }
Richard Smith9380e0e2012-04-04 21:11:30 +00005955 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005956 // A value of reference type is not an object.
5957 if (Var->getType()->isReferenceType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005958 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
5959 << Var->getType() << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005960 S.Diag(Param->getLocation(), diag::note_template_param_here);
5961 return true;
5962 }
5963
Richard Smith9380e0e2012-04-04 21:11:30 +00005964 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00005965 if (Var->getTLSKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005966 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
5967 << Arg->getSourceRange();
Richard Smith9380e0e2012-04-04 21:11:30 +00005968 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
5969 return true;
5970 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00005971
5972 // If the template parameter has pointer type, we must have taken
5973 // the address of this object.
5974 if (ParamType->isReferenceType()) {
5975 if (AddressTaken) {
5976 // If we originally had an address-of operator, but the
5977 // parameter has reference type, complain and (if things look
5978 // like they will work) drop the address-of operator.
5979 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
5980 ParamType.getNonReferenceType())) {
5981 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5982 << ParamType;
5983 S.Diag(Param->getLocation(), diag::note_template_param_here);
5984 return true;
5985 }
5986
5987 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5988 << ParamType
5989 << FixItHint::CreateRemoval(AddrOpLoc);
5990 S.Diag(Param->getLocation(), diag::note_template_param_here);
5991
5992 ArgType = Var->getType();
5993 }
5994 } else if (!AddressTaken && ParamType->isPointerType()) {
5995 if (Var->getType()->isArrayType()) {
5996 // Array-to-pointer decay.
5997 ArgType = S.Context.getArrayDecayedType(Var->getType());
5998 } else {
5999 // If the template parameter has pointer type but the address of
6000 // this object was not taken, complain and (possibly) recover by
6001 // taking the address of the entity.
6002 ArgType = S.Context.getPointerType(Var->getType());
6003 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006004 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6005 << ParamType;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006006 S.Diag(Param->getLocation(), diag::note_template_param_here);
6007 return true;
6008 }
6009
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006010 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6011 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
Douglas Gregorb242683d2010-04-01 18:32:35 +00006012
6013 S.Diag(Param->getLocation(), diag::note_template_param_here);
6014 }
6015 }
Douglas Gregorccb07762009-02-11 19:52:55 +00006016 }
Mike Stump11289f42009-09-09 15:08:12 +00006017
David Majnemer61c39a12013-08-23 05:39:39 +00006018 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6019 Arg, ArgType))
6020 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006021
6022 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00006023 Converted =
6024 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006025 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00006026 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00006027}
6028
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006029/// Checks whether the given template argument is a pointer to
Douglas Gregorccb07762009-02-11 19:52:55 +00006030/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00006031static bool CheckTemplateArgumentPointerToMember(Sema &S,
6032 NonTypeTemplateParmDecl *Param,
6033 QualType ParamType,
6034 Expr *&ResultArg,
6035 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00006036 bool Invalid = false;
6037
Douglas Gregor20fdef32012-04-10 17:08:25 +00006038 Expr *Arg = ResultArg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006039 bool ObjCLifetimeConversion;
Douglas Gregorccb07762009-02-11 19:52:55 +00006040
6041 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00006042 //
Douglas Gregorccb07762009-02-11 19:52:55 +00006043 // A template-argument for a non-type, non-template
6044 // template-parameter shall be one of: [...]
6045 //
6046 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00006047 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00006048
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00006049 // In C++98/03 mode, give an extension warning on any extra parentheses.
6050 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6051 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00006052 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00006053 if (!Invalid && !ExtraParens) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006054 S.Diag(Arg->getBeginLoc(),
6055 S.getLangOpts().CPlusPlus11
6056 ? diag::warn_cxx98_compat_template_arg_extra_parens
6057 : diag::ext_template_arg_extra_parens)
6058 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00006059 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00006060 }
6061
6062 Arg = Parens->getSubExpr();
6063 }
6064
John McCall7c454bb2011-07-15 05:09:51 +00006065 while (SubstNonTypeTemplateParmExpr *subst =
6066 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6067 Arg = subst->getReplacement()->IgnoreImpCasts();
6068
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006069 // A pointer-to-member constant written &Class::member.
6070 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00006071 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00006072 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
6073 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00006074 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00006075 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006076 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006077 // A constant of pointer-to-member type.
6078 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00006079 ValueDecl *VD = DRE->getDecl();
6080 if (VD->getType()->isMemberPointerType()) {
6081 if (isa<NonTypeTemplateParmDecl>(VD)) {
6082 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6083 Converted = TemplateArgument(Arg);
6084 } else {
6085 VD = cast<ValueDecl>(VD->getCanonicalDecl());
6086 Converted = TemplateArgument(VD, ParamType);
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006087 }
George Burgess IV00f70bd2018-03-01 05:43:23 +00006088 return Invalid;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006089 }
6090 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006091
Craig Topperc3ec1492014-05-26 06:22:03 +00006092 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006093 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006094
Reid Klecknercd016d82017-07-07 22:04:29 +00006095 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6096
6097 // Check for a null pointer value.
6098 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
6099 Entity)) {
6100 case NPV_Error:
6101 return true;
6102 case NPV_NullPointer:
6103 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6104 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
6105 /*isNullPtr*/true);
6106 return false;
6107 case NPV_NotNullPointer:
6108 break;
6109 }
6110
6111 if (S.IsQualificationConversion(ResultArg->getType(),
6112 ParamType.getNonReferenceType(), false,
6113 ObjCLifetimeConversion)) {
6114 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
6115 ResultArg->getValueKind())
6116 .get();
6117 } else if (!S.Context.hasSameUnqualifiedType(
6118 ResultArg->getType(), ParamType.getNonReferenceType())) {
6119 // We can't perform this conversion.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006120 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
Reid Klecknercd016d82017-07-07 22:04:29 +00006121 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
6122 S.Diag(Param->getLocation(), diag::note_template_param_here);
6123 return true;
6124 }
6125
Douglas Gregorccb07762009-02-11 19:52:55 +00006126 if (!DRE)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006127 return S.Diag(Arg->getBeginLoc(),
Douglas Gregor20fdef32012-04-10 17:08:25 +00006128 diag::err_template_arg_not_pointer_to_member_form)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006129 << Arg->getSourceRange();
Douglas Gregorccb07762009-02-11 19:52:55 +00006130
David Majnemer3ac84e62013-10-22 21:56:38 +00006131 if (isa<FieldDecl>(DRE->getDecl()) ||
6132 isa<IndirectFieldDecl>(DRE->getDecl()) ||
6133 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00006134 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00006135 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00006136 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
6137 "Only non-static member pointers can make it here");
6138
6139 // Okay: this is the address of a non-static member, and therefore
6140 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00006141 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00006142 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00006143 } else {
6144 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00006145 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00006146 }
Douglas Gregorccb07762009-02-11 19:52:55 +00006147 return Invalid;
6148 }
6149
6150 // We found something else, but we don't know specifically what it is.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006151 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
6152 << Arg->getSourceRange();
Douglas Gregor20fdef32012-04-10 17:08:25 +00006153 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00006154 return true;
6155}
6156
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006157/// Check a template argument against its corresponding
Douglas Gregord32e0282009-02-09 23:23:08 +00006158/// non-type template parameter.
6159///
Douglas Gregor463421d2009-03-03 04:44:36 +00006160/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00006161/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00006162/// returns the converted template argument. \p ParamType is the
6163/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00006164ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00006165 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00006166 TemplateArgument &Converted,
6167 CheckTemplateArgumentKind CTAK) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006168 SourceLocation StartLoc = Arg->getBeginLoc();
Douglas Gregorc40290e2009-03-09 23:48:35 +00006169
Richard Smith5f274382016-09-28 23:55:27 +00006170 // If the parameter type somehow involves auto, deduce the type now.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00006171 if (getLangOpts().CPlusPlus17 && ParamType->isUndeducedType()) {
Richard Smith4ae5ec82017-02-22 20:01:55 +00006172 // During template argument deduction, we allow 'decltype(auto)' to
6173 // match an arbitrary dependent argument.
6174 // FIXME: The language rules don't say what happens in this case.
6175 // FIXME: We get an opaque dependent type out of decltype(auto) if the
6176 // expression is merely instantiation-dependent; is this enough?
6177 if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
6178 auto *AT = dyn_cast<AutoType>(ParamType);
6179 if (AT && AT->isDecltypeAuto()) {
6180 Converted = TemplateArgument(Arg);
6181 return Arg;
6182 }
6183 }
6184
Richard Smith87d263e2016-12-25 08:05:23 +00006185 // When checking a deduced template argument, deduce from its type even if
6186 // the type is dependent, in order to check the types of non-type template
6187 // arguments line up properly in partial ordering.
6188 Optional<unsigned> Depth;
6189 if (CTAK != CTAK_Specified)
6190 Depth = Param->getDepth() + 1;
Richard Smith5f274382016-09-28 23:55:27 +00006191 if (DeduceAutoType(
6192 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
Richard Smith87d263e2016-12-25 08:05:23 +00006193 Arg, ParamType, Depth) == DAR_Failed) {
Richard Smith5f274382016-09-28 23:55:27 +00006194 Diag(Arg->getExprLoc(),
6195 diag::err_non_type_template_parm_type_deduction_failure)
6196 << Param->getDeclName() << Param->getType() << Arg->getType()
6197 << Arg->getSourceRange();
6198 Diag(Param->getLocation(), diag::note_template_param_here);
6199 return ExprError();
6200 }
6201 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
6202 // an error. The error message normally references the parameter
6203 // declaration, but here we'll pass the argument location because that's
6204 // where the parameter type is deduced.
6205 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
6206 if (ParamType.isNull()) {
6207 Diag(Param->getLocation(), diag::note_template_param_here);
6208 return ExprError();
6209 }
6210 }
6211
Richard Smithd663fdd2014-12-17 20:42:37 +00006212 // We should have already dropped all cv-qualifiers by now.
6213 assert(!ParamType.hasQualifiers() &&
6214 "non-type template parameter type cannot be qualified");
6215
6216 if (CTAK == CTAK_Deduced &&
Richard Smithd92eddf2016-12-27 06:14:37 +00006217 !Context.hasSameType(ParamType.getNonLValueExprType(Context),
Richard Smith0e617ec2016-12-27 07:56:27 +00006218 Arg->getType())) {
Richard Smith957fbf12017-01-17 02:14:37 +00006219 // FIXME: If either type is dependent, we skip the check. This isn't
6220 // correct, since during deduction we're supposed to have replaced each
6221 // template parameter with some unique (non-dependent) placeholder.
6222 // FIXME: If the argument type contains 'auto', we carry on and fail the
6223 // type check in order to force specific types to be more specialized than
6224 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
6225 // work.
6226 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
6227 !Arg->getType()->getContainedAutoType()) {
6228 Converted = TemplateArgument(Arg);
6229 return Arg;
6230 }
6231 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
6232 // we should actually be checking the type of the template argument in P,
6233 // not the type of the template argument deduced from A, against the
6234 // template parameter type.
Richard Smithd663fdd2014-12-17 20:42:37 +00006235 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
Richard Smith0e617ec2016-12-27 07:56:27 +00006236 << Arg->getType()
Richard Smithd663fdd2014-12-17 20:42:37 +00006237 << ParamType.getUnqualifiedType();
6238 Diag(Param->getLocation(), diag::note_template_param_here);
6239 return ExprError();
6240 }
6241
Richard Smith87d263e2016-12-25 08:05:23 +00006242 // If either the parameter has a dependent type or the argument is
6243 // type-dependent, there's nothing we can check now.
6244 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
6245 // FIXME: Produce a cloned, canonical expression?
6246 Converted = TemplateArgument(Arg);
6247 return Arg;
6248 }
6249
Richard Smithe5945872017-01-06 22:52:53 +00006250 // The initialization of the parameter from the argument is
6251 // a constant-evaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006252 EnterExpressionEvaluationContext ConstantEvaluated(
6253 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Richard Smithe5945872017-01-06 22:52:53 +00006254
Aaron Ballmanc351fba2017-12-04 20:27:34 +00006255 if (getLangOpts().CPlusPlus17) {
6256 // C++17 [temp.arg.nontype]p1:
Richard Smith410cc892014-11-26 03:26:53 +00006257 // A template-argument for a non-type template parameter shall be
6258 // a converted constant expression of the type of the template-parameter.
6259 APValue Value;
6260 ExprResult ArgResult = CheckConvertedConstantExpression(
6261 Arg, ParamType, Value, CCEK_TemplateArg);
6262 if (ArgResult.isInvalid())
6263 return ExprError();
6264
Richard Smith52e624f2016-12-21 21:42:57 +00006265 // For a value-dependent argument, CheckConvertedConstantExpression is
6266 // permitted (and expected) to be unable to determine a value.
6267 if (ArgResult.get()->isValueDependent()) {
Richard Smith01bfa682016-12-27 02:02:09 +00006268 Converted = TemplateArgument(ArgResult.get());
6269 return ArgResult;
Richard Smith52e624f2016-12-21 21:42:57 +00006270 }
6271
Richard Smithd663fdd2014-12-17 20:42:37 +00006272 QualType CanonParamType = Context.getCanonicalType(ParamType);
6273
Richard Smith410cc892014-11-26 03:26:53 +00006274 // Convert the APValue to a TemplateArgument.
6275 switch (Value.getKind()) {
6276 case APValue::Uninitialized:
6277 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00006278 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00006279 break;
6280 case APValue::Int:
6281 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00006282 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00006283 break;
6284 case APValue::MemberPointer: {
6285 assert(ParamType->isMemberPointerType());
6286
6287 // FIXME: We need TemplateArgument representation and mangling for these.
6288 if (!Value.getMemberPointerPath().empty()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006289 Diag(Arg->getBeginLoc(),
Richard Smith410cc892014-11-26 03:26:53 +00006290 diag::err_template_arg_member_ptr_base_derived_not_supported)
6291 << Value.getMemberPointerDecl() << ParamType
6292 << Arg->getSourceRange();
6293 return ExprError();
6294 }
6295
6296 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00006297 Converted = VD ? TemplateArgument(VD, CanonParamType)
6298 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00006299 break;
6300 }
6301 case APValue::LValue: {
6302 // For a non-type template-parameter of pointer or reference type,
6303 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00006304 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
6305 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00006306 // -- a temporary object
6307 // -- a string literal
6308 // -- the result of a typeid expression, or
Eric Christopher0d2c56a2017-03-31 01:45:39 +00006309 // -- a predefined __func__ variable
Richard Smith410cc892014-11-26 03:26:53 +00006310 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
6311 if (isa<CXXUuidofExpr>(E)) {
Nico Weberd60bbce2018-05-17 15:26:37 +00006312 Converted = TemplateArgument(ArgResult.get());
Richard Smith410cc892014-11-26 03:26:53 +00006313 break;
6314 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006315 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6316 << Arg->getSourceRange();
Richard Smith410cc892014-11-26 03:26:53 +00006317 return ExprError();
6318 }
6319 auto *VD = const_cast<ValueDecl *>(
6320 Value.getLValueBase().dyn_cast<const ValueDecl *>());
6321 // -- a subobject
6322 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
6323 VD && VD->getType()->isArrayType() &&
6324 Value.getLValuePath()[0].ArrayIndex == 0 &&
6325 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
6326 // Per defect report (no number yet):
6327 // ... other than a pointer to the first element of a complete array
6328 // object.
6329 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
6330 Value.isLValueOnePastTheEnd()) {
6331 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
6332 << Value.getAsString(Context, ParamType);
6333 return ExprError();
6334 }
Richard Smithd663fdd2014-12-17 20:42:37 +00006335 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00006336 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00006337 assert((!VD || !ParamType->isNullPtrType()) &&
6338 "non-null value of type nullptr_t?");
6339 Converted = VD ? TemplateArgument(VD, CanonParamType)
6340 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00006341 break;
6342 }
6343 case APValue::AddrLabelDiff:
6344 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
6345 case APValue::Float:
6346 case APValue::ComplexInt:
6347 case APValue::ComplexFloat:
6348 case APValue::Vector:
6349 case APValue::Array:
6350 case APValue::Struct:
6351 case APValue::Union:
6352 llvm_unreachable("invalid kind for template argument");
6353 }
6354
6355 return ArgResult.get();
6356 }
6357
Douglas Gregor86560402009-02-10 23:36:10 +00006358 // C++ [temp.arg.nontype]p5:
6359 // The following conversions are performed on each expression used
6360 // as a non-type template-argument. If a non-type
6361 // template-argument cannot be converted to the type of the
6362 // corresponding template-parameter then the program is
6363 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00006364 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00006365 // C++11:
6366 // -- for a non-type template-parameter of integral or
6367 // enumeration type, conversions permitted in a converted
6368 // constant expression are applied.
6369 //
6370 // C++98:
6371 // -- for a non-type template-parameter of integral or
6372 // enumeration type, integral promotions (4.5) and integral
6373 // conversions (4.7) are applied.
6374
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006375 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00006376 // C++ [temp.arg.nontype]p1:
6377 // A template-argument for a non-type, non-template template-parameter
6378 // shall be one of:
6379 //
6380 // -- for a non-type template-parameter of integral or enumeration
6381 // type, a converted constant expression of the type of the
6382 // template-parameter; or
6383 llvm::APSInt Value;
6384 ExprResult ArgResult =
6385 CheckConvertedConstantExpression(Arg, ParamType, Value,
6386 CCEK_TemplateArg);
6387 if (ArgResult.isInvalid())
6388 return ExprError();
6389
Richard Smith01bfa682016-12-27 02:02:09 +00006390 // We can't check arbitrary value-dependent arguments.
6391 if (ArgResult.get()->isValueDependent()) {
6392 Converted = TemplateArgument(ArgResult.get());
6393 return ArgResult;
6394 }
6395
Richard Smithf8379a02012-01-18 23:55:52 +00006396 // Widen the argument value to sizeof(parameter type). This is almost
6397 // always a no-op, except when the parameter type is bool. In
6398 // that case, this may extend the argument from 1 bit to 8 bits.
6399 QualType IntegerType = ParamType;
6400 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6401 IntegerType = Enum->getDecl()->getIntegerType();
6402 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
6403
Benjamin Kramer6003ad52012-06-07 15:09:51 +00006404 Converted = TemplateArgument(Context, Value,
6405 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00006406 return ArgResult;
6407 }
6408
Richard Smith08b12f12011-10-27 22:11:44 +00006409 ExprResult ArgResult = DefaultLvalueConversion(Arg);
6410 if (ArgResult.isInvalid())
6411 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006412 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00006413
6414 QualType ArgType = Arg->getType();
6415
Douglas Gregor86560402009-02-10 23:36:10 +00006416 // C++ [temp.arg.nontype]p1:
6417 // A template-argument for a non-type, non-template
6418 // template-parameter shall be one of:
6419 //
6420 // -- an integral constant-expression of integral or enumeration
6421 // type; or
6422 // -- the name of a non-type template-parameter; or
Douglas Gregor264ec4f2009-02-17 01:05:43 +00006423 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00006424 if (!ArgType->isIntegralOrEnumerationType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006425 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
6426 << ArgType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00006427 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00006428 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00006429 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00006430 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
6431 QualType T;
Simon Pilgrim6905d222016-12-30 22:55:33 +00006432
Douglas Gregore2b37442012-05-04 22:38:52 +00006433 public:
6434 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00006435
6436 void diagnoseNotICE(Sema &S, SourceLocation Loc,
6437 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00006438 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
6439 }
6440 } Diagnoser(ArgType);
6441
6442 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006443 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00006444 if (!Arg)
6445 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00006446 }
6447
Richard Smithd663fdd2014-12-17 20:42:37 +00006448 // From here on out, all we care about is the unqualified form
6449 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006450 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00006451
6452 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00006453 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00006454 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00006455 } else if (ParamType->isBooleanType()) {
6456 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006457 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00006458 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
6459 !ParamType->isEnumeralType()) {
6460 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006461 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00006462 } else {
6463 // We can't perform this conversion.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006464 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6465 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00006466 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00006467 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00006468 }
6469
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006470 // Add the value of this argument to the list of converted
6471 // arguments. We use the bitwidth and signedness of the template
6472 // parameter.
6473 if (Arg->isValueDependent()) {
6474 // The argument is value-dependent. Create a new
6475 // TemplateArgument with the converted expression.
6476 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006477 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006478 }
6479
Douglas Gregor52aba872009-03-14 00:20:21 +00006480 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00006481 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00006482 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00006483
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006484 if (ParamType->isBooleanType()) {
6485 // Value must be zero or one.
6486 Value = Value != 0;
6487 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6488 if (Value.getBitWidth() != AllowedBits)
6489 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006490 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006491 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006492 llvm::APSInt OldValue = Value;
Simon Pilgrim6905d222016-12-30 22:55:33 +00006493
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006494 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006495 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00006496 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00006497 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006498 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006499 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Simon Pilgrim6905d222016-12-30 22:55:33 +00006500
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006501 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006502 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006503 && (OldValue.isSigned() && OldValue.isNegative())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006504 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
6505 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6506 << Arg->getSourceRange();
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006507 Diag(Param->getLocation(), diag::note_template_param_here);
6508 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006509
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006510 // Complain if we overflowed the template parameter's type.
6511 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006512 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006513 RequiredBits = OldValue.getActiveBits();
6514 else if (OldValue.isUnsigned())
6515 RequiredBits = OldValue.getActiveBits() + 1;
6516 else
6517 RequiredBits = OldValue.getMinSignedBits();
6518 if (RequiredBits > AllowedBits) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006519 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
6520 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6521 << Arg->getSourceRange();
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006522 Diag(Param->getLocation(), diag::note_template_param_here);
6523 }
Douglas Gregor52aba872009-03-14 00:20:21 +00006524 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00006525
Benjamin Kramer6003ad52012-06-07 15:09:51 +00006526 Converted = TemplateArgument(Context, Value,
Simon Pilgrim6905d222016-12-30 22:55:33 +00006527 ParamType->isEnumeralType()
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00006528 ? Context.getCanonicalType(ParamType)
6529 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006530 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00006531 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006532
Richard Smith08b12f12011-10-27 22:11:44 +00006533 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00006534 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
6535
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006536 // Handle pointer-to-function, reference-to-function, and
6537 // pointer-to-member-function all in (roughly) the same way.
6538 if (// -- For a non-type template-parameter of type pointer to
6539 // function, only the function-to-pointer conversion (4.3) is
6540 // applied. If the template-argument represents a set of
6541 // overloaded functions (or a pointer to such), the matching
6542 // function is selected from the set (13.4).
6543 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006544 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006545 // -- For a non-type template-parameter of type reference to
6546 // function, no conversions apply. If the template-argument
6547 // represents a set of overloaded functions, the matching
6548 // function is selected from the set (13.4).
6549 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006550 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006551 // -- For a non-type template-parameter of type pointer to
6552 // member function, no conversions apply. If the
6553 // template-argument represents a set of overloaded member
6554 // functions, the matching member function is selected from
6555 // the set (13.4).
6556 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006557 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006558 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006559
Douglas Gregor064fdb22010-04-14 23:11:21 +00006560 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006561 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00006562 true,
6563 FoundResult)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006564 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
John Wiegley01296292011-04-08 18:41:53 +00006565 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00006566
6567 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6568 ArgType = Arg->getType();
6569 } else
John Wiegley01296292011-04-08 18:41:53 +00006570 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006571 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006572
John Wiegley01296292011-04-08 18:41:53 +00006573 if (!ParamType->isMemberPointerType()) {
6574 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6575 ParamType,
6576 Arg, Converted))
6577 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006578 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00006579 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00006580
Douglas Gregor20fdef32012-04-10 17:08:25 +00006581 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6582 Converted))
John Wiegley01296292011-04-08 18:41:53 +00006583 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006584 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006585 }
6586
Chris Lattner696197c2009-02-20 21:37:53 +00006587 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006588 // -- for a non-type template-parameter of type pointer to
6589 // object, qualification conversions (4.4) and the
6590 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00006591 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00006592 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006593 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00006594
John Wiegley01296292011-04-08 18:41:53 +00006595 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6596 ParamType,
6597 Arg, Converted))
6598 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006599 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00006600 }
Mike Stump11289f42009-09-09 15:08:12 +00006601
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006602 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006603 // -- For a non-type template-parameter of type reference to
6604 // object, no conversions apply. The type referred to by the
6605 // reference may be more cv-qualified than the (otherwise
6606 // identical) type of the template-argument. The
6607 // template-parameter is bound directly to the
6608 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00006609 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006610 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00006611
Douglas Gregor064fdb22010-04-14 23:11:21 +00006612 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006613 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
6614 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00006615 true,
6616 FoundResult)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006617 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
John Wiegley01296292011-04-08 18:41:53 +00006618 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00006619
6620 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6621 ArgType = Arg->getType();
6622 } else
John Wiegley01296292011-04-08 18:41:53 +00006623 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006624 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006625
John Wiegley01296292011-04-08 18:41:53 +00006626 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6627 ParamType,
6628 Arg, Converted))
6629 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006630 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006631 }
Douglas Gregor0e558532009-02-11 16:16:59 +00006632
Douglas Gregor20fdef32012-04-10 17:08:25 +00006633 // Deal with parameters of type std::nullptr_t.
6634 if (ParamType->isNullPtrType()) {
6635 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6636 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006637 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006638 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006639
Douglas Gregor20fdef32012-04-10 17:08:25 +00006640 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
6641 case NPV_NotNullPointer:
6642 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
6643 << Arg->getType() << ParamType;
6644 Diag(Param->getLocation(), diag::note_template_param_here);
6645 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00006646
Douglas Gregor20fdef32012-04-10 17:08:25 +00006647 case NPV_Error:
6648 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00006649
Douglas Gregor20fdef32012-04-10 17:08:25 +00006650 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00006651 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00006652 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
6653 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006654 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006655 }
6656 }
6657
Douglas Gregor0e558532009-02-11 16:16:59 +00006658 // -- For a non-type template-parameter of type pointer to data
6659 // member, qualification conversions (4.4) are applied.
6660 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
6661
Douglas Gregor20fdef32012-04-10 17:08:25 +00006662 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6663 Converted))
John Wiegley01296292011-04-08 18:41:53 +00006664 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006665 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00006666}
6667
Richard Smith26b86ea2016-12-31 21:41:23 +00006668static void DiagnoseTemplateParameterListArityMismatch(
6669 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
6670 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
6671
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006672/// Check a template argument against its corresponding
Douglas Gregord32e0282009-02-09 23:23:08 +00006673/// template template parameter.
6674///
6675/// This routine implements the semantics of C++ [temp.arg.template].
6676/// It returns true if an error occurred, and false otherwise.
Richard Smith5d331022018-03-08 01:07:33 +00006677bool Sema::CheckTemplateTemplateArgument(TemplateParameterList *Params,
6678 TemplateArgumentLoc &Arg) {
Eli Friedmanb826a002012-09-26 02:36:12 +00006679 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006680 TemplateDecl *Template = Name.getAsTemplateDecl();
6681 if (!Template) {
6682 // Any dependent template name is fine.
6683 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
6684 return false;
6685 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00006686
Richard Smith26b86ea2016-12-31 21:41:23 +00006687 if (Template->isInvalidDecl())
6688 return true;
6689
Richard Smith3f1b5d02011-05-05 21:57:07 +00006690 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00006691 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00006692 // the name of a class template or an alias template, expressed as an
6693 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00006694 // primary class templates are considered when matching the
6695 // template template argument with the corresponding parameter;
6696 // partial specializations are not considered even if their
6697 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00006698 //
6699 // Note that we also allow template template parameters here, which
6700 // will happen when we are dealing with, e.g., class template
6701 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00006702 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00006703 !isa<TemplateTemplateParmDecl>(Template) &&
David Majnemerc2406d42016-07-11 17:09:56 +00006704 !isa<TypeAliasTemplateDecl>(Template) &&
6705 !isa<BuiltinTemplateDecl>(Template)) {
6706 assert(isa<FunctionTemplateDecl>(Template) &&
6707 "Only function templates are possible here");
Faisal Valib8b04f82016-03-26 20:46:45 +00006708 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
David Majnemerc2406d42016-07-11 17:09:56 +00006709 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
6710 << Template;
Douglas Gregor85e0f662009-02-10 00:24:35 +00006711 }
6712
Richard Smith26b86ea2016-12-31 21:41:23 +00006713 // C++1z [temp.arg.template]p3: (DR 150)
6714 // A template-argument matches a template template-parameter P when P
6715 // is at least as specialized as the template-argument A.
6716 if (getLangOpts().RelaxedTemplateTemplateArgs) {
6717 // Quick check for the common case:
6718 // If P contains a parameter pack, then A [...] matches P if each of A's
6719 // template parameters matches the corresponding template parameter in
6720 // the template-parameter-list of P.
6721 if (TemplateParameterListsAreEqual(
6722 Template->getTemplateParameters(), Params, false,
6723 TPL_TemplateTemplateArgumentMatch, Arg.getLocation()))
6724 return false;
6725
6726 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
6727 Arg.getLocation()))
6728 return false;
6729 // FIXME: Produce better diagnostics for deduction failures.
6730 }
6731
Douglas Gregor85e0f662009-02-10 00:24:35 +00006732 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00006733 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006734 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006735 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006736 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00006737}
6738
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006739/// Given a non-type template argument that refers to a
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006740/// declaration and the type of its corresponding non-type template
6741/// parameter, produce an expression that properly refers to that
6742/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006743ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006744Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6745 QualType ParamType,
6746 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00006747 // C++ [temp.param]p8:
6748 //
6749 // A non-type template-parameter of type "array of T" or
6750 // "function returning T" is adjusted to be of type "pointer to
6751 // T" or "pointer to function returning T", respectively.
6752 if (ParamType->isArrayType())
6753 ParamType = Context.getArrayDecayedType(ParamType);
6754 else if (ParamType->isFunctionType())
6755 ParamType = Context.getPointerType(ParamType);
6756
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006757 // For a NULL non-type template argument, return nullptr casted to the
6758 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00006759 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006760 return ImpCastExprToType(
6761 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
6762 ParamType,
6763 ParamType->getAs<MemberPointerType>()
6764 ? CK_NullToMemberPointer
6765 : CK_NullToPointer);
6766 }
Eli Friedmanb826a002012-09-26 02:36:12 +00006767 assert(Arg.getKind() == TemplateArgument::Declaration &&
6768 "Only declaration template arguments permitted here");
6769
George Burgess IV00f70bd2018-03-01 05:43:23 +00006770 ValueDecl *VD = Arg.getAsDecl();
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006771
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006772 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00006773 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
6774 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006775 // If the value is a class member, we might have a pointer-to-member.
6776 // Determine whether the non-type template template parameter is of
6777 // pointer-to-member type. If so, we need to build an appropriate
6778 // expression for a pointer-to-member, since a "normal" DeclRefExpr
6779 // would refer to the member itself.
6780 if (ParamType->isMemberPointerType()) {
6781 QualType ClassType
6782 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
6783 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00006784 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00006785 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006786 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00006787 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00006788
6789 // The actual value-ness of this is unimportant, but for
6790 // internal consistency's sake, references to instance methods
6791 // are r-values.
6792 ExprValueKind VK = VK_LValue;
6793 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
6794 VK = VK_RValue;
6795
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006796 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00006797 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00006798 VK,
John McCall7decc9e2010-11-18 06:31:45 +00006799 Loc,
6800 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006801 if (RefExpr.isInvalid())
6802 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006803
John McCalle3027922010-08-25 11:45:40 +00006804 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006805
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006806 // We might need to perform a trailing qualification conversion, since
6807 // the element type on the parameter could be more qualified than the
6808 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00006809 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006810 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00006811 ParamType.getUnqualifiedType(), false,
6812 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006813 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006814
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006815 assert(!RefExpr.isInvalid() &&
6816 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006817 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006818 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006819 }
6820 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006821
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006822 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00006823
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006824 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006825 // When the non-type template parameter is a pointer, take the
6826 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00006827 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006828 if (RefExpr.isInvalid())
6829 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006830
Richard Smithfc6fca12017-01-28 00:38:35 +00006831 if (!Context.hasSameUnqualifiedType(ParamType->getPointeeType(), T) &&
6832 (T->isFunctionType() || T->isArrayType())) {
6833 // Decay functions and arrays unless we're forming a pointer to array.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006834 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00006835 if (RefExpr.isInvalid())
6836 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006837
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006838 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006839 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006840
Douglas Gregorb242683d2010-04-01 18:32:35 +00006841 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00006842 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006843 }
6844
John McCall7decc9e2010-11-18 06:31:45 +00006845 ExprValueKind VK = VK_RValue;
6846
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006847 // If the non-type template parameter has reference type, qualify the
6848 // resulting declaration reference with the extra qualifiers on the
6849 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00006850 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
6851 VK = VK_LValue;
6852 T = Context.getQualifiedType(T,
6853 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00006854 } else if (isa<FunctionDecl>(VD)) {
6855 // References to functions are always lvalues.
6856 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00006857 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006858
John McCall7decc9e2010-11-18 06:31:45 +00006859 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006860}
6861
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006862/// Construct a new expression that refers to the given
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006863/// integral template argument with the given source-location
6864/// information.
6865///
6866/// This routine takes care of the mapping from an integral template
6867/// argument (which may have any integral type) to the appropriate
6868/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006869ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006870Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6871 SourceLocation Loc) {
6872 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00006873 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006874 QualType OrigT = Arg.getIntegralType();
6875
6876 // If this is an enum type that we're instantiating, we need to use an integer
6877 // type the same size as the enumerator. We don't want to build an
6878 // IntegerLiteral with enum type. The integer type of an enum type can be of
6879 // any integral type with C++11 enum classes, make sure we create the right
6880 // type of literal for it.
6881 QualType T = OrigT;
6882 if (const EnumType *ET = OrigT->getAs<EnumType>())
6883 T = ET->getDecl()->getIntegerType();
6884
6885 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00006886 if (T->isAnyCharacterType()) {
6887 CharacterLiteral::CharacterKind Kind;
6888 if (T->isWideCharType())
6889 Kind = CharacterLiteral::Wide;
Richard Smith3a8244d2018-05-01 05:02:45 +00006890 else if (T->isChar8Type() && getLangOpts().Char8)
6891 Kind = CharacterLiteral::UTF8;
Douglas Gregorfb65e592011-07-27 05:40:30 +00006892 else if (T->isChar16Type())
6893 Kind = CharacterLiteral::UTF16;
6894 else if (T->isChar32Type())
6895 Kind = CharacterLiteral::UTF32;
6896 else
6897 Kind = CharacterLiteral::Ascii;
6898
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006899 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
6900 Kind, T, Loc);
6901 } else if (T->isBooleanType()) {
6902 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
6903 T, Loc);
6904 } else if (T->isNullPtrType()) {
6905 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
6906 } else {
6907 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00006908 }
6909
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006910 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00006911 // FIXME: This is a hack. We need a better way to handle substituted
6912 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00006913 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
6914 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006915 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00006916 Loc, Loc);
6917 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006918
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006919 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006920}
6921
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006922/// Match two template parameters within template parameter lists.
Douglas Gregor641040a2011-01-12 23:45:44 +00006923static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
6924 bool Complain,
6925 Sema::TemplateParameterListEqualKind Kind,
6926 SourceLocation TemplateArgLoc) {
6927 // Check the actual kind (type, non-type, template).
6928 if (Old->getKind() != New->getKind()) {
6929 if (Complain) {
6930 unsigned NextDiag = diag::err_template_param_different_kind;
6931 if (TemplateArgLoc.isValid()) {
6932 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6933 NextDiag = diag::note_template_param_different_kind;
6934 }
6935 S.Diag(New->getLocation(), NextDiag)
6936 << (Kind != Sema::TPL_TemplateMatch);
6937 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
6938 << (Kind != Sema::TPL_TemplateMatch);
6939 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006940
Douglas Gregor641040a2011-01-12 23:45:44 +00006941 return false;
6942 }
6943
Richard Smith26b86ea2016-12-31 21:41:23 +00006944 // Check that both are parameter packs or neither are parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006945 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006946 // template template parameter, the template template parameter can have
6947 // a parameter pack where the template template argument does not.
6948 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
6949 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
6950 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00006951 if (Complain) {
6952 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
6953 if (TemplateArgLoc.isValid()) {
6954 S.Diag(TemplateArgLoc,
6955 diag::err_template_arg_template_params_mismatch);
6956 NextDiag = diag::note_template_parameter_pack_non_pack;
6957 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006958
Douglas Gregor641040a2011-01-12 23:45:44 +00006959 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
6960 : isa<NonTypeTemplateParmDecl>(New)? 1
6961 : 2;
6962 S.Diag(New->getLocation(), NextDiag)
6963 << ParamKind << New->isParameterPack();
6964 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
6965 << ParamKind << Old->isParameterPack();
6966 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006967
Douglas Gregor641040a2011-01-12 23:45:44 +00006968 return false;
6969 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006970
Douglas Gregor641040a2011-01-12 23:45:44 +00006971 // For non-type template parameters, check the type of the parameter.
6972 if (NonTypeTemplateParmDecl *OldNTTP
6973 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
6974 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006975
Douglas Gregor641040a2011-01-12 23:45:44 +00006976 // If we are matching a template template argument to a template
6977 // template parameter and one of the non-type template parameter types
Richard Smith13894182017-04-13 21:37:24 +00006978 // is dependent, then we must wait until template instantiation time
6979 // to actually compare the arguments.
Douglas Gregor641040a2011-01-12 23:45:44 +00006980 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
Richard Smith13894182017-04-13 21:37:24 +00006981 (OldNTTP->getType()->isDependentType() ||
6982 NewNTTP->getType()->isDependentType()))
Douglas Gregor641040a2011-01-12 23:45:44 +00006983 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006984
Douglas Gregor641040a2011-01-12 23:45:44 +00006985 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
6986 if (Complain) {
6987 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
6988 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006989 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00006990 diag::err_template_arg_template_params_mismatch);
6991 NextDiag = diag::note_template_nontype_parm_different_type;
6992 }
6993 S.Diag(NewNTTP->getLocation(), NextDiag)
6994 << NewNTTP->getType()
6995 << (Kind != Sema::TPL_TemplateMatch);
6996 S.Diag(OldNTTP->getLocation(),
6997 diag::note_template_nontype_parm_prev_declaration)
6998 << OldNTTP->getType();
6999 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007000
Douglas Gregor641040a2011-01-12 23:45:44 +00007001 return false;
7002 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007003
Douglas Gregor641040a2011-01-12 23:45:44 +00007004 return true;
7005 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007006
Douglas Gregor641040a2011-01-12 23:45:44 +00007007 // For template template parameters, check the template parameter types.
7008 // The template parameter lists of template template
7009 // parameters must agree.
7010 if (TemplateTemplateParmDecl *OldTTP
7011 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007012 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00007013 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
7014 OldTTP->getTemplateParameters(),
7015 Complain,
7016 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007017 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00007018 : Kind),
7019 TemplateArgLoc);
7020 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007021
Douglas Gregor641040a2011-01-12 23:45:44 +00007022 return true;
7023}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00007024
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007025/// Diagnose a known arity mismatch when comparing template argument
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007026/// lists.
7027static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007028void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007029 TemplateParameterList *New,
7030 TemplateParameterList *Old,
7031 Sema::TemplateParameterListEqualKind Kind,
7032 SourceLocation TemplateArgLoc) {
7033 unsigned NextDiag = diag::err_template_param_list_different_arity;
7034 if (TemplateArgLoc.isValid()) {
7035 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7036 NextDiag = diag::note_template_param_list_different_arity;
7037 }
7038 S.Diag(New->getTemplateLoc(), NextDiag)
7039 << (New->size() > Old->size())
7040 << (Kind != Sema::TPL_TemplateMatch)
7041 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
7042 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
7043 << (Kind != Sema::TPL_TemplateMatch)
7044 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
7045}
7046
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007047/// Determine whether the given template parameter lists are
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007048/// equivalent.
7049///
Mike Stump11289f42009-09-09 15:08:12 +00007050/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007051/// source code as part of a new template declaration.
7052///
7053/// \param Old The old template parameter list, typically found via
7054/// name lookup of the template declared with this template parameter
7055/// list.
7056///
7057/// \param Complain If true, this routine will produce a diagnostic if
7058/// the template parameter lists are not equivalent.
7059///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00007060/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00007061///
7062/// \param TemplateArgLoc If this source location is valid, then we
7063/// are actually checking the template parameter list of a template
7064/// argument (New) against the template parameter list of its
7065/// corresponding template template parameter (Old). We produce
7066/// slightly different diagnostics in this scenario.
7067///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007068/// \returns True if the template parameter lists are equal, false
7069/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00007070bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007071Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
7072 TemplateParameterList *Old,
7073 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00007074 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00007075 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007076 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
7077 if (Complain)
7078 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7079 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007080
7081 return false;
7082 }
7083
Douglas Gregor641040a2011-01-12 23:45:44 +00007084 // C++0x [temp.arg.template]p3:
7085 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00007086 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00007087 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00007088 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007089 // template-parameter-list of P. [...]
7090 TemplateParameterList::iterator NewParm = New->begin();
7091 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007092 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007093 OldParmEnd = Old->end();
7094 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00007095 if (Kind != TPL_TemplateTemplateArgumentMatch ||
7096 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007097 if (NewParm == NewParmEnd) {
7098 if (Complain)
7099 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7100 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007101
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007102 return false;
7103 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007104
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007105 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
7106 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007107 return false;
7108
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007109 ++NewParm;
7110 continue;
7111 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007112
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007113 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00007114 // [...] When P's template- parameter-list contains a template parameter
7115 // pack (14.5.3), the template parameter pack will match zero or more
7116 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007117 // template-parameter-list of A with the same type and form as the
7118 // template parameter pack in P (ignoring whether those template
7119 // parameters are template parameter packs).
7120 for (; NewParm != NewParmEnd; ++NewParm) {
7121 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
7122 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007123 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007124 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007125 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007126
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007127 // Make sure we exhausted all of the arguments.
7128 if (NewParm != NewParmEnd) {
7129 if (Complain)
7130 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7131 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007132
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007133 return false;
7134 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007135
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007136 return true;
7137}
7138
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007139/// Check whether a template can be declared within this scope.
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007140///
7141/// If the template declaration is valid in this scope, returns
7142/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00007143bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007144Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00007145 if (!S)
7146 return false;
7147
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007148 // Find the nearest enclosing declaration scope.
7149 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7150 (S->getFlags() & Scope::TemplateParamScope) != 0)
7151 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00007152
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00007153 // C++ [temp]p4:
7154 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007155 DeclContext *Ctx = S->getEntity();
Alex Lorenz560ae562016-11-02 15:46:34 +00007156 if (Ctx && Ctx->isExternCContext()) {
7157 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
7158 << TemplateParams->getSourceRange();
7159 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
7160 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
7161 return true;
7162 }
Richard Smith8df390f2016-09-08 23:14:54 +00007163 Ctx = Ctx->getRedeclContext();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007164
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00007165 // C++ [temp]p2:
7166 // A template-declaration can appear only as a namespace scope or
7167 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00007168 if (Ctx) {
7169 if (Ctx->isFileContext())
7170 return false;
7171 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
7172 // C++ [temp.mem]p2:
7173 // A local class shall not have member templates.
7174 if (RD->isLocalClass())
7175 return Diag(TemplateParams->getTemplateLoc(),
7176 diag::err_template_inside_local_class)
7177 << TemplateParams->getSourceRange();
7178 else
7179 return false;
7180 }
7181 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007182
Mike Stump11289f42009-09-09 15:08:12 +00007183 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007184 diag::err_template_outside_namespace_or_class_scope)
7185 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007186}
Douglas Gregor67a65642009-02-17 23:15:12 +00007187
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007188/// Determine what kind of template specialization the given declaration
Douglas Gregor54888652009-10-07 00:13:32 +00007189/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007190static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00007191 if (!D)
7192 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007193
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007194 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
7195 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00007196 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
7197 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007198 if (VarDecl *Var = dyn_cast<VarDecl>(D))
7199 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007200
Douglas Gregor54888652009-10-07 00:13:32 +00007201 return TSK_Undeclared;
7202}
7203
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007204/// Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007205/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00007206///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007207/// This routine determines whether a template specialization can be declared
7208/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00007209///
7210/// \param S the semantic analysis object for which this check is being
7211/// performed.
7212///
7213/// \param Specialized the entity being specialized or instantiated, which
7214/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007215/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00007216/// member class).
7217///
7218/// \param PrevDecl the previous declaration of this entity, if any.
7219///
7220/// \param Loc the location of the explicit specialization or instantiation of
7221/// this entity.
7222///
7223/// \param IsPartialSpecialization whether this is a partial specialization of
7224/// a class template.
7225///
Douglas Gregor54888652009-10-07 00:13:32 +00007226/// \returns true if there was an error that we cannot recover from, false
7227/// otherwise.
7228static bool CheckTemplateSpecializationScope(Sema &S,
7229 NamedDecl *Specialized,
7230 NamedDecl *PrevDecl,
7231 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007232 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00007233 // Keep these "kind" numbers in sync with the %select statements in the
7234 // various diagnostics emitted by this routine.
7235 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00007236 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00007237 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007238 else if (isa<VarTemplateDecl>(Specialized))
7239 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00007240 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00007241 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007242 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00007243 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007244 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00007245 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007246 else if (isa<RecordDecl>(Specialized))
7247 EntityKind = 7;
7248 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
7249 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00007250 else {
Richard Smith7d137e32012-03-23 03:33:32 +00007251 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007252 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007253 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00007254 return true;
7255 }
7256
Douglas Gregorf47b9112009-02-25 22:02:03 +00007257 // C++ [temp.expl.spec]p2:
Richard Smithc660c8f2018-03-16 13:36:56 +00007258 // An explicit specialization may be declared in any scope in which
7259 // the corresponding primary template may be defined.
Sebastian Redl50c68252010-08-31 00:36:30 +00007260 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00007261 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007262 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007263 return true;
7264 }
Douglas Gregore4b05162009-10-07 17:21:34 +00007265
7266 // C++ [temp.class.spec]p6:
Richard Smithc660c8f2018-03-16 13:36:56 +00007267 // A class template partial specialization may be declared in any
7268 // scope in which the primary template may be defined.
7269 DeclContext *SpecializedContext =
7270 Specialized->getDeclContext()->getRedeclContext();
7271 DeclContext *DC = S.CurContext->getRedeclContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00007272
Richard Smithc660c8f2018-03-16 13:36:56 +00007273 // Make sure that this redeclaration (or definition) occurs in the same
7274 // scope or an enclosing namespace.
7275 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
7276 : DC->Equals(SpecializedContext))) {
Richard Smitha98f8fc2013-12-07 05:09:50 +00007277 if (isa<TranslationUnitDecl>(SpecializedContext))
7278 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
7279 << EntityKind << Specialized;
Richard Smithc660c8f2018-03-16 13:36:56 +00007280 else {
7281 auto *ND = cast<NamedDecl>(SpecializedContext);
Alexey Bataev0068cb22015-03-20 07:21:46 +00007282 int Diag = diag::err_template_spec_redecl_out_of_scope;
Richard Smithc660c8f2018-03-16 13:36:56 +00007283 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
Alexey Bataev0068cb22015-03-20 07:21:46 +00007284 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
7285 S.Diag(Loc, Diag) << EntityKind << Specialized
Richard Smithc660c8f2018-03-16 13:36:56 +00007286 << ND << isa<CXXRecordDecl>(ND);
7287 }
Richard Smitha98f8fc2013-12-07 05:09:50 +00007288
7289 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007290
Richard Smithc660c8f2018-03-16 13:36:56 +00007291 // Don't allow specializing in the wrong class during error recovery.
7292 // Otherwise, things can go horribly wrong.
7293 if (DC->isRecord())
7294 return true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007295 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007296
Douglas Gregorf47b9112009-02-25 22:02:03 +00007297 return false;
7298}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007299
Richard Smith57aae072016-12-28 02:37:25 +00007300static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
7301 if (!E->isTypeDependent())
Richard Smith6056d5e2014-02-09 00:54:43 +00007302 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00007303 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00007304 Checker.TraverseStmt(E);
Richard Smith57aae072016-12-28 02:37:25 +00007305 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00007306 return E->getSourceRange();
7307 return Checker.MatchLoc;
7308}
7309
7310static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
7311 if (!TL.getType()->isDependentType())
7312 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00007313 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00007314 Checker.TraverseTypeLoc(TL);
Richard Smith57aae072016-12-28 02:37:25 +00007315 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00007316 return TL.getSourceRange();
7317 return Checker.MatchLoc;
7318}
7319
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007320/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007321/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007322static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00007323 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
7324 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007325 for (unsigned I = 0; I != NumArgs; ++I) {
7326 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00007327 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00007328 S, TemplateNameLoc, Param, Args[I].pack_begin(),
7329 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007330 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007331
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007332 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007333 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007334
Eli Friedmanb826a002012-09-26 02:36:12 +00007335 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007336 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00007337
7338 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007339
Douglas Gregor98318c22011-01-03 21:37:45 +00007340 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007341 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
7342 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00007343
7344 // Strip off any implicit casts we added as part of type checking.
7345 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
7346 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007347
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007348 // C++ [temp.class.spec]p8:
7349 // A non-type argument is non-specialized if it is the name of a
7350 // non-type parameter. All other non-type arguments are
7351 // specialized.
7352 //
7353 // Below, we check the two conditions that only apply to
7354 // specialized non-type arguments, so skip any non-specialized
7355 // arguments.
7356 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00007357 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007358 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007359
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007360 // C++ [temp.class.spec]p9:
7361 // Within the argument list of a class template partial
7362 // specialization, the following restrictions apply:
7363 // -- A partially specialized non-type argument expression
7364 // shall not involve a template parameter of the partial
7365 // specialization except when the argument expression is a
7366 // simple identifier.
Richard Smith57aae072016-12-28 02:37:25 +00007367 // -- The type of a template parameter corresponding to a
7368 // specialized non-type argument shall not be dependent on a
7369 // parameter of the specialization.
7370 // DR1315 removes the first bullet, leaving an incoherent set of rules.
7371 // We implement a compromise between the original rules and DR1315:
7372 // -- A specialized non-type template argument shall not be
7373 // type-dependent and the corresponding template parameter
7374 // shall have a non-dependent type.
Richard Smith6056d5e2014-02-09 00:54:43 +00007375 SourceRange ParamUseRange =
Richard Smith57aae072016-12-28 02:37:25 +00007376 findTemplateParameterInType(Param->getDepth(), ArgExpr);
Richard Smith6056d5e2014-02-09 00:54:43 +00007377 if (ParamUseRange.isValid()) {
7378 if (IsDefaultArgument) {
7379 S.Diag(TemplateNameLoc,
7380 diag::err_dependent_non_type_arg_in_partial_spec);
7381 S.Diag(ParamUseRange.getBegin(),
7382 diag::note_dependent_non_type_default_arg_in_partial_spec)
7383 << ParamUseRange;
7384 } else {
7385 S.Diag(ParamUseRange.getBegin(),
7386 diag::err_dependent_non_type_arg_in_partial_spec)
7387 << ParamUseRange;
7388 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007389 return true;
7390 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007391
Richard Smith6056d5e2014-02-09 00:54:43 +00007392 ParamUseRange = findTemplateParameter(
Richard Smith57aae072016-12-28 02:37:25 +00007393 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
Richard Smith6056d5e2014-02-09 00:54:43 +00007394 if (ParamUseRange.isValid()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007395 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
Richard Smith6056d5e2014-02-09 00:54:43 +00007396 diag::err_dependent_typed_non_type_arg_in_partial_spec)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007397 << Param->getType();
Richard Smith6056d5e2014-02-09 00:54:43 +00007398 S.Diag(Param->getLocation(), diag::note_template_param_here)
Richard Smith57aae072016-12-28 02:37:25 +00007399 << (IsDefaultArgument ? ParamUseRange : SourceRange())
7400 << ParamUseRange;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007401 return true;
7402 }
7403 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007404
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007405 return false;
7406}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007407
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007408/// Check the non-type template arguments of a class template
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007409/// partial specialization according to C++ [temp.class.spec]p9.
7410///
Richard Smith6056d5e2014-02-09 00:54:43 +00007411/// \param TemplateNameLoc the location of the template name.
Simon Pilgrim6905d222016-12-30 22:55:33 +00007412/// \param PrimaryTemplate the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00007413/// template.
7414/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00007415/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00007416/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007417///
Richard Smith6056d5e2014-02-09 00:54:43 +00007418/// \returns \c true if there was an error, \c false otherwise.
Richard Smith57aae072016-12-28 02:37:25 +00007419bool Sema::CheckTemplatePartialSpecializationArgs(
7420 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
7421 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
7422 // We have to be conservative when checking a template in a dependent
7423 // context.
7424 if (PrimaryTemplate->getDeclContext()->isDependentContext())
7425 return false;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007426
Richard Smith57aae072016-12-28 02:37:25 +00007427 TemplateParameterList *TemplateParams =
7428 PrimaryTemplate->getTemplateParameters();
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007429 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7430 NonTypeTemplateParmDecl *Param
7431 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
7432 if (!Param)
7433 continue;
7434
Richard Smith57aae072016-12-28 02:37:25 +00007435 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
7436 Param, &TemplateArgs[I],
7437 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007438 return true;
7439 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007440
7441 return false;
7442}
7443
Erich Keanec480f302018-07-12 21:09:05 +00007444DeclResult Sema::ActOnClassTemplateSpecialization(
7445 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7446 SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId,
7447 const ParsedAttributesView &Attr,
7448 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00007449 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00007450
Richard Smith4b55a9c2014-04-17 03:29:33 +00007451 CXXScopeSpec &SS = TemplateId.SS;
7452
Abramo Bagnara60804e12011-03-18 15:16:37 +00007453 // NOTE: KWLoc is the location of the tag keyword. This will instead
7454 // store the location of the outermost template keyword in the declaration.
7455 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00007456 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
7457 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
7458 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
7459 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00007460
Douglas Gregor67a65642009-02-17 23:15:12 +00007461 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00007462 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00007463 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00007464 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
7465
7466 if (!ClassTemplate) {
7467 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007468 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00007469 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
7470 return true;
7471 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007472
Richard Smithf445f192017-02-09 21:04:43 +00007473 bool isMemberSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00007474 bool isPartialSpecialization = false;
7475
Douglas Gregorf47b9112009-02-25 22:02:03 +00007476 // Check the validity of the template headers that introduce this
7477 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00007478 // FIXME: We probably shouldn't complain about these headers for
7479 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007480 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00007481 TemplateParameterList *TemplateParams =
7482 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00007483 KWLoc, TemplateNameLoc, SS, &TemplateId,
Richard Smithf445f192017-02-09 21:04:43 +00007484 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
Richard Smith4b55a9c2014-04-17 03:29:33 +00007485 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007486 if (Invalid)
7487 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007488
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007489 if (TemplateParams && TemplateParams->size() > 0) {
7490 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007491
Douglas Gregorec9518b2010-12-21 08:14:57 +00007492 if (TUK == TUK_Friend) {
7493 Diag(KWLoc, diag::err_partial_specialization_friend)
7494 << SourceRange(LAngleLoc, RAngleLoc);
7495 return true;
7496 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007497
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007498 // C++ [temp.class.spec]p10:
7499 // The template parameter list of a specialization shall not
7500 // contain default template argument values.
7501 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7502 Decl *Param = TemplateParams->getParam(I);
7503 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
7504 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00007505 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007506 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00007507 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007508 }
7509 } else if (NonTypeTemplateParmDecl *NTTP
7510 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
7511 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00007512 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007513 diag::err_default_arg_in_partial_spec)
7514 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00007515 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007516 }
7517 } else {
7518 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00007519 if (TTP->hasDefaultArgument()) {
7520 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007521 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00007522 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00007523 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00007524 }
7525 }
7526 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007527 } else if (TemplateParams) {
7528 if (TUK == TUK_Friend)
7529 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00007530 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007531 SourceRange(TemplateParams->getTemplateLoc(),
7532 TemplateParams->getRAngleLoc()))
7533 << SourceRange(LAngleLoc, RAngleLoc);
Richard Smith4b55a9c2014-04-17 03:29:33 +00007534 } else {
7535 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007536 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00007537
Douglas Gregor67a65642009-02-17 23:15:12 +00007538 // Check that the specialization uses the same tag kind as the
7539 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007540 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7541 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00007542 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007543 Kind, TUK == TUK_Definition, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00007544 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007545 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00007546 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007547 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00007548 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007549 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00007550 diag::note_previous_use);
7551 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7552 }
7553
Douglas Gregorc40290e2009-03-09 23:48:35 +00007554 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00007555 TemplateArgumentListInfo TemplateArgs =
7556 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00007557
Douglas Gregor14406932011-01-03 20:35:03 +00007558 // Check for unexpanded parameter packs in any of the template arguments.
7559 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007560 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00007561 UPPC_PartialSpecialization))
7562 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007563
Douglas Gregor67a65642009-02-17 23:15:12 +00007564 // Check that the template argument list is well-formed for this
7565 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007566 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007567 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7568 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00007569 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00007570
Douglas Gregor2373c592009-05-31 09:31:02 +00007571 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00007572 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00007573 if (isPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00007574 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
7575 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007576 return true;
7577
Richard Smith57aae072016-12-28 02:37:25 +00007578 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
7579 // also do it during instantiation.
Douglas Gregor678d76c2011-07-01 01:22:09 +00007580 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007581 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00007582 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00007583 TemplateArgs.arguments(), InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00007584 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
7585 << ClassTemplate->getDeclName();
7586 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00007587 }
7588 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007589
Craig Topperc3ec1492014-05-26 06:22:03 +00007590 void *InsertPos = nullptr;
7591 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00007592
7593 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007594 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00007595 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00007596 else
Craig Topper7e0daca2014-06-26 04:58:53 +00007597 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00007598
Craig Topperc3ec1492014-05-26 06:22:03 +00007599 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00007600
Douglas Gregorf47b9112009-02-25 22:02:03 +00007601 // Check whether we can declare a class template specialization in
7602 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00007603 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007604 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
7605 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007606 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00007607 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007608
Douglas Gregor15301382009-07-30 17:40:51 +00007609 // The canonical type
7610 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00007611 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00007612 // Build the canonical type that describes the converted template
7613 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00007614 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7615 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00007616 Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007617
7618 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007619 ClassTemplate->getInjectedClassNameSpecialization())) {
7620 // C++ [temp.class.spec]p9b3:
7621 //
7622 // -- The argument list of the specialization shall not be identical
7623 // to the implicit argument list of the primary template.
Richard Smith0e617ec2016-12-27 07:56:27 +00007624 //
7625 // This rule has since been removed, because it's redundant given DR1495,
7626 // but we keep it because it produces better diagnostics and recovery.
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007627 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00007628 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00007629 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007630 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
7631 ClassTemplate->getIdentifier(),
7632 TemplateNameLoc,
7633 Attr,
7634 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00007635 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00007636 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00007637 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007638 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007639 }
Douglas Gregor15301382009-07-30 17:40:51 +00007640
Douglas Gregor2373c592009-05-31 09:31:02 +00007641 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00007642 ClassTemplatePartialSpecializationDecl *PrevPartial
7643 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007644 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00007645 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00007646 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007647 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00007648 TemplateParams,
7649 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007650 Converted,
John McCall6b51f282009-11-23 01:53:49 +00007651 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00007652 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00007653 PrevPartial);
Bruno Ricci4224c872018-12-21 14:35:24 +00007654 SetNestedNameSpecifier(*this, Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007655 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Benjamin Kramer9cc210652015-08-05 09:40:49 +00007656 Partial->setTemplateParameterListsInfo(
7657 Context, TemplateParameterLists.drop_back(1));
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007658 }
Douglas Gregor2373c592009-05-31 09:31:02 +00007659
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007660 if (!PrevPartial)
7661 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00007662 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00007663
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007664 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00007665 // template specialization, make a note of that.
7666 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
7667 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007668
Richard Smith57aae072016-12-28 02:37:25 +00007669 CheckTemplatePartialSpecialization(Partial);
Douglas Gregor67a65642009-02-17 23:15:12 +00007670 } else {
7671 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00007672 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00007673 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007674 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00007675 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007676 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007677 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007678 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00007679 PrevDecl);
Bruno Ricci4224c872018-12-21 14:35:24 +00007680 SetNestedNameSpecifier(*this, Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007681 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00007682 Specialization->setTemplateParameterListsInfo(Context,
Benjamin Kramer9cc210652015-08-05 09:40:49 +00007683 TemplateParameterLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007684 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007685
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007686 if (!PrevDecl)
7687 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00007688
David Majnemer678f50b2015-11-18 19:49:19 +00007689 if (CurContext->isDependentContext()) {
David Majnemer678f50b2015-11-18 19:49:19 +00007690 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7691 CanonType = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00007692 CanonTemplate, Converted);
David Majnemer678f50b2015-11-18 19:49:19 +00007693 } else {
7694 CanonType = Context.getTypeDeclType(Specialization);
7695 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007696 }
7697
Douglas Gregor06db9f52009-10-12 20:18:28 +00007698 // C++ [temp.expl.spec]p6:
7699 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007700 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007701 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007702 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007703 // use occurs; no diagnostic is required.
7704 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007705 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007706 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007707 // Is there any previous explicit specialization declaration?
7708 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7709 Okay = true;
7710 break;
7711 }
7712 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007713
Douglas Gregorc854c662010-02-26 06:03:23 +00007714 if (!Okay) {
7715 SourceRange Range(TemplateNameLoc, RAngleLoc);
7716 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
7717 << Context.getTypeDeclType(Specialization) << Range;
7718
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007719 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00007720 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007721 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00007722 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00007723 return true;
7724 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007725 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007726
Douglas Gregor2208a292009-09-26 20:57:03 +00007727 // If this is not a friend, note that this is an explicit specialization.
7728 if (TUK != TUK_Friend)
7729 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00007730
7731 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00007732 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00007733 RecordDecl *Def = Specialization->getDefinition();
7734 NamedDecl *Hidden = nullptr;
7735 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
7736 SkipBody->ShouldSkip = true;
Richard Smithc4577662018-09-12 02:13:47 +00007737 SkipBody->Previous = Def;
Richard Smith858e0e02017-05-11 23:11:16 +00007738 makeMergedDefinitionVisible(Hidden);
Richard Smithc7e6ff02015-05-18 20:36:47 +00007739 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00007740 SourceRange Range(TemplateNameLoc, RAngleLoc);
Richard Smith792c22d2016-12-24 04:09:05 +00007741 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00007742 Diag(Def->getLocation(), diag::note_previous_definition);
7743 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00007744 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00007745 }
7746 }
7747
Erich Keanec480f302018-07-12 21:09:05 +00007748 ProcessDeclAttributeList(S, Specialization, Attr);
John McCall659a3372010-12-18 03:30:47 +00007749
Richard Smith034b94a2012-08-17 03:20:55 +00007750 // Add alignment attributes if necessary; these attributes are checked when
7751 // the ASTContext lays out the structure.
Richard Smithc4577662018-09-12 02:13:47 +00007752 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
Richard Smith034b94a2012-08-17 03:20:55 +00007753 AddAlignmentAttributesForRecord(Specialization);
7754 AddMsStructLayoutForRecord(Specialization);
7755 }
7756
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00007757 if (ModulePrivateLoc.isValid())
7758 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
7759 << (isPartialSpecialization? 1 : 0)
7760 << FixItHint::CreateRemoval(ModulePrivateLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00007761
Douglas Gregord56a91e2009-02-26 22:19:44 +00007762 // Build the fully-sugared type for this class template
7763 // specialization as the user wrote in the specialization
7764 // itself. This means that we'll pretty-print the type retrieved
7765 // from the specialization's declaration the way that the user
7766 // actually wrote the specialization, rather than formatting the
7767 // name based on the "canonical" representation used to store the
7768 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007769 TypeSourceInfo *WrittenTy
7770 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7771 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007772 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00007773 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007774 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007775 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007776
Douglas Gregor1e249f82009-02-25 22:18:32 +00007777 // C++ [temp.expl.spec]p9:
7778 // A template explicit specialization is in the scope of the
7779 // namespace in which the template was defined.
7780 //
7781 // We actually implement this paragraph where we set the semantic
7782 // context (in the creation of the ClassTemplateSpecializationDecl),
7783 // but we also maintain the lexical context where the actual
7784 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00007785 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00007786
Douglas Gregor67a65642009-02-17 23:15:12 +00007787 // We may be starting the definition of this specialization.
Richard Smithc4577662018-09-12 02:13:47 +00007788 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
Douglas Gregor67a65642009-02-17 23:15:12 +00007789 Specialization->startDefinition();
7790
Douglas Gregor2208a292009-09-26 20:57:03 +00007791 if (TUK == TUK_Friend) {
7792 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
7793 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00007794 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00007795 /*FIXME:*/KWLoc);
7796 Friend->setAccess(AS_public);
7797 CurContext->addDecl(Friend);
7798 } else {
7799 // Add the specialization into its lexical context, so that it can
7800 // be seen when iterating through the list of declarations in that
7801 // context. However, specializations are not found by name lookup.
7802 CurContext->addDecl(Specialization);
7803 }
Richard Smithc4577662018-09-12 02:13:47 +00007804
7805 if (SkipBody && SkipBody->ShouldSkip)
7806 return SkipBody->Previous;
7807
John McCall48871652010-08-21 09:40:31 +00007808 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00007809}
Douglas Gregor333489b2009-03-27 23:10:48 +00007810
John McCall48871652010-08-21 09:40:31 +00007811Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00007812 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00007813 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007814 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00007815 ActOnDocumentableDecl(NewDecl);
7816 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00007817}
7818
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007819/// Strips various properties off an implicit instantiation
John McCall4f7ced62010-02-11 01:33:53 +00007820/// that has just been explicitly specialized.
7821static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00007822 D->dropAttr<DLLImportAttr>();
7823 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00007824
Nico Webere4974382014-12-19 23:52:45 +00007825 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00007826 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00007827}
7828
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007829/// Compute the diagnostic location for an explicit instantiation
Nico Webera8f80b32012-01-09 19:52:25 +00007830// declaration or definition.
7831static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007832 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00007833 // Explicit instantiations following a specialization have no effect and
7834 // hence no PointOfInstantiation. In that case, walk decl backwards
7835 // until a valid name loc is found.
7836 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007837 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
7838 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00007839 PrevDiagLoc = Prev->getLocation();
7840 }
7841 assert(PrevDiagLoc.isValid() &&
7842 "Explicit instantiation without point of instantiation?");
7843 return PrevDiagLoc;
7844}
7845
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007846/// Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007847/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007848/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007849/// new specialization/instantiation will have any effect.
7850///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007851/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007852/// instantiation.
7853///
7854/// \param NewTSK the kind of the new explicit specialization or instantiation.
7855///
7856/// \param PrevDecl the previous declaration of the entity.
7857///
7858/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
7859///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007860/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007861/// declaration was instantiated (either implicitly or explicitly).
7862///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007863/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007864/// specialization or instantiation has no effect and should be ignored.
7865///
7866/// \returns true if there was an error that should prevent the introduction of
7867/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00007868bool
7869Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7870 TemplateSpecializationKind NewTSK,
7871 NamedDecl *PrevDecl,
7872 TemplateSpecializationKind PrevTSK,
7873 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007874 bool &HasNoEffect) {
7875 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007876
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007877 switch (NewTSK) {
7878 case TSK_Undeclared:
7879 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00007880 assert(
7881 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
7882 "previous declaration must be implicit!");
7883 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007884
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007885 case TSK_ExplicitSpecialization:
7886 switch (PrevTSK) {
7887 case TSK_Undeclared:
7888 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007889 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007890 // explicitly specialized or has merely been mentioned without any
7891 // instantiation.
7892 return false;
7893
7894 case TSK_ImplicitInstantiation:
7895 if (PrevPointOfInstantiation.isInvalid()) {
7896 // The declaration itself has not actually been instantiated, so it is
7897 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00007898 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007899 return false;
7900 }
7901 // Fall through
Galina Kistanova3779cb32017-06-07 06:25:05 +00007902 LLVM_FALLTHROUGH;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007903
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007904 case TSK_ExplicitInstantiationDeclaration:
7905 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007906 assert((PrevTSK == TSK_ImplicitInstantiation ||
7907 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007908 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007909
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007910 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007911 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007912 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007913 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007914 // implicit instantiation to take place, in every translation unit in
7915 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007916 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007917 // Is there any previous explicit specialization declaration?
7918 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
7919 return false;
7920 }
7921
Douglas Gregor1d957a32009-10-27 18:42:08 +00007922 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007923 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007924 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007925 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007926
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007927 return true;
7928 }
Galina Kistanova1d36e832017-06-08 18:20:32 +00007929 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007930
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007931 case TSK_ExplicitInstantiationDeclaration:
7932 switch (PrevTSK) {
7933 case TSK_ExplicitInstantiationDeclaration:
7934 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00007935 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007936 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007937
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007938 case TSK_Undeclared:
7939 case TSK_ImplicitInstantiation:
7940 // We're explicitly instantiating something that may have already been
7941 // implicitly instantiated; that's fine.
7942 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007943
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007944 case TSK_ExplicitSpecialization:
7945 // C++0x [temp.explicit]p4:
7946 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007947 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007948 // specialization for that template, the explicit instantiation has no
7949 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007950 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007951 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007952
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007953 case TSK_ExplicitInstantiationDefinition:
7954 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007955 // If an entity is the subject of both an explicit instantiation
7956 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007957 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007958 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00007959 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00007960
7961 // Explicit instantiations following a specialization have no effect and
7962 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
7963 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00007964 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7965 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007966 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007967 return false;
7968 }
Bruno Riccid8c17672018-12-21 20:38:06 +00007969 llvm_unreachable("Unexpected TemplateSpecializationKind!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007970
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007971 case TSK_ExplicitInstantiationDefinition:
7972 switch (PrevTSK) {
7973 case TSK_Undeclared:
7974 case TSK_ImplicitInstantiation:
7975 // We're explicitly instantiating something that may have already been
7976 // implicitly instantiated; that's fine.
7977 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007978
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007979 case TSK_ExplicitSpecialization:
7980 // C++ DR 259, C++0x [temp.explicit]p4:
7981 // For a given set of template parameters, if an explicit
7982 // instantiation of a template appears after a declaration of
7983 // an explicit specialization for that template, the explicit
7984 // instantiation has no effect.
Richard Smithe4caa482016-08-31 23:23:25 +00007985 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
Richard Smith0bf8a4922011-10-18 20:49:44 +00007986 << PrevDecl;
7987 Diag(PrevDecl->getLocation(),
7988 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007989 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007990 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007991
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007992 case TSK_ExplicitInstantiationDeclaration:
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00007993 // We're explicitly instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007994 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00007995
7996 // C++0x [temp.explicit]p4:
7997 // For a given set of template parameters, if an explicit instantiation
7998 // of a template appears after a declaration of an explicit
7999 // specialization for that template, the explicit instantiation has no
8000 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00008001 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00008002 // Is there any previous explicit specialization declaration?
8003 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
8004 HasNoEffect = true;
8005 break;
8006 }
8007 }
8008
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008009 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008010
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008011 case TSK_ExplicitInstantiationDefinition:
8012 // C++0x [temp.spec]p5:
8013 // For a given template and a given set of template-arguments,
8014 // - an explicit instantiation definition shall appear at most once
8015 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00008016
8017 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
8018 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00008019 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00008020 : diag::err_explicit_instantiation_duplicate)
8021 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00008022 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00008023 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008024 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008025 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008026 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008027 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008028
David Blaikie83d382b2011-09-23 05:06:16 +00008029 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008030}
8031
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008032/// Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00008033/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00008034///
James Dennettf14a6e52012-06-15 22:23:43 +00008035/// The only possible way to get a dependent function template specialization
8036/// is with a friend declaration, like so:
8037///
8038/// \code
8039/// template \<class T> void foo(T);
8040/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00008041/// friend void foo<>(T);
8042/// };
James Dennettf14a6e52012-06-15 22:23:43 +00008043/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00008044///
8045/// There really isn't any useful analysis we can do here, so we
8046/// just store the information.
8047bool
8048Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
8049 const TemplateArgumentListInfo &ExplicitTemplateArgs,
8050 LookupResult &Previous) {
8051 // Remove anything from Previous that isn't a function template in
8052 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00008053 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00008054 LookupResult::Filter F = Previous.makeFilter();
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008055 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
8056 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
John McCallb9c78482010-04-08 09:05:18 +00008057 while (F.hasNext()) {
8058 NamedDecl *D = F.next()->getUnderlyingDecl();
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008059 if (!isa<FunctionTemplateDecl>(D)) {
John McCallb9c78482010-04-08 09:05:18 +00008060 F.erase();
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008061 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
8062 continue;
8063 }
8064
8065 if (!FDLookupContext->InEnclosingNamespaceSetOf(
8066 D->getDeclContext()->getRedeclContext())) {
8067 F.erase();
8068 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
8069 continue;
8070 }
John McCallb9c78482010-04-08 09:05:18 +00008071 }
8072 F.done();
8073
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008074 if (Previous.empty()) {
8075 Diag(FD->getLocation(),
8076 diag::err_dependent_function_template_spec_no_match);
8077 for (auto &P : DiscardedCandidates)
8078 Diag(P.second->getLocation(),
8079 diag::note_dependent_function_template_spec_discard_reason)
8080 << P.first;
8081 return true;
8082 }
John McCallb9c78482010-04-08 09:05:18 +00008083
8084 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
8085 ExplicitTemplateArgs);
8086 return false;
8087}
8088
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008089/// Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008090/// specialization.
8091///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008092/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008093/// explicit function template specialization. On successful completion,
8094/// the function declaration \p FD will become a function template
8095/// specialization.
8096///
8097/// \param FD the function declaration, which will be updated to become a
8098/// function template specialization.
8099///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008100/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
8101/// if any. Note that this may be valid info even when 0 arguments are
8102/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
8103/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008104///
Francois Pichet3a44e432011-07-08 06:21:47 +00008105/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008106/// this function specialization.
Richard Smith8ce732b2019-01-07 06:00:46 +00008107///
8108/// \param QualifiedFriend whether this is a lookup for a qualified friend
8109/// declaration with no explicit template argument list that might be
8110/// befriending a function template specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008111bool Sema::CheckFunctionTemplateSpecialization(
8112 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smith8ce732b2019-01-07 06:00:46 +00008113 LookupResult &Previous, bool QualifiedFriend) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008114 // The set of function template specializations that could match this
8115 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00008116 UnresolvedSet<8> Candidates;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008117 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
8118 /*ForTakingAddress=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008119
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008120 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
8121 ConvertedTemplateArgs;
8122
Sebastian Redl50c68252010-08-31 00:36:30 +00008123 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00008124 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8125 I != E; ++I) {
8126 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
8127 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008128 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008129 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00008130 if (!FDLookupContext->InEnclosingNamespaceSetOf(
8131 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008132 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008133
Richard Smith574f4f62013-01-14 05:37:29 +00008134 // When matching a constexpr member function template specialization
8135 // against the primary template, we don't yet know whether the
8136 // specialization has an implicit 'const' (because we don't know whether
8137 // it will be a static member function until we know which template it
8138 // specializes), so adjust it now assuming it specializes this template.
8139 QualType FT = FD->getType();
8140 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00008141 CXXMethodDecl *OldMD =
8142 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00008143 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00008144 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00008145 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00008146 EPI.TypeQuals.addConst();
Alp Toker314cc812014-01-25 16:55:45 +00008147 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00008148 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00008149 }
8150 }
8151
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008152 TemplateArgumentListInfo Args;
8153 if (ExplicitTemplateArgs)
8154 Args = *ExplicitTemplateArgs;
8155
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008156 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008157 // A trailing template-argument can be left unspecified in the
8158 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008159 // provided it can be deduced from the function argument type.
8160 // Perform template argument deduction to determine whether we may be
8161 // specializing this template.
8162 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00008163 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00008164 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00008165 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
8166 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
Richard Smithc2bebe92016-05-11 20:37:46 +00008167 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
8168 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008169 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008170 // that we can provide nifty diagnostics.
Richard Smithc2bebe92016-05-11 20:37:46 +00008171 FailedCandidates.addCandidate().set(
8172 I.getPair(), FunTmpl->getTemplatedDecl(),
8173 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008174 (void)TDK;
8175 continue;
8176 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008177
Artem Belevich64135c32016-12-08 19:38:13 +00008178 // Target attributes are part of the cuda function signature, so
8179 // the deduced template's cuda target must match that of the
8180 // specialization. Given that C++ template deduction does not
8181 // take target attributes into account, we reject candidates
8182 // here that have a different target.
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008183 if (LangOpts.CUDA &&
Artem Belevich64135c32016-12-08 19:38:13 +00008184 IdentifyCUDATarget(Specialization,
8185 /* IgnoreImplicitHDAttributes = */ true) !=
8186 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttributes = */ true)) {
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008187 FailedCandidates.addCandidate().set(
8188 I.getPair(), FunTmpl->getTemplatedDecl(),
8189 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
8190 continue;
8191 }
8192
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008193 // Record this candidate.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008194 if (ExplicitTemplateArgs)
8195 ConvertedTemplateArgs[Specialization] = std::move(Args);
John McCall58cc69d2010-01-27 01:50:18 +00008196 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008197 }
8198 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008199
Richard Smith8ce732b2019-01-07 06:00:46 +00008200 // For a qualified friend declaration (with no explicit marker to indicate
8201 // that a template specialization was intended), note all (template and
8202 // non-template) candidates.
8203 if (QualifiedFriend && Candidates.empty()) {
8204 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
8205 << FD->getDeclName() << FDLookupContext;
8206 // FIXME: We should form a single candidate list and diagnose all
8207 // candidates at once, to get proper sorting and limiting.
8208 for (auto *OldND : Previous) {
8209 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
8210 NoteOverloadCandidate(OldND, OldFD, FD->getType(), false);
8211 }
8212 FailedCandidates.NoteCandidates(*this, FD->getLocation());
8213 return true;
8214 }
8215
Douglas Gregor5de279c2009-09-26 03:41:46 +00008216 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008217 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith8ce732b2019-01-07 06:00:46 +00008218 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
Larisse Voufo98b20f12013-07-19 23:00:19 +00008219 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
8220 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00008221 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00008222 PDiag(diag::note_function_template_spec_matched));
8223
John McCall58cc69d2010-01-27 01:50:18 +00008224 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008225 return true;
John McCall58cc69d2010-01-27 01:50:18 +00008226
8227 // Ignore access information; it doesn't figure into redeclaration checking.
8228 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00008229
8230 FunctionTemplateSpecializationInfo *SpecInfo
8231 = Specialization->getTemplateSpecializationInfo();
8232 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00008233
8234 // Note: do not overwrite location info if previous template
8235 // specialization kind was explicit.
8236 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00008237 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00008238 Specialization->setLocation(FD->getLocation());
Richard Smith54f04402017-05-18 02:29:20 +00008239 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
Richard Smith5b8b3db2012-02-20 23:28:05 +00008240 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
8241 // function can differ from the template declaration with respect to
8242 // the constexpr specifier.
Richard Smith77e9e842017-05-09 23:02:10 +00008243 // FIXME: We need an update record for this AST mutation.
8244 // FIXME: What if there are multiple such prior declarations (for instance,
8245 // from different modules)?
Richard Smith5b8b3db2012-02-20 23:28:05 +00008246 Specialization->setConstexpr(FD->isConstexpr());
8247 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008248
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008249 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00008250 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00008251
8252 // If this is a friend declaration, then we're not really declaring
8253 // an explicit specialization.
8254 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008255
Douglas Gregor54888652009-10-07 00:13:32 +00008256 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00008257 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008258 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00008259 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008260 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00008261 false))
Douglas Gregor54888652009-10-07 00:13:32 +00008262 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00008263
8264 // C++ [temp.expl.spec]p6:
8265 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008266 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00008267 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008268 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00008269 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00008270 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00008271 if (!isFriend &&
8272 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00008273 TSK_ExplicitSpecialization,
8274 Specialization,
8275 SpecInfo->getTemplateSpecializationKind(),
8276 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008277 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00008278 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008279
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008280 // Mark the prior declaration as an explicit specialization, so that later
8281 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00008282 if (!isFriend) {
Faisal Vali81a88be2016-06-14 03:23:15 +00008283 // Since explicit specializations do not inherit '=delete' from their
8284 // primary function template - check if the 'specialization' that was
8285 // implicitly generated (during template argument deduction for partial
8286 // ordering) from the most specialized of all the function templates that
8287 // 'FD' could have been specializing, has a 'deleted' definition. If so,
8288 // first check that it was implicitly generated during template argument
8289 // deduction by making sure it wasn't referenced, and then reset the deleted
8290 // flag to not-deleted, so that we can inherit that information from 'FD'.
8291 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
8292 !Specialization->getCanonicalDecl()->isReferenced()) {
Richard Smith77e9e842017-05-09 23:02:10 +00008293 // FIXME: This assert will not hold in the presence of modules.
Faisal Vali81a88be2016-06-14 03:23:15 +00008294 assert(
8295 Specialization->getCanonicalDecl() == Specialization &&
8296 "This must be the only existing declaration of this specialization");
Richard Smith77e9e842017-05-09 23:02:10 +00008297 // FIXME: We need an update record for this AST mutation.
Faisal Vali81a88be2016-06-14 03:23:15 +00008298 Specialization->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008299 }
Richard Smith54f04402017-05-18 02:29:20 +00008300 // FIXME: We need an update record for this AST mutation.
John McCall816d75b2010-03-24 07:46:06 +00008301 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00008302 MarkUnusedFileScopedDecl(Specialization);
8303 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008304
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008305 // Turn the given function declaration into a function template
8306 // specialization, with the template arguments from the previous
8307 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008308 // Take copies of (semantic and syntactic) template argument lists.
8309 const TemplateArgumentList* TemplArgs = new (Context)
8310 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008311 FD->setFunctionTemplateSpecialization(
8312 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
8313 SpecInfo->getTemplateSpecializationKind(),
8314 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008315
Artem Belevich64135c32016-12-08 19:38:13 +00008316 // A function template specialization inherits the target attributes
8317 // of its template. (We require the attributes explicitly in the
8318 // code to match, but a template may have implicit attributes by
8319 // virtue e.g. of being constexpr, and it passes these implicit
8320 // attributes on to its specializations.)
8321 if (LangOpts.CUDA)
8322 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
8323
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008324 // The "previous declaration" for this function template specialization is
8325 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00008326 Previous.clear();
8327 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008328 return false;
8329}
8330
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008331/// Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008332/// specialization.
8333///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008334/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008335/// explicit member function specialization. On successful completion,
8336/// the function declaration \p FD will become a member function
8337/// specialization.
8338///
Douglas Gregor86d142a2009-10-08 07:24:58 +00008339/// \param Member the member declaration, which will be updated to become a
8340/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008341///
John McCall1f82f242009-11-18 22:49:29 +00008342/// \param Previous the set of declarations, one of which may be specialized
8343/// by this function specialization; the set will be modified to contain the
8344/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008345bool
John McCall1f82f242009-11-18 22:49:29 +00008346Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008347 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00008348
Douglas Gregor86d142a2009-10-08 07:24:58 +00008349 // Try to find the member we are instantiating.
Richard Smith22e7cc62016-05-24 00:01:49 +00008350 NamedDecl *FoundInstantiation = nullptr;
Craig Topperc3ec1492014-05-26 06:22:03 +00008351 NamedDecl *Instantiation = nullptr;
8352 NamedDecl *InstantiatedFrom = nullptr;
8353 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00008354
John McCall1f82f242009-11-18 22:49:29 +00008355 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008356 // Nowhere to look anyway.
8357 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008358 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8359 I != E; ++I) {
8360 NamedDecl *D = (*I)->getUnderlyingDecl();
8361 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00008362 QualType Adjusted = Function->getType();
8363 if (!hasExplicitCallingConv(Adjusted))
8364 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
Richard Smith4576a772018-09-10 06:35:32 +00008365 // This doesn't handle deduced return types, but both function
8366 // declarations should be undeduced at this point.
Rafael Espindola66747222013-12-10 00:59:31 +00008367 if (Context.hasSameType(Adjusted, Method->getType())) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008368 FoundInstantiation = *I;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008369 Instantiation = Method;
8370 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008371 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008372 break;
8373 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008374 }
8375 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00008376 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008377 VarDecl *PrevVar;
8378 if (Previous.isSingleResult() &&
8379 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00008380 if (PrevVar->isStaticDataMember()) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008381 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00008382 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008383 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008384 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008385 }
8386 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008387 CXXRecordDecl *PrevRecord;
8388 if (Previous.isSingleResult() &&
8389 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008390 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00008391 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008392 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008393 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008394 }
Richard Smith7d137e32012-03-23 03:33:32 +00008395 } else if (isa<EnumDecl>(Member)) {
8396 EnumDecl *PrevEnum;
8397 if (Previous.isSingleResult() &&
8398 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008399 FoundInstantiation = Previous.getRepresentativeDecl();
Richard Smith7d137e32012-03-23 03:33:32 +00008400 Instantiation = PrevEnum;
8401 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
8402 MSInfo = PrevEnum->getMemberSpecializationInfo();
8403 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008404 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008405
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008406 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008407 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008408 // specializations are always out-of-line, the caller will complain about
8409 // this mismatch later.
8410 return false;
8411 }
John McCalle820e5e2010-04-13 20:37:33 +00008412
Richard Smith77e9e842017-05-09 23:02:10 +00008413 // A member specialization in a friend declaration isn't really declaring
8414 // an explicit specialization, just identifying a specific (possibly implicit)
8415 // specialization. Don't change the template specialization kind.
8416 //
8417 // FIXME: Is this really valid? Other compilers reject.
John McCalle820e5e2010-04-13 20:37:33 +00008418 if (Member->getFriendObjectKind() != Decl::FOK_None) {
8419 // Preserve instantiation information.
8420 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
8421 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
8422 cast<CXXMethodDecl>(InstantiatedFrom),
8423 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
8424 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
8425 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
8426 cast<CXXRecordDecl>(InstantiatedFrom),
8427 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
8428 }
8429
8430 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00008431 Previous.addDecl(FoundInstantiation);
John McCalle820e5e2010-04-13 20:37:33 +00008432 return false;
8433 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008434
Douglas Gregor86d142a2009-10-08 07:24:58 +00008435 // Make sure that this is a specialization of a member.
8436 if (!InstantiatedFrom) {
8437 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
8438 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008439 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
8440 return true;
8441 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008442
Douglas Gregor06db9f52009-10-12 20:18:28 +00008443 // C++ [temp.expl.spec]p6:
8444 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00008445 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00008446 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008447 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00008448 // use occurs; no diagnostic is required.
8449 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00008450
Abramo Bagnara8075c852010-06-12 07:44:57 +00008451 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00008452 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
8453 TSK_ExplicitSpecialization,
8454 Instantiation,
8455 MSInfo->getTemplateSpecializationKind(),
8456 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008457 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00008458 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008459
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008460 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008461 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00008462 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008463 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00008464 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008465 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00008466
Richard Smith77e9e842017-05-09 23:02:10 +00008467 // Note that this member specialization is an "instantiation of" the
8468 // corresponding member of the original template.
8469 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008470 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
8471 if (InstantiationFunction->getTemplateSpecializationKind() ==
8472 TSK_ImplicitInstantiation) {
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008473 // Explicit specializations of member functions of class templates do not
8474 // inherit '=delete' from the member function they are specializing.
8475 if (InstantiationFunction->isDeleted()) {
Richard Smith77e9e842017-05-09 23:02:10 +00008476 // FIXME: This assert will not hold in the presence of modules.
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008477 assert(InstantiationFunction->getCanonicalDecl() ==
8478 InstantiationFunction);
Richard Smith77e9e842017-05-09 23:02:10 +00008479 // FIXME: We need an update record for this AST mutation.
Richard Smith5f274382016-09-28 23:55:27 +00008480 InstantiationFunction->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008481 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008482 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008483
Richard Smith77e9e842017-05-09 23:02:10 +00008484 MemberFunction->setInstantiationOfMemberFunction(
8485 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8486 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
8487 MemberVar->setInstantiationOfStaticDataMember(
Larisse Voufo39a1e502013-08-06 01:03:05 +00008488 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Richard Smith77e9e842017-05-09 23:02:10 +00008489 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
8490 MemberClass->setInstantiationOfMemberClass(
8491 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8492 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
8493 MemberEnum->setInstantiationOfMemberEnum(
Richard Smith7d137e32012-03-23 03:33:32 +00008494 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Richard Smith77e9e842017-05-09 23:02:10 +00008495 } else {
8496 llvm_unreachable("unknown member specialization kind");
Douglas Gregor86d142a2009-10-08 07:24:58 +00008497 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008498
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008499 // Save the caller the trouble of having to figure out which declaration
8500 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00008501 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00008502 Previous.addDecl(FoundInstantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008503 return false;
8504}
8505
Richard Smith77e9e842017-05-09 23:02:10 +00008506/// Complete the explicit specialization of a member of a class template by
8507/// updating the instantiated member to be marked as an explicit specialization.
8508///
8509/// \param OrigD The member declaration instantiated from the template.
8510/// \param Loc The location of the explicit specialization of the member.
8511template<typename DeclT>
8512static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
8513 SourceLocation Loc) {
8514 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
8515 return;
8516
8517 // FIXME: Inform AST mutation listeners of this AST mutation.
8518 // FIXME: If there are multiple in-class declarations of the member (from
8519 // multiple modules, or a declaration and later definition of a member type),
8520 // should we update all of them?
8521 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
8522 OrigD->setLocation(Loc);
8523}
8524
8525void Sema::CompleteMemberSpecialization(NamedDecl *Member,
8526 LookupResult &Previous) {
8527 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
8528 if (Instantiation == Member)
8529 return;
8530
8531 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
8532 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
8533 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
8534 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
8535 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
8536 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
8537 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
8538 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
8539 else
8540 llvm_unreachable("unknown member specialization kind");
8541}
8542
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008543/// Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008544///
8545/// \returns true if a serious error occurs, false otherwise.
8546static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00008547 SourceLocation InstLoc,
8548 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00008549 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
8550 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008551
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008552 if (CurContext->isRecord()) {
8553 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
8554 << D;
8555 return true;
8556 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008557
Richard Smith050d2612011-10-18 02:28:33 +00008558 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008559 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00008560 // template. If the name declared in the explicit instantiation is an
8561 // unqualified name, the explicit instantiation shall appear in the
8562 // namespace where its template is declared or, if that namespace is inline
8563 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008564 //
8565 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00008566 if (WasQualifiedName) {
8567 if (CurContext->Encloses(OrigContext))
8568 return false;
8569 } else {
8570 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
8571 return false;
8572 }
8573
8574 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
8575 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008576 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008577 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008578 diag::err_explicit_instantiation_out_of_scope :
8579 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008580 << D << NS;
8581 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008582 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008583 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008584 diag::err_explicit_instantiation_unqualified_wrong_namespace :
8585 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
8586 << D << NS;
8587 } else
8588 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008589 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008590 diag::err_explicit_instantiation_must_be_global :
8591 diag::warn_explicit_instantiation_must_be_global_0x)
8592 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00008593 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008594 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00008595}
8596
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008597/// Determine whether the given scope specifier has a template-id in it.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008598static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
8599 if (!SS.isSet())
8600 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008601
Richard Smith050d2612011-10-18 02:28:33 +00008602 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008603 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008604 // or a static data member of a class template specialization, the name of
8605 // the class template specialization in the qualified-id for the member
8606 // name shall be a simple-template-id.
8607 //
8608 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00008609 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
8610 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00008611 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00008612 if (isa<TemplateSpecializationType>(T))
8613 return true;
8614
8615 return false;
8616}
8617
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008618/// Make a dllexport or dllimport attr on a class template specialization take
8619/// effect.
8620static void dllExportImportClassTemplateSpecialization(
8621 Sema &S, ClassTemplateSpecializationDecl *Def) {
8622 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
8623 assert(A && "dllExportImportClassTemplateSpecialization called "
8624 "on Def without dllexport or dllimport");
8625
8626 // We reject explicit instantiations in class scope, so there should
8627 // never be any delayed exported classes to worry about.
8628 assert(S.DelayedDllExportClasses.empty() &&
8629 "delayed exports present at explicit instantiation");
8630 S.checkClassLevelDLLAttribute(Def);
8631
8632 // Propagate attribute to base class templates.
8633 for (auto &B : Def->bases()) {
8634 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
8635 B.getType()->getAsCXXRecordDecl()))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008636 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getBeginLoc());
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008637 }
8638
8639 S.referenceDLLExportedClassMethods();
8640}
8641
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008642// Explicit instantiation of a class template specialization
Erich Keanec480f302018-07-12 21:09:05 +00008643DeclResult Sema::ActOnExplicitInstantiation(
8644 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
8645 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
8646 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
8647 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
8648 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
Douglas Gregora1f49972009-05-13 00:25:59 +00008649 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00008650 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00008651 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00008652 // Check that the specialization uses the same tag kind as the
8653 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00008654 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8655 assert(Kind != TTK_Enum &&
8656 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00008657
Richard Trieu265c3442016-04-05 21:13:54 +00008658 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
8659
8660 if (!ClassTemplate) {
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00008661 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
8662 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
Richard Trieu265c3442016-04-05 21:13:54 +00008663 Diag(TD->getLocation(), diag::note_previous_use);
Richard Smith392497b2013-06-22 22:03:31 +00008664 return true;
8665 }
8666
Douglas Gregord9034f02009-05-14 16:41:31 +00008667 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00008668 Kind, /*isDefinition*/false, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00008669 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00008670 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00008671 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00008672 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00008673 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00008674 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00008675 diag::note_previous_use);
8676 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8677 }
8678
Douglas Gregore47f5a72009-10-14 23:41:34 +00008679 // C++0x [temp.explicit]p2:
8680 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008681 // definition and an explicit instantiation declaration. An explicit
8682 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00008683 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
8684 ? TSK_ExplicitInstantiationDefinition
8685 : TSK_ExplicitInstantiationDeclaration;
8686
8687 if (TSK == TSK_ExplicitInstantiationDeclaration) {
8688 // Check for dllexport class template instantiation declarations.
Erich Keanee891aa92018-07-13 15:07:47 +00008689 for (const ParsedAttr &AL : Attr) {
8690 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
Hans Wennborgfd76d912015-01-15 21:18:30 +00008691 Diag(ExternLoc,
8692 diag::warn_attribute_dllexport_explicit_instantiation_decl);
Erich Keanec480f302018-07-12 21:09:05 +00008693 Diag(AL.getLoc(), diag::note_attribute);
Hans Wennborgfd76d912015-01-15 21:18:30 +00008694 break;
8695 }
8696 }
8697
8698 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
8699 Diag(ExternLoc,
8700 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8701 Diag(A->getLocation(), diag::note_attribute);
8702 }
8703 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008704
Hans Wennborga86a83b2016-05-26 19:42:56 +00008705 // In MSVC mode, dllimported explicit instantiation definitions are treated as
8706 // instantiation declarations for most purposes.
8707 bool DLLImportExplicitInstantiationDef = false;
8708 if (TSK == TSK_ExplicitInstantiationDefinition &&
8709 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
8710 // Check for dllimport class template instantiation definitions.
8711 bool DLLImport =
8712 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
Erich Keanee891aa92018-07-13 15:07:47 +00008713 for (const ParsedAttr &AL : Attr) {
8714 if (AL.getKind() == ParsedAttr::AT_DLLImport)
Hans Wennborga86a83b2016-05-26 19:42:56 +00008715 DLLImport = true;
Erich Keanee891aa92018-07-13 15:07:47 +00008716 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
Hans Wennborga86a83b2016-05-26 19:42:56 +00008717 // dllexport trumps dllimport here.
8718 DLLImport = false;
8719 break;
8720 }
8721 }
8722 if (DLLImport) {
8723 TSK = TSK_ExplicitInstantiationDeclaration;
8724 DLLImportExplicitInstantiationDef = true;
8725 }
8726 }
8727
Douglas Gregora1f49972009-05-13 00:25:59 +00008728 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00008729 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00008730 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00008731
8732 // Check that the template argument list is well-formed for this
8733 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008734 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00008735 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
8736 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00008737 return true;
8738
Douglas Gregora1f49972009-05-13 00:25:59 +00008739 // Find the class template specialization declaration that
8740 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00008741 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00008742 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00008743 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00008744
Abramo Bagnara8075c852010-06-12 07:44:57 +00008745 TemplateSpecializationKind PrevDecl_TSK
8746 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
8747
Douglas Gregor54888652009-10-07 00:13:32 +00008748 // C++0x [temp.explicit]p2:
8749 // [...] An explicit instantiation shall appear in an enclosing
8750 // namespace of its template. [...]
8751 //
8752 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008753 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
8754 SS.isSet()))
8755 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008756
Craig Topperc3ec1492014-05-26 06:22:03 +00008757 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00008758
Abramo Bagnara8075c852010-06-12 07:44:57 +00008759 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00008760 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00008761 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00008762 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00008763 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008764 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00008765 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00008766
Abramo Bagnara8075c852010-06-12 07:44:57 +00008767 // Even though HasNoEffect == true means that this explicit instantiation
8768 // has no effect on semantics, we go on to put its syntax in the AST.
8769
8770 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
8771 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008772 // Since the only prior class template specialization with these
8773 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00008774 // declaration node as our own, updating the source location
8775 // for the template name to reflect our new declaration.
8776 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008777 Specialization = PrevDecl;
8778 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00008779 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008780 }
Hans Wennborga86a83b2016-05-26 19:42:56 +00008781
8782 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
8783 DLLImportExplicitInstantiationDef) {
8784 // The new specialization might add a dllimport attribute.
8785 HasNoEffect = false;
8786 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00008787 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00008788
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008789 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00008790 // Create a new class template specialization declaration node for
8791 // this explicit specialization.
8792 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00008793 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00008794 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00008795 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00008796 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00008797 Converted,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008798 PrevDecl);
Bruno Ricci4224c872018-12-21 14:35:24 +00008799 SetNestedNameSpecifier(*this, Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00008800
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00008801 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00008802 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00008803 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008804 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008805 }
8806
8807 // Build the fully-sugared type for this explicit instantiation as
8808 // the user wrote in the explicit instantiation itself. This means
8809 // that we'll pretty-print the type retrieved from the
8810 // specialization's declaration the way that the user actually wrote
8811 // the explicit instantiation, rather than formatting the name based
8812 // on the "canonical" representation used to store the template
8813 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00008814 TypeSourceInfo *WrittenTy
8815 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
8816 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00008817 Context.getTypeDeclType(Specialization));
8818 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00008819
Abramo Bagnara8075c852010-06-12 07:44:57 +00008820 // Set source locations for keywords.
8821 Specialization->setExternLoc(ExternLoc);
8822 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00008823 Specialization->setBraceRange(SourceRange());
Abramo Bagnara8075c852010-06-12 07:44:57 +00008824
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00008825 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
Erich Keanec480f302018-07-12 21:09:05 +00008826 ProcessDeclAttributeList(S, Specialization, Attr);
Rafael Espindola0b062072012-01-03 06:04:21 +00008827
Abramo Bagnara8075c852010-06-12 07:44:57 +00008828 // Add the explicit instantiation into its lexical context. However,
8829 // since explicit instantiations are never found by name lookup, we
8830 // just put it into the declaration context directly.
8831 Specialization->setLexicalDeclContext(CurContext);
8832 CurContext->addDecl(Specialization);
8833
8834 // Syntax is now OK, so return if it has no other effect on semantics.
8835 if (HasNoEffect) {
8836 // Set the template specialization kind.
8837 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00008838 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00008839 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008840
8841 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00008842 // A definition of a class template or class member template
8843 // shall be in scope at the point of the explicit instantiation of
8844 // the class template or class member template.
8845 //
8846 // This check comes when we actually try to perform the
8847 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00008848 ClassTemplateSpecializationDecl *Def
8849 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008850 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00008851 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00008852 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008853 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00008854 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008855 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
8856 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00008857
Douglas Gregor1d957a32009-10-27 18:42:08 +00008858 // Instantiate the members of this class template specialization.
8859 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008860 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00008861 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008862 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008863 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
8864 // TSK_ExplicitInstantiationDefinition
8865 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborga86a83b2016-05-26 19:42:56 +00008866 (TSK == TSK_ExplicitInstantiationDefinition ||
8867 DLLImportExplicitInstantiationDef)) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00008868 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008869 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00008870
Hans Wennborgc0875502015-06-09 00:39:05 +00008871 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
Shoaib Meenaiab3f96c2016-11-09 23:52:20 +00008872 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8873 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
Hans Wennborgc0875502015-06-09 00:39:05 +00008874 // In the MS ABI, an explicit instantiation definition can add a dll
8875 // attribute to a template with a previous instantiation declaration.
8876 // MinGW doesn't allow this.
Hans Wennborg17f9b442015-05-27 00:06:45 +00008877 auto *A = cast<InheritableAttr>(
8878 getDLLAttr(Specialization)->clone(getASTContext()));
8879 A->setInherited(true);
8880 Def->addAttr(A);
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008881 dllExportImportClassTemplateSpecialization(*this, Def);
Hans Wennborg17f9b442015-05-27 00:06:45 +00008882 }
8883 }
8884
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008885 // Fix a TSK_ImplicitInstantiation followed by a
8886 // TSK_ExplicitInstantiationDefinition
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00008887 bool NewlyDLLExported =
8888 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
8889 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008890 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8891 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
8892 // In the MS ABI, an explicit instantiation definition can add a dll
8893 // attribute to a template with a previous implicit instantiation.
8894 // MinGW doesn't allow this. We limit clang to only adding dllexport, to
8895 // avoid potentially strange codegen behavior. For example, if we extend
8896 // this conditional to dllimport, and we have a source file calling a
8897 // method on an implicitly instantiated template class instance and then
8898 // declaring a dllimport explicit instantiation definition for the same
8899 // template class, the codegen for the method call will not respect the
8900 // dllimport, while it will with cl. The Def will already have the DLL
8901 // attribute, since the Def and Specialization will be the same in the
8902 // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
8903 // attribute to the Specialization; we just need to make it take effect.
8904 assert(Def == Specialization &&
8905 "Def and Specialization should match for implicit instantiation");
8906 dllExportImportClassTemplateSpecialization(*this, Def);
8907 }
8908
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00008909 // Set the template specialization kind. Make sure it is set before
8910 // instantiating the members which will trigger ASTConsumer callbacks.
8911 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregor12e49d32009-10-15 22:53:21 +00008912 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00008913 } else {
8914
8915 // Set the template specialization kind.
8916 Specialization->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00008917 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008918
John McCall48871652010-08-21 09:40:31 +00008919 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00008920}
8921
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008922// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00008923DeclResult
Erich Keanec480f302018-07-12 21:09:05 +00008924Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
8925 SourceLocation TemplateLoc, unsigned TagSpec,
8926 SourceLocation KWLoc, CXXScopeSpec &SS,
8927 IdentifierInfo *Name, SourceLocation NameLoc,
8928 const ParsedAttributesView &Attr) {
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008929
Douglas Gregord6ab8742009-05-28 23:31:59 +00008930 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00008931 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00008932 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00008933 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00008934 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00008935 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00008936 SourceLocation(), false, TypeResult(),
Akira Hatanaka12ddcee2017-06-26 18:46:12 +00008937 /*IsTypeSpecifier*/false,
8938 /*IsTemplateParamOrArg*/false);
John McCall7f41d982009-09-11 04:59:25 +00008939 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
8940
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008941 if (!TagD)
8942 return true;
8943
John McCall48871652010-08-21 09:40:31 +00008944 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00008945 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008946
Douglas Gregorb8006faf2009-05-27 17:30:49 +00008947 if (Tag->isInvalidDecl())
8948 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008949
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008950 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
8951 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
8952 if (!Pattern) {
8953 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
8954 << Context.getTypeDeclType(Record);
8955 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
8956 return true;
8957 }
8958
Douglas Gregore47f5a72009-10-14 23:41:34 +00008959 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008960 // If the explicit instantiation is for a class or member class, the
8961 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00008962 // simple-template-id.
8963 //
8964 // C++98 has the same restriction, just worded differently.
8965 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00008966 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008967 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008968
Douglas Gregore47f5a72009-10-14 23:41:34 +00008969 // C++0x [temp.explicit]p2:
8970 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008971 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00008972 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00008973 TemplateSpecializationKind TSK
8974 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8975 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008976
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008977 // C++0x [temp.explicit]p2:
8978 // [...] An explicit instantiation shall appear in an enclosing
8979 // namespace of its template. [...]
8980 //
8981 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008982 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008983
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008984 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008985 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00008986 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008987 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00008988 PrevDecl = Record;
8989 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008990 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00008991 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008992 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008993 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008994 PrevDecl,
8995 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008996 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008997 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008998 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00008999 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009000 return TagD;
9001 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009002
Douglas Gregor12e49d32009-10-15 22:53:21 +00009003 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009004 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00009005 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00009006 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009007 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00009008 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009009 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009010 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00009011 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00009012 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
9013 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00009014 Diag(Pattern->getLocation(), diag::note_forward_declaration)
9015 << Pattern;
9016 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00009017 } else {
9018 if (InstantiateClass(NameLoc, Record, Def,
9019 getTemplateInstantiationArgs(Record),
9020 TSK))
9021 return true;
9022
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009023 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00009024 if (!RecordDef)
9025 return true;
9026 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009027 }
9028
Douglas Gregor1d957a32009-10-27 18:42:08 +00009029 // Instantiate all of the members of the class.
9030 InstantiateClassMembers(NameLoc, RecordDef,
9031 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009032
Douglas Gregor88d292c2010-05-13 16:44:06 +00009033 if (TSK == TSK_ExplicitInstantiationDefinition)
9034 MarkVTableUsed(NameLoc, RecordDef, true);
9035
Mike Stump87c57ac2009-05-16 07:39:55 +00009036 // FIXME: We don't have any representation for explicit instantiations of
9037 // member classes. Such a representation is not needed for compilation, but it
9038 // should be available for clients that want to see all of the declarations in
9039 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009040 return TagD;
9041}
9042
John McCallfaf5fb42010-08-26 23:41:50 +00009043DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
9044 SourceLocation ExternLoc,
9045 SourceLocation TemplateLoc,
9046 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00009047 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009048 // TODO: check if/when DNInfo should replace Name.
9049 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9050 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00009051 if (!Name) {
9052 if (!D.isInvalidType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009053 Diag(D.getDeclSpec().getBeginLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00009054 diag::err_explicit_instantiation_requires_name)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009055 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009056
Douglas Gregor450f00842009-09-25 18:43:00 +00009057 return true;
9058 }
9059
9060 // The scope passed in may not be a decl scope. Zip up the scope tree until
9061 // we find one that is.
9062 while ((S->getFlags() & Scope::DeclScope) == 0 ||
9063 (S->getFlags() & Scope::TemplateParamScope) != 0)
9064 S = S->getParent();
9065
9066 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00009067 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
9068 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00009069 if (R.isNull())
9070 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009071
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009072 // C++ [dcl.stc]p1:
Simon Pilgrim6905d222016-12-30 22:55:33 +00009073 // A storage-class-specifier shall not be specified in [...] an explicit
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009074 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00009075 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00009076 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
9077 << Name;
9078 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009079 } else if (D.getDeclSpec().getStorageClassSpec()
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009080 != DeclSpec::SCS_unspecified) {
9081 // Complain about then remove the storage class specifier.
9082 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
9083 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009084
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009085 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00009086 }
9087
Douglas Gregor3c74d412009-10-14 20:14:33 +00009088 // C++0x [temp.explicit]p1:
9089 // [...] An explicit instantiation of a function template shall not use the
9090 // inline or constexpr specifiers.
9091 // Presumably, this also applies to member functions of class templates as
9092 // well.
Richard Smith83c19292011-10-18 03:44:03 +00009093 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009094 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009095 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00009096 diag::err_explicit_instantiation_inline :
9097 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00009098 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00009099 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00009100 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
9101 // not already specified.
9102 Diag(D.getDeclSpec().getConstexprSpecLoc(),
9103 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009104
Richard Smith19a311a2017-02-09 22:47:51 +00009105 // A deduction guide is not on the list of entities that can be explicitly
9106 // instantiated.
9107 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009108 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
9109 << /*explicit instantiation*/ 0;
Richard Smith19a311a2017-02-09 22:47:51 +00009110 return true;
9111 }
9112
Douglas Gregore47f5a72009-10-14 23:41:34 +00009113 // C++0x [temp.explicit]p2:
9114 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009115 // definition and an explicit instantiation declaration. An explicit
9116 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00009117 TemplateSpecializationKind TSK
9118 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
9119 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009120
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009121 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00009122 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00009123
9124 if (!R->isFunctionType()) {
9125 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009126 // A [...] static data member of a class template can be explicitly
9127 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00009128 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00009129 // C++1y [temp.explicit]p1:
9130 // A [...] variable [...] template specialization can be explicitly
9131 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00009132 if (Previous.isAmbiguous())
9133 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009134
John McCall67c00872009-12-02 08:25:40 +00009135 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00009136 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009137
Larisse Voufo39a1e502013-08-06 01:03:05 +00009138 if (!PrevTemplate) {
9139 if (!Prev || !Prev->isStaticDataMember()) {
9140 // We expect to see a data data member here.
9141 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
9142 << Name;
9143 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9144 P != PEnd; ++P)
9145 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
9146 return true;
9147 }
9148
9149 if (!Prev->getInstantiatedFromStaticDataMember()) {
9150 // FIXME: Check for explicit specialization?
9151 Diag(D.getIdentifierLoc(),
9152 diag::err_explicit_instantiation_data_member_not_instantiated)
9153 << Prev;
9154 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
9155 // FIXME: Can we provide a note showing where this was declared?
9156 return true;
9157 }
9158 } else {
9159 // Explicitly instantiate a variable template.
9160
9161 // C++1y [dcl.spec.auto]p6:
9162 // ... A program that uses auto or decltype(auto) in a context not
9163 // explicitly allowed in this section is ill-formed.
9164 //
9165 // This includes auto-typed variable template instantiations.
9166 if (R->isUndeducedType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009167 Diag(T->getTypeLoc().getBeginLoc(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00009168 diag::err_auto_not_allowed_var_inst);
9169 return true;
9170 }
9171
Faisal Vali2ab8c152017-12-30 04:15:27 +00009172 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
Richard Smithef985ac2013-09-18 02:10:12 +00009173 // C++1y [temp.explicit]p3:
9174 // If the explicit instantiation is for a variable, the unqualified-id
9175 // in the declaration shall be a template-id.
9176 Diag(D.getIdentifierLoc(),
9177 diag::err_explicit_instantiation_without_template_id)
9178 << PrevTemplate;
9179 Diag(PrevTemplate->getLocation(),
9180 diag::note_explicit_instantiation_here);
9181 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00009182 }
9183
Richard Smithef985ac2013-09-18 02:10:12 +00009184 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00009185 TemplateArgumentListInfo TemplateArgs =
9186 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00009187
Larisse Voufo39a1e502013-08-06 01:03:05 +00009188 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
9189 D.getIdentifierLoc(), TemplateArgs);
9190 if (Res.isInvalid())
9191 return true;
9192
9193 // Ignore access control bits, we don't need them for redeclaration
9194 // checking.
9195 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00009196 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009197
Douglas Gregore47f5a72009-10-14 23:41:34 +00009198 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009199 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00009200 // or a static data member of a class template specialization, the name of
9201 // the class template specialization in the qualified-id for the member
9202 // name shall be a simple-template-id.
9203 //
9204 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00009205 //
Richard Smith5977d872013-09-18 21:55:14 +00009206 // This does not apply to variable template specializations, where the
9207 // template-id is in the unqualified-id instead.
9208 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009209 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00009210 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00009211 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009212
Douglas Gregore47f5a72009-10-14 23:41:34 +00009213 // Check the scope of this explicit instantiation.
9214 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009215
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009216 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00009217 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
9218 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00009219 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00009220 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00009221 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009222 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009223
Larisse Voufo39a1e502013-08-06 01:03:05 +00009224 if (!HasNoEffect) {
9225 // Instantiate static data member or variable template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00009226 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Louis Dionnee6e81752018-10-10 15:32:29 +00009227 // Merge attributes.
9228 ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
Larisse Voufo39a1e502013-08-06 01:03:05 +00009229 if (TSK == TSK_ExplicitInstantiationDefinition)
9230 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
9231 }
9232
9233 // Check the new variable specialization against the parsed input.
9234 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009235 Diag(T->getTypeLoc().getBeginLoc(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00009236 diag::err_invalid_var_template_spec_type)
9237 << 0 << PrevTemplate << R << Prev->getType();
9238 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
9239 << 2 << PrevTemplate->getDeclName();
9240 return true;
9241 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009242
Douglas Gregor450f00842009-09-25 18:43:00 +00009243 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00009244 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009245 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009246
9247 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00009248 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00009249 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00009250 TemplateArgumentListInfo TemplateArgs;
Faisal Vali2ab8c152017-12-30 04:15:27 +00009251 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00009252 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00009253 HasExplicitTemplateArgs = true;
9254 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009255
Douglas Gregor450f00842009-09-25 18:43:00 +00009256 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009257 // A [...] function [...] can be explicitly instantiated from its template.
9258 // A member function [...] of a class template can be explicitly
9259 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00009260 // template.
John McCall27c11dd2017-06-07 23:00:05 +00009261 UnresolvedSet<8> TemplateMatches;
9262 FunctionDecl *NonTemplateMatch = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009263 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00009264 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9265 P != PEnd; ++P) {
9266 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00009267 if (!HasExplicitTemplateArgs) {
9268 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Richard Smithbaa47832016-12-01 02:11:49 +00009269 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
9270 /*AdjustExceptionSpec*/true);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00009271 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
John McCall27c11dd2017-06-07 23:00:05 +00009272 if (Method->getPrimaryTemplate()) {
9273 TemplateMatches.addDecl(Method, P.getAccess());
9274 } else {
9275 // FIXME: Can this assert ever happen? Needs a test.
9276 assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
9277 NonTemplateMatch = Method;
9278 }
Douglas Gregord90fd522009-09-25 21:45:23 +00009279 }
Douglas Gregor450f00842009-09-25 18:43:00 +00009280 }
9281 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009282
Douglas Gregor450f00842009-09-25 18:43:00 +00009283 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
9284 if (!FunTmpl)
9285 continue;
9286
Larisse Voufo98b20f12013-07-19 23:00:19 +00009287 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00009288 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009289 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009290 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00009291 (HasExplicitTemplateArgs ? &TemplateArgs
9292 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00009293 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009294 // Keep track of almost-matches.
9295 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +00009296 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +00009297 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00009298 (void)TDK;
9299 continue;
9300 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009301
Artem Belevich64135c32016-12-08 19:38:13 +00009302 // Target attributes are part of the cuda function signature, so
9303 // the cuda target of the instantiated function must match that of its
9304 // template. Given that C++ template deduction does not take
9305 // target attributes into account, we reject candidates here that
9306 // have a different target.
9307 if (LangOpts.CUDA &&
9308 IdentifyCUDATarget(Specialization,
9309 /* IgnoreImplicitHDAttributes = */ true) !=
Erich Keanec480f302018-07-12 21:09:05 +00009310 IdentifyCUDATarget(D.getDeclSpec().getAttributes())) {
Artem Belevich64135c32016-12-08 19:38:13 +00009311 FailedCandidates.addCandidate().set(
9312 P.getPair(), FunTmpl->getTemplatedDecl(),
9313 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
9314 continue;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00009315 }
9316
John McCall27c11dd2017-06-07 23:00:05 +00009317 TemplateMatches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00009318 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009319
John McCall27c11dd2017-06-07 23:00:05 +00009320 FunctionDecl *Specialization = NonTemplateMatch;
9321 if (!Specialization) {
9322 // Find the most specialized function template specialization.
9323 UnresolvedSetIterator Result = getMostSpecialized(
9324 TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
9325 D.getIdentifierLoc(),
9326 PDiag(diag::err_explicit_instantiation_not_known) << Name,
9327 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
9328 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00009329
John McCall27c11dd2017-06-07 23:00:05 +00009330 if (Result == TemplateMatches.end())
9331 return true;
John McCall58cc69d2010-01-27 01:50:18 +00009332
John McCall27c11dd2017-06-07 23:00:05 +00009333 // Ignore access control bits, we don't need them for redeclaration checking.
9334 Specialization = cast<FunctionDecl>(*Result);
9335 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009336
Alexey Bataev73983912014-11-06 10:10:50 +00009337 // C++11 [except.spec]p4
9338 // In an explicit instantiation an exception-specification may be specified,
9339 // but is not required.
9340 // If an exception-specification is specified in an explicit instantiation
9341 // directive, it shall be compatible with the exception-specifications of
9342 // other declarations of that function.
9343 if (auto *FPT = R->getAs<FunctionProtoType>())
9344 if (FPT->hasExceptionSpec()) {
9345 unsigned DiagID =
9346 diag::err_mismatched_exception_spec_explicit_instantiation;
9347 if (getLangOpts().MicrosoftExt)
9348 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
9349 bool Result = CheckEquivalentExceptionSpec(
9350 PDiag(DiagID) << Specialization->getType(),
9351 PDiag(diag::note_explicit_instantiation_here),
9352 Specialization->getType()->getAs<FunctionProtoType>(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009353 Specialization->getLocation(), FPT, D.getBeginLoc());
Alexey Bataev73983912014-11-06 10:10:50 +00009354 // In Microsoft mode, mismatching exception specifications just cause a
9355 // warning.
9356 if (!getLangOpts().MicrosoftExt && Result)
9357 return true;
9358 }
9359
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009360 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009361 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00009362 diag::err_explicit_instantiation_member_function_not_instantiated)
9363 << Specialization
9364 << (Specialization->getTemplateSpecializationKind() ==
9365 TSK_ExplicitSpecialization);
9366 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
9367 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009368 }
9369
Douglas Gregorec9fd132012-01-14 16:38:05 +00009370 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00009371 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
9372 PrevDecl = Specialization;
9373
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009374 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00009375 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00009376 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009377 PrevDecl,
9378 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009379 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00009380 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009381 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009382
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009383 // FIXME: We may still want to build some representation of this
9384 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00009385 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00009386 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009387 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00009388
Erich Keanec480f302018-07-12 21:09:05 +00009389 ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009390
Hans Wennborgb8304a62017-11-29 23:44:11 +00009391 // In MSVC mode, dllimported explicit instantiation definitions are treated as
9392 // instantiation declarations.
9393 if (TSK == TSK_ExplicitInstantiationDefinition &&
9394 Specialization->hasAttr<DLLImportAttr>() &&
9395 Context.getTargetInfo().getCXXABI().isMicrosoft())
9396 TSK = TSK_ExplicitInstantiationDeclaration;
9397
9398 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9399
Richard Smitheb36ddf2014-04-24 22:45:46 +00009400 if (Specialization->isDefined()) {
9401 // Let the ASTConsumer know that this function has been explicitly
9402 // instantiated now, and its linkage might have changed.
9403 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
9404 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00009405 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009406
Douglas Gregore47f5a72009-10-14 23:41:34 +00009407 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009408 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00009409 // or a static data member of a class template specialization, the name of
9410 // the class template specialization in the qualified-id for the member
9411 // name shall be a simple-template-id.
9412 //
9413 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009414 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Faisal Vali2ab8c152017-12-30 04:15:27 +00009415 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009416 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00009417 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009418 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00009419 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00009420 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009421
Douglas Gregore47f5a72009-10-14 23:41:34 +00009422 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009423 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregore47f5a72009-10-14 23:41:34 +00009424 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009425 D.getIdentifierLoc(),
Douglas Gregore47f5a72009-10-14 23:41:34 +00009426 D.getCXXScopeSpec().isSet());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009427
Douglas Gregor450f00842009-09-25 18:43:00 +00009428 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00009429 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009430}
9431
John McCallfaf5fb42010-08-26 23:41:50 +00009432TypeResult
Faisal Vali090da2d2018-01-01 18:23:28 +00009433Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
John McCall7f41d982009-09-11 04:59:25 +00009434 const CXXScopeSpec &SS, IdentifierInfo *Name,
9435 SourceLocation TagLoc, SourceLocation NameLoc) {
9436 // This has to hold, because SS is expected to be defined.
9437 assert(Name && "Expected a name in a dependent tag");
9438
Aaron Ballman4a979672014-01-03 13:56:08 +00009439 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00009440 if (!NNS)
9441 return true;
9442
Abramo Bagnara6150c882010-05-11 21:36:43 +00009443 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00009444
Douglas Gregorba41d012010-04-24 16:38:41 +00009445 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
9446 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00009447 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00009448 return true;
9449 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00009450
Douglas Gregore7c20652011-03-02 00:47:37 +00009451 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00009452 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00009453 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009454
Douglas Gregore7c20652011-03-02 00:47:37 +00009455 // Create type-source location information for this type.
9456 TypeLocBuilder TLB;
9457 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009458 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00009459 TL.setQualifierLoc(SS.getWithLocInContext(Context));
9460 TL.setNameLoc(NameLoc);
9461 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00009462}
9463
John McCallfaf5fb42010-08-26 23:41:50 +00009464TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009465Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
9466 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00009467 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009468 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00009469 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009470
Richard Smith0bf8a4922011-10-18 20:49:44 +00009471 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9472 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009473 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00009474 diag::warn_cxx98_compat_typename_outside_of_template :
9475 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009476 << FixItHint::CreateRemoval(TypenameLoc);
9477
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009478 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00009479 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
9480 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00009481 if (T.isNull())
9482 return true;
John McCall99b2fe52010-04-29 23:50:39 +00009483
9484 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9485 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00009486 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009487 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009488 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00009489 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00009490 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00009491 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009492 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009493 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00009494 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00009495 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009496
John McCallba7bf592010-08-24 05:47:05 +00009497 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00009498}
9499
John McCallfaf5fb42010-08-26 23:41:50 +00009500TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009501Sema::ActOnTypenameType(Scope *S,
9502 SourceLocation TypenameLoc,
9503 const CXXScopeSpec &SS,
9504 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00009505 TemplateTy TemplateIn,
Richard Smith74f02342017-01-19 21:00:13 +00009506 IdentifierInfo *TemplateII,
9507 SourceLocation TemplateIILoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00009508 SourceLocation LAngleLoc,
9509 ASTTemplateArgsPtr TemplateArgsIn,
9510 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00009511 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9512 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009513 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00009514 diag::warn_cxx98_compat_typename_outside_of_template :
9515 diag::ext_typename_outside_of_template)
9516 << FixItHint::CreateRemoval(TypenameLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009517
Richard Smith74f02342017-01-19 21:00:13 +00009518 // Strangely, non-type results are not ignored by this lookup, so the
9519 // program is ill-formed if it finds an injected-class-name.
Richard Smith62559bd2017-02-01 21:36:38 +00009520 if (TypenameLoc.isValid()) {
9521 auto *LookupRD =
9522 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
9523 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
9524 Diag(TemplateIILoc,
9525 diag::ext_out_of_line_qualified_id_type_names_constructor)
9526 << TemplateII << 0 /*injected-class-name used as template name*/
9527 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
9528 }
Richard Smith74f02342017-01-19 21:00:13 +00009529 }
9530
Douglas Gregorb09518c2011-02-27 22:46:49 +00009531 // Translate the parser's template argument list in our AST format.
9532 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9533 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009534
Douglas Gregorb09518c2011-02-27 22:46:49 +00009535 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009536 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
9537 // Construct a dependent template specialization type.
9538 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00009539 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009540 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
9541 DTN->getQualifier(),
9542 DTN->getIdentifier(),
9543 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009544
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009545 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00009546 TypeLocBuilder Builder;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009547 DependentTemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009548 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009549 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
9550 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00009551 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00009552 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009553 SpecTL.setLAngleLoc(LAngleLoc);
9554 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009555 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9556 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009557 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00009558 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009559
Richard Smith74f02342017-01-19 21:00:13 +00009560 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009561 if (T.isNull())
9562 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009563
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009564 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00009565 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009566 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009567 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009568 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00009569 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009570 SpecTL.setLAngleLoc(LAngleLoc);
9571 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009572 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9573 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009574
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009575 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
9576 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009577 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009578 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Simon Pilgrim6905d222016-12-30 22:55:33 +00009579
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009580 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
9581 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00009582}
9583
Douglas Gregorb09518c2011-02-27 22:46:49 +00009584
Richard Smith6f8d2c62012-05-09 05:17:00 +00009585/// Determine whether this failed name lookup should be treated as being
9586/// disabled by a usage of std::enable_if.
9587static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009588 SourceRange &CondRange, Expr *&Cond) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00009589 // We must be looking for a ::type...
9590 if (!II.isStr("type"))
9591 return false;
9592
9593 // ... within an explicitly-written template specialization...
9594 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
9595 return false;
9596 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00009597 TemplateSpecializationTypeLoc EnableIfTSTLoc =
9598 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
9599 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00009600 return false;
George Burgess IV00f70bd2018-03-01 05:43:23 +00009601 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009602
9603 // ... which names a complete class template declaration...
9604 const TemplateDecl *EnableIfDecl =
9605 EnableIfTST->getTemplateName().getAsTemplateDecl();
9606 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
9607 return false;
9608
9609 // ... called "enable_if".
9610 const IdentifierInfo *EnableIfII =
9611 EnableIfDecl->getDeclName().getAsIdentifierInfo();
9612 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
9613 return false;
9614
9615 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00009616 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009617
9618 // Dig out the condition.
9619 Cond = nullptr;
9620 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
9621 != TemplateArgument::Expression)
9622 return true;
9623
9624 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
9625
9626 // Ignore Boolean literals; they add no value.
9627 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
9628 Cond = nullptr;
9629
Richard Smith6f8d2c62012-05-09 05:17:00 +00009630 return true;
9631}
9632
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009633/// Build the type that describes a C++ typename specifier,
Douglas Gregor333489b2009-03-27 23:10:48 +00009634/// e.g., "typename T::type".
9635QualType
Simon Pilgrim6905d222016-12-30 22:55:33 +00009636Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009637 SourceLocation KeywordLoc,
Simon Pilgrim6905d222016-12-30 22:55:33 +00009638 NestedNameSpecifierLoc QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009639 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00009640 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00009641 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009642 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00009643
John McCall0b66eb32010-05-01 00:40:08 +00009644 DeclContext *Ctx = computeDeclContext(SS);
9645 if (!Ctx) {
9646 // If the nested-name-specifier is dependent and couldn't be
9647 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009648 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009649 return Context.getDependentNameType(Keyword,
9650 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009651 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00009652 }
Douglas Gregor333489b2009-03-27 23:10:48 +00009653
John McCall0b66eb32010-05-01 00:40:08 +00009654 // If the nested-name-specifier refers to the current instantiation,
9655 // the "typename" keyword itself is superfluous. In C++03, the
9656 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
9657 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00009658 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00009659
John McCall0b66eb32010-05-01 00:40:08 +00009660 if (RequireCompleteDeclContext(SS, Ctx))
9661 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00009662
9663 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00009664 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00009665 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00009666 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00009667 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00009668 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00009669 case LookupResult::NotFound: {
9670 // If we're looking up 'type' within a template named 'enable_if', produce
9671 // a more specific diagnostic.
9672 SourceRange CondRange;
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009673 Expr *Cond = nullptr;
9674 if (isEnableIf(QualifierLoc, II, CondRange, Cond)) {
9675 // If we have a condition, narrow it down to the specific failed
9676 // condition.
9677 if (Cond) {
9678 Expr *FailedCond;
9679 std::string FailedDescription;
9680 std::tie(FailedCond, FailedDescription) =
Clement Courbetf44c6f42018-12-11 08:39:11 +00009681 findFailedBooleanCondition(Cond);
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009682
9683 Diag(FailedCond->getExprLoc(),
9684 diag::err_typename_nested_not_found_requirement)
9685 << FailedDescription
9686 << FailedCond->getSourceRange();
9687 return QualType();
9688 }
9689
Richard Smith6f8d2c62012-05-09 05:17:00 +00009690 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009691 << Ctx << CondRange;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009692 return QualType();
9693 }
9694
Douglas Gregore40876a2009-10-13 21:16:44 +00009695 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00009696 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009697 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009698
9699 case LookupResult::FoundUnresolvedValue: {
9700 // We found a using declaration that is a value. Most likely, the using
9701 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009702 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009703 IILoc);
9704 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
9705 << Name << Ctx << FullRange;
9706 if (UnresolvedUsingValueDecl *Using
9707 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009708 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009709 Diag(Loc, diag::note_using_value_decl_missing_typename)
9710 << FixItHint::CreateInsertion(Loc, "typename ");
9711 }
9712 }
9713 // Fall through to create a dependent typename type, from which we can recover
9714 // better.
Galina Kistanova3779cb32017-06-07 06:25:05 +00009715 LLVM_FALLTHROUGH;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009716
Douglas Gregord0d2ee02010-01-15 01:44:47 +00009717 case LookupResult::NotFoundInCurrentInstantiation:
9718 // Okay, it's a member of an unknown instantiation.
Simon Pilgrim6905d222016-12-30 22:55:33 +00009719 return Context.getDependentNameType(Keyword,
9720 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009721 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00009722
9723 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009724 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Richard Smith74f02342017-01-19 21:00:13 +00009725 // C++ [class.qual]p2:
9726 // In a lookup in which function names are not ignored and the
9727 // nested-name-specifier nominates a class C, if the name specified
9728 // after the nested-name-specifier, when looked up in C, is the
9729 // injected-class-name of C [...] then the name is instead considered
9730 // to name the constructor of class C.
9731 //
9732 // Unlike in an elaborated-type-specifier, function names are not ignored
9733 // in typename-specifier lookup. However, they are ignored in all the
9734 // contexts where we form a typename type with no keyword (that is, in
9735 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
9736 //
9737 // FIXME: That's not strictly true: mem-initializer-id lookup does not
9738 // ignore functions, but that appears to be an oversight.
9739 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
9740 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
9741 if (Keyword == ETK_Typename && LookupRD && FoundRD &&
9742 FoundRD->isInjectedClassName() &&
9743 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
9744 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
9745 << &II << 1 << 0 /*'typename' keyword used*/;
9746
Abramo Bagnara6150c882010-05-11 21:36:43 +00009747 // We found a type. Build an ElaboratedType, since the
9748 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00009749 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Richard Smith74f02342017-01-19 21:00:13 +00009750 return Context.getElaboratedType(Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009751 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00009752 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00009753 }
9754
Richard Smithee579842017-01-30 20:39:26 +00009755 // C++ [dcl.type.simple]p2:
9756 // A type-specifier of the form
9757 // typename[opt] nested-name-specifier[opt] template-name
9758 // is a placeholder for a deduced class type [...].
Aaron Ballmanc351fba2017-12-04 20:27:34 +00009759 if (getLangOpts().CPlusPlus17) {
Richard Smithee579842017-01-30 20:39:26 +00009760 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
9761 return Context.getElaboratedType(
9762 Keyword, QualifierLoc.getNestedNameSpecifier(),
9763 Context.getDeducedTemplateSpecializationType(TemplateName(TD),
9764 QualType(), false));
9765 }
9766 }
Richard Smith600b5262017-01-26 20:40:47 +00009767
Douglas Gregor333489b2009-03-27 23:10:48 +00009768 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00009769 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00009770 break;
9771
9772 case LookupResult::FoundOverloaded:
9773 DiagID = diag::err_typename_nested_not_type;
9774 Referenced = *Result.begin();
9775 break;
9776
John McCall6538c932009-10-10 05:48:19 +00009777 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00009778 return QualType();
9779 }
9780
9781 // If we get here, it's because name lookup did not find a
9782 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009783 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00009784 IILoc);
9785 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00009786 if (Referenced)
9787 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
9788 << Name;
9789 return QualType();
9790}
Douglas Gregor15acfb92009-08-06 16:20:37 +00009791
9792namespace {
9793 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00009794 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00009795 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00009796 SourceLocation Loc;
9797 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00009798
Douglas Gregor15acfb92009-08-06 16:20:37 +00009799 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00009800 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009801
Mike Stump11289f42009-09-09 15:08:12 +00009802 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00009803 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00009804 DeclarationName Entity)
9805 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00009806 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00009807
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009808 /// Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00009809 /// transformed.
9810 ///
9811 /// For the purposes of type reconstruction, a type has already been
9812 /// transformed if it is NULL or if it is not dependent.
9813 bool AlreadyTransformed(QualType T) {
9814 return T.isNull() || !T->isDependentType();
9815 }
Mike Stump11289f42009-09-09 15:08:12 +00009816
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009817 /// Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00009818 /// rebuilt.
9819 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00009820
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009821 /// Returns the name of the entity whose type is being rebuilt.
Douglas Gregor15acfb92009-08-06 16:20:37 +00009822 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00009823
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009824 /// Sets the "base" location and entity when that
Douglas Gregoref6ab412009-10-27 06:26:26 +00009825 /// information is known based on another transformation.
9826 void setBase(SourceLocation Loc, DeclarationName Entity) {
9827 this->Loc = Loc;
9828 this->Entity = Entity;
9829 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009830
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00009831 ExprResult TransformLambdaExpr(LambdaExpr *E) {
9832 // Lambdas never need to be transformed.
9833 return E;
9834 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00009835 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009836} // end anonymous namespace
Douglas Gregor15acfb92009-08-06 16:20:37 +00009837
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009838/// Rebuilds a type within the context of the current instantiation.
Douglas Gregor15acfb92009-08-06 16:20:37 +00009839///
Mike Stump11289f42009-09-09 15:08:12 +00009840/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00009841/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00009842/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00009843/// partial specialization thereof). This routine will rebuild that type now
9844/// that we have entered the declarator's scope, which may produce different
9845/// canonical types, e.g.,
9846///
9847/// \code
9848/// template<typename T>
9849/// struct X {
9850/// typedef T* pointer;
9851/// pointer data();
9852/// };
9853///
9854/// template<typename T>
9855/// typename X<T>::pointer X<T>::data() { ... }
9856/// \endcode
9857///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00009858/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00009859/// since we do not know that we can look into X<T> when we parsed the type.
9860/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00009861/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00009862/// as the canonical type of T*, allowing the return types of the out-of-line
9863/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00009864TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
9865 SourceLocation Loc,
9866 DeclarationName Name) {
9867 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00009868 return T;
Mike Stump11289f42009-09-09 15:08:12 +00009869
Douglas Gregor15acfb92009-08-06 16:20:37 +00009870 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
9871 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00009872}
Douglas Gregorbe999392009-09-15 16:23:51 +00009873
John McCalldadc5752010-08-24 06:29:42 +00009874ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00009875 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
9876 DeclarationName());
9877 return Rebuilder.TransformExpr(E);
9878}
9879
John McCall99b2fe52010-04-29 23:50:39 +00009880bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00009881 if (SS.isInvalid())
Douglas Gregor10176412011-02-25 16:07:42 +00009882 return true;
John McCall2408e322010-04-27 00:57:59 +00009883
Douglas Gregor10176412011-02-25 16:07:42 +00009884 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00009885 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
9886 DeclarationName());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009887 NestedNameSpecifierLoc Rebuilt
Douglas Gregor10176412011-02-25 16:07:42 +00009888 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009889 if (!Rebuilt)
Douglas Gregor10176412011-02-25 16:07:42 +00009890 return true;
John McCall99b2fe52010-04-29 23:50:39 +00009891
Douglas Gregor10176412011-02-25 16:07:42 +00009892 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00009893 return false;
John McCall2408e322010-04-27 00:57:59 +00009894}
9895
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009896/// Rebuild the template parameters now that we know we're in a current
Douglas Gregor041b0842011-10-14 15:31:12 +00009897/// instantiation.
9898bool Sema::RebuildTemplateParamsInCurrentInstantiation(
9899 TemplateParameterList *Params) {
9900 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
9901 Decl *Param = Params->getParam(I);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009902
Douglas Gregor041b0842011-10-14 15:31:12 +00009903 // There is nothing to rebuild in a type parameter.
9904 if (isa<TemplateTypeParmDecl>(Param))
9905 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009906
Douglas Gregor041b0842011-10-14 15:31:12 +00009907 // Rebuild the template parameter list of a template template parameter.
Simon Pilgrim6905d222016-12-30 22:55:33 +00009908 if (TemplateTemplateParmDecl *TTP
Douglas Gregor041b0842011-10-14 15:31:12 +00009909 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
9910 if (RebuildTemplateParamsInCurrentInstantiation(
9911 TTP->getTemplateParameters()))
9912 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009913
Douglas Gregor041b0842011-10-14 15:31:12 +00009914 continue;
9915 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009916
Douglas Gregor041b0842011-10-14 15:31:12 +00009917 // Rebuild the type of a non-type template parameter.
9918 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009919 TypeSourceInfo *NewTSI
9920 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
9921 NTTP->getLocation(),
Douglas Gregor041b0842011-10-14 15:31:12 +00009922 NTTP->getDeclName());
9923 if (!NewTSI)
9924 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009925
Erik Pilkington9f9462a2018-08-07 22:59:02 +00009926 if (NewTSI->getType()->isUndeducedType()) {
9927 // C++17 [temp.dep.expr]p3:
9928 // An id-expression is type-dependent if it contains
9929 // - an identifier associated by name lookup with a non-type
9930 // template-parameter declared with a type that contains a
9931 // placeholder type (7.1.7.4),
9932 NewTSI = SubstAutoTypeSourceInfo(NewTSI, Context.DependentTy);
9933 }
9934
Douglas Gregor041b0842011-10-14 15:31:12 +00009935 if (NewTSI != NTTP->getTypeSourceInfo()) {
9936 NTTP->setTypeSourceInfo(NewTSI);
9937 NTTP->setType(NewTSI->getType());
9938 }
9939 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009940
Douglas Gregor041b0842011-10-14 15:31:12 +00009941 return false;
9942}
9943
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009944/// Produces a formatted string that describes the binding of
Douglas Gregorbe999392009-09-15 16:23:51 +00009945/// template parameters to template arguments.
9946std::string
9947Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9948 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009949 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00009950}
9951
9952std::string
9953Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9954 const TemplateArgument *Args,
9955 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009956 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +00009957 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +00009958
Douglas Gregore62e6a02009-11-11 19:13:48 +00009959 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00009960 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009961
Douglas Gregorbe999392009-09-15 16:23:51 +00009962 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00009963 if (I >= NumArgs)
9964 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009965
Douglas Gregorbe999392009-09-15 16:23:51 +00009966 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00009967 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +00009968 else
Douglas Gregor0192c232010-12-20 16:52:59 +00009969 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009970
Douglas Gregorbe999392009-09-15 16:23:51 +00009971 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +00009972 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +00009973 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +00009974 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +00009975 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009976
Douglas Gregor0192c232010-12-20 16:52:59 +00009977 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +00009978 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +00009979 }
Douglas Gregor0192c232010-12-20 16:52:59 +00009980
9981 Out << ']';
9982 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +00009983}
Francois Pichet1c229c02011-04-22 22:18:13 +00009984
Richard Smithe40f2ba2013-08-07 21:41:30 +00009985void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
9986 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +00009987 if (!FD)
9988 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +00009989
Justin Lebar28f09c52016-10-10 16:26:08 +00009990 auto LPT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00009991
9992 // Take tokens to avoid allocations
9993 LPT->Toks.swap(Toks);
9994 LPT->D = FnD;
Justin Lebar28f09c52016-10-10 16:26:08 +00009995 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00009996
9997 FD->setLateTemplateParsed(true);
9998}
9999
10000void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
10001 if (!FD)
10002 return;
10003 FD->setLateTemplateParsed(false);
10004}
Francois Pichet1c229c02011-04-22 22:18:13 +000010005
10006bool Sema::IsInsideALocalClassWithinATemplateFunction() {
10007 DeclContext *DC = CurContext;
10008
10009 while (DC) {
10010 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
10011 const FunctionDecl *FD = RD->isLocalClass();
10012 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
10013 } else if (DC->isTranslationUnit() || DC->isNamespace())
10014 return false;
10015
10016 DC = DC->getParent();
10017 }
10018 return false;
10019}
Richard Smith6739a102016-05-05 00:56:12 +000010020
Benjamin Kramera0a13c32016-08-06 11:21:04 +000010021namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010022/// Walk the path from which a declaration was instantiated, and check
Richard Smith6739a102016-05-05 00:56:12 +000010023/// that every explicit specialization along that path is visible. This enforces
10024/// C++ [temp.expl.spec]/6:
10025///
10026/// If a template, a member template or a member of a class template is
10027/// explicitly specialized then that specialization shall be declared before
10028/// the first use of that specialization that would cause an implicit
10029/// instantiation to take place, in every translation unit in which such a
10030/// use occurs; no diagnostic is required.
10031///
10032/// and also C++ [temp.class.spec]/1:
10033///
10034/// A partial specialization shall be declared before the first use of a
10035/// class template specialization that would make use of the partial
10036/// specialization as the result of an implicit or explicit instantiation
10037/// in every translation unit in which such a use occurs; no diagnostic is
10038/// required.
10039class ExplicitSpecializationVisibilityChecker {
10040 Sema &S;
10041 SourceLocation Loc;
10042 llvm::SmallVector<Module *, 8> Modules;
10043
10044public:
10045 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
10046 : S(S), Loc(Loc) {}
10047
10048 void check(NamedDecl *ND) {
10049 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10050 return checkImpl(FD);
10051 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
10052 return checkImpl(RD);
10053 if (auto *VD = dyn_cast<VarDecl>(ND))
10054 return checkImpl(VD);
10055 if (auto *ED = dyn_cast<EnumDecl>(ND))
10056 return checkImpl(ED);
10057 }
10058
10059private:
10060 void diagnose(NamedDecl *D, bool IsPartialSpec) {
10061 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
10062 : Sema::MissingImportKind::ExplicitSpecialization;
10063 const bool Recover = true;
10064
10065 // If we got a custom set of modules (because only a subset of the
10066 // declarations are interesting), use them, otherwise let
10067 // diagnoseMissingImport intelligently pick some.
10068 if (Modules.empty())
10069 S.diagnoseMissingImport(Loc, D, Kind, Recover);
10070 else
10071 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
10072 }
10073
10074 // Check a specific declaration. There are three problematic cases:
10075 //
10076 // 1) The declaration is an explicit specialization of a template
10077 // specialization.
10078 // 2) The declaration is an explicit specialization of a member of an
10079 // templated class.
10080 // 3) The declaration is an instantiation of a template, and that template
10081 // is an explicit specialization of a member of a templated class.
10082 //
10083 // We don't need to go any deeper than that, as the instantiation of the
10084 // surrounding class / etc is not triggered by whatever triggered this
10085 // instantiation, and thus should be checked elsewhere.
10086 template<typename SpecDecl>
10087 void checkImpl(SpecDecl *Spec) {
10088 bool IsHiddenExplicitSpecialization = false;
10089 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
10090 IsHiddenExplicitSpecialization =
10091 Spec->getMemberSpecializationInfo()
10092 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
Richard Smith54f04402017-05-18 02:29:20 +000010093 : !S.hasVisibleExplicitSpecialization(Spec, &Modules);
Richard Smith6739a102016-05-05 00:56:12 +000010094 } else {
10095 checkInstantiated(Spec);
10096 }
10097
10098 if (IsHiddenExplicitSpecialization)
10099 diagnose(Spec->getMostRecentDecl(), false);
10100 }
10101
10102 void checkInstantiated(FunctionDecl *FD) {
10103 if (auto *TD = FD->getPrimaryTemplate())
10104 checkTemplate(TD);
10105 }
10106
10107 void checkInstantiated(CXXRecordDecl *RD) {
10108 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
10109 if (!SD)
10110 return;
10111
10112 auto From = SD->getSpecializedTemplateOrPartial();
10113 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
10114 checkTemplate(TD);
10115 else if (auto *TD =
10116 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
10117 if (!S.hasVisibleDeclaration(TD))
10118 diagnose(TD, true);
10119 checkTemplate(TD);
10120 }
10121 }
10122
10123 void checkInstantiated(VarDecl *RD) {
10124 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
10125 if (!SD)
10126 return;
10127
10128 auto From = SD->getSpecializedTemplateOrPartial();
10129 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
10130 checkTemplate(TD);
10131 else if (auto *TD =
10132 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
10133 if (!S.hasVisibleDeclaration(TD))
10134 diagnose(TD, true);
10135 checkTemplate(TD);
10136 }
10137 }
10138
10139 void checkInstantiated(EnumDecl *FD) {}
10140
10141 template<typename TemplDecl>
10142 void checkTemplate(TemplDecl *TD) {
10143 if (TD->isMemberSpecialization()) {
10144 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
10145 diagnose(TD->getMostRecentDecl(), false);
10146 }
10147 }
10148};
Benjamin Kramera0a13c32016-08-06 11:21:04 +000010149} // end anonymous namespace
Richard Smith6739a102016-05-05 00:56:12 +000010150
10151void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
10152 if (!getLangOpts().Modules)
10153 return;
10154
10155 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
10156}
10157
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010158/// Check whether a template partial specialization that we've discovered
Richard Smith6739a102016-05-05 00:56:12 +000010159/// is hidden, and produce suitable diagnostics if so.
10160void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
10161 NamedDecl *Spec) {
10162 llvm::SmallVector<Module *, 8> Modules;
10163 if (!hasVisibleDeclaration(Spec, &Modules))
10164 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
10165 MissingImportKind::PartialSpecialization,
10166 /*Recover*/true);
10167}