blob: 3f642b5c426a337b1de83b594c9e71b499559653 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006//===----------------------------------------------------------------------===//
Douglas Gregor5101c242008-12-05 18:15:24 +00007//
8// This file implements semantic analysis for C++ templates.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009//===----------------------------------------------------------------------===//
Douglas Gregor5101c242008-12-05 18:15:24 +000010
Douglas Gregor15acfb92009-08-06 16:20:37 +000011#include "TreeTransform.h"
Larisse Voufo39a1e502013-08-06 01:03:05 +000012#include "clang/AST/ASTConsumer.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000013#include "clang/AST/ASTContext.h"
John McCallbbbbe4e2010-03-11 07:50:04 +000014#include "clang/AST/DeclFriend.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000015#include "clang/AST/DeclTemplate.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "clang/AST/Expr.h"
17#include "clang/AST/ExprCXX.h"
John McCalla020a012010-10-20 05:44:58 +000018#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor7731d3f2010-10-13 00:27:52 +000019#include "clang/AST/TypeVisitor.h"
David Majnemerd9b1a4f2015-11-04 03:40:30 +000020#include "clang/Basic/Builtins.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000021#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000022#include "clang/Basic/PartialDiagnostic.h"
David Majnemer763584d2014-02-06 10:59:19 +000023#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Sema/DeclSpec.h"
25#include "clang/Sema/Lookup.h"
26#include "clang/Sema/ParsedTemplate.h"
27#include "clang/Sema/Scope.h"
28#include "clang/Sema/SemaInternal.h"
29#include "clang/Sema/Template.h"
30#include "clang/Sema/TemplateDeduction.h"
Benjamin Kramere0513cb2012-01-30 16:17:39 +000031#include "llvm/ADT/SmallBitVector.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000032#include "llvm/ADT/SmallString.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000033#include "llvm/ADT/StringExtras.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000034
Eric Fiselier6ad68552016-07-01 01:24:09 +000035#include <iterator>
Douglas Gregor5101c242008-12-05 18:15:24 +000036using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000037using namespace sema;
Douglas Gregor5101c242008-12-05 18:15:24 +000038
John McCall9b72f892010-11-10 02:40:36 +000039// Exported for use by Parser.
40SourceRange
41clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
42 unsigned N) {
43 if (!N) return SourceRange();
44 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
45}
46
Hubert Tong5a8ec4e2017-02-10 02:46:19 +000047namespace clang {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000048/// [temp.constr.decl]p2: A template's associated constraints are
Hubert Tong5a8ec4e2017-02-10 02:46:19 +000049/// defined as a single constraint-expression derived from the introduced
50/// constraint-expressions [ ... ].
51///
52/// \param Params The template parameter list and optional requires-clause.
53///
54/// \param FD The underlying templated function declaration for a function
55/// template.
56static Expr *formAssociatedConstraints(TemplateParameterList *Params,
57 FunctionDecl *FD);
58}
59
60static Expr *clang::formAssociatedConstraints(TemplateParameterList *Params,
61 FunctionDecl *FD) {
62 // FIXME: Concepts: collect additional introduced constraint-expressions
63 assert(!FD && "Cannot collect constraints from function declaration yet.");
64 return Params->getRequiresClause();
65}
66
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000067/// Determine whether the declaration found is acceptable as the name
Douglas Gregorb7bfe792009-09-02 22:59:36 +000068/// of a template and, if so, return that template declaration. Otherwise,
Richard Smithafcfb6b2019-02-15 21:53:07 +000069/// returns null.
70///
71/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
72/// is true. In all other cases it will return a TemplateDecl (or null).
73NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D,
74 bool AllowFunctionTemplates,
75 bool AllowDependent) {
76 D = D->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +000077
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000078 if (isa<TemplateDecl>(D)) {
79 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +000080 return nullptr;
81
Richard Smithafcfb6b2019-02-15 21:53:07 +000082 return D;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000083 }
Mike Stump11289f42009-09-09 15:08:12 +000084
Douglas Gregorb7bfe792009-09-02 22:59:36 +000085 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
86 // C++ [temp.local]p1:
87 // Like normal (non-template) classes, class templates have an
88 // injected-class-name (Clause 9). The injected-class-name
89 // can be used with or without a template-argument-list. When
90 // it is used without a template-argument-list, it is
91 // equivalent to the injected-class-name followed by the
92 // template-parameters of the class template enclosed in
93 // <>. When it is used with a template-argument-list, it
94 // refers to the specified class template specialization,
95 // which could be the current specialization or another
96 // specialization.
97 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000098 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000099 if (Record->getDescribedClassTemplate())
100 return Record->getDescribedClassTemplate();
101
102 if (ClassTemplateSpecializationDecl *Spec
103 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
104 return Spec->getSpecializedTemplate();
105 }
Mike Stump11289f42009-09-09 15:08:12 +0000106
Craig Topperc3ec1492014-05-26 06:22:03 +0000107 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000108 }
Mike Stump11289f42009-09-09 15:08:12 +0000109
Richard Smithcbebd622018-05-14 20:52:48 +0000110 // 'using Dependent::foo;' can resolve to a template name.
111 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
112 // injected-class-name).
Richard Smithafcfb6b2019-02-15 21:53:07 +0000113 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
Richard Smithcbebd622018-05-14 20:52:48 +0000114 return D;
115
Craig Topperc3ec1492014-05-26 06:22:03 +0000116 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000117}
118
Simon Pilgrim6905d222016-12-30 22:55:33 +0000119void Sema::FilterAcceptableTemplateNames(LookupResult &R,
Richard Smithafcfb6b2019-02-15 21:53:07 +0000120 bool AllowFunctionTemplates,
121 bool AllowDependent) {
John McCalle66edc12009-11-24 19:00:30 +0000122 LookupResult::Filter filter = R.makeFilter();
123 while (filter.hasNext()) {
124 NamedDecl *Orig = filter.next();
Richard Smithafcfb6b2019-02-15 21:53:07 +0000125 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
John McCalle66edc12009-11-24 19:00:30 +0000126 filter.erase();
John McCalle66edc12009-11-24 19:00:30 +0000127 }
128 filter.done();
129}
130
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000131bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
Richard Smithafcfb6b2019-02-15 21:53:07 +0000132 bool AllowFunctionTemplates,
133 bool AllowDependent) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000134 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
Richard Smithafcfb6b2019-02-15 21:53:07 +0000135 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000136 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +0000137
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000138 return false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000139}
140
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000141TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000142 CXXScopeSpec &SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000143 bool hasTemplateKeyword,
Richard Smithc08b6932018-04-27 02:00:13 +0000144 const UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +0000145 ParsedType ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000146 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000147 TemplateTy &TemplateResult,
148 bool &MemberOfUnknownSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000149 assert(getLangOpts().CPlusPlus && "No template names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000150
Douglas Gregor3cf81312009-11-03 23:16:33 +0000151 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000152 MemberOfUnknownSpecialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000153
Douglas Gregor3cf81312009-11-03 23:16:33 +0000154 switch (Name.getKind()) {
Faisal Vali2ab8c152017-12-30 04:15:27 +0000155 case UnqualifiedIdKind::IK_Identifier:
Douglas Gregor3cf81312009-11-03 23:16:33 +0000156 TName = DeclarationName(Name.Identifier);
157 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000158
Faisal Vali2ab8c152017-12-30 04:15:27 +0000159 case UnqualifiedIdKind::IK_OperatorFunctionId:
Douglas Gregor3cf81312009-11-03 23:16:33 +0000160 TName = Context.DeclarationNames.getCXXOperatorName(
161 Name.OperatorFunctionId.Operator);
162 break;
163
Faisal Vali2ab8c152017-12-30 04:15:27 +0000164 case UnqualifiedIdKind::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000165 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
166 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000167
Douglas Gregor3cf81312009-11-03 23:16:33 +0000168 default:
169 return TNK_Non_template;
170 }
Mike Stump11289f42009-09-09 15:08:12 +0000171
John McCallba7bf592010-08-24 05:47:05 +0000172 QualType ObjectType = ObjectTypePtr.get();
Mike Stump11289f42009-09-09 15:08:12 +0000173
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000174 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
Richard Smith79810042018-05-11 02:43:08 +0000175 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
176 MemberOfUnknownSpecialization))
177 return TNK_Non_template;
John McCallfb3f9ba2010-08-28 20:17:00 +0000178 if (R.empty()) return TNK_Non_template;
Richard Smith40bd10b2019-02-15 00:29:04 +0000179
Richard Smithafcfb6b2019-02-15 21:53:07 +0000180 NamedDecl *D = nullptr;
181 if (R.isAmbiguous()) {
182 // If we got an ambiguity involving a non-function template, treat this
183 // as a template name, and pick an arbitrary template for error recovery.
184 bool AnyFunctionTemplates = false;
185 for (NamedDecl *FoundD : R) {
186 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
187 if (isa<FunctionTemplateDecl>(FoundTemplate))
188 AnyFunctionTemplates = true;
189 else {
190 D = FoundTemplate;
191 break;
192 }
193 }
194 }
195
196 // If we didn't find any templates at all, this isn't a template name.
197 // Leave the ambiguity for a later lookup to diagnose.
198 if (!D && !AnyFunctionTemplates) {
199 R.suppressDiagnostics();
200 return TNK_Non_template;
201 }
202
203 // If the only templates were function templates, filter out the rest.
204 // We'll diagnose the ambiguity later.
205 if (!D)
206 FilterAcceptableTemplateNames(R);
John McCalldcc71402010-08-13 02:23:42 +0000207 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000208
Richard Smithafcfb6b2019-02-15 21:53:07 +0000209 // At this point, we have either picked a single template name declaration D
210 // or we have a non-empty set of results R containing either one template name
211 // declaration or a set of function templates.
212
John McCalld28ae272009-12-02 08:04:21 +0000213 TemplateName Template;
214 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000215
John McCalld28ae272009-12-02 08:04:21 +0000216 unsigned ResultCount = R.end() - R.begin();
Richard Smithafcfb6b2019-02-15 21:53:07 +0000217 if (!D && ResultCount > 1) {
John McCalld28ae272009-12-02 08:04:21 +0000218 // We assume that we'll preserve the qualifier from a function
219 // template name in other ways.
220 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
221 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000222
223 // We'll do this lookup again later.
224 R.suppressDiagnostics();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000225 } else {
Richard Smithafcfb6b2019-02-15 21:53:07 +0000226 if (!D) {
227 D = getAsTemplateNameDecl(*R.begin());
228 assert(D && "unambiguous result is not a template name");
229 }
230
231 if (isa<UnresolvedUsingValueDecl>(D)) {
232 // We don't yet know whether this is a template-name or not.
233 MemberOfUnknownSpecialization = true;
234 return TNK_Non_template;
235 }
236
237 TemplateDecl *TD = cast<TemplateDecl>(D);
John McCalld28ae272009-12-02 08:04:21 +0000238
239 if (SS.isSet() && !SS.isInvalid()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000240 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000241 Template = Context.getQualifiedTemplateName(Qualifier,
242 hasTemplateKeyword, TD);
John McCalld28ae272009-12-02 08:04:21 +0000243 } else {
244 Template = TemplateName(TD);
245 }
246
John McCalldcc71402010-08-13 02:23:42 +0000247 if (isa<FunctionTemplateDecl>(TD)) {
John McCalld28ae272009-12-02 08:04:21 +0000248 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000249
250 // We'll do this lookup again later.
251 R.suppressDiagnostics();
252 } else {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000253 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000254 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
Faisal Valia534f072018-04-26 00:42:40 +0000255 isa<BuiltinTemplateDecl>(TD));
Larisse Voufo39a1e502013-08-06 01:03:05 +0000256 TemplateKind =
Faisal Valia534f072018-04-26 00:42:40 +0000257 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
John McCalld28ae272009-12-02 08:04:21 +0000258 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000259 }
Mike Stump11289f42009-09-09 15:08:12 +0000260
John McCalld28ae272009-12-02 08:04:21 +0000261 TemplateResult = TemplateTy::make(Template);
262 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000263}
264
Richard Smith278890f2017-02-10 20:39:58 +0000265bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
266 SourceLocation NameLoc,
267 ParsedTemplateTy *Template) {
268 CXXScopeSpec SS;
269 bool MemberOfUnknownSpecialization = false;
270
271 // We could use redeclaration lookup here, but we don't need to: the
272 // syntactic form of a deduction guide is enough to identify it even
273 // if we can't look up the template name at all.
274 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
Richard Smith79810042018-05-11 02:43:08 +0000275 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
276 /*EnteringContext*/ false,
277 MemberOfUnknownSpecialization))
278 return false;
Richard Smith278890f2017-02-10 20:39:58 +0000279
280 if (R.empty()) return false;
281 if (R.isAmbiguous()) {
282 // FIXME: Diagnose an ambiguity if we find at least one template.
283 R.suppressDiagnostics();
284 return false;
285 }
286
287 // We only treat template-names that name type templates as valid deduction
288 // guide names.
289 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
290 if (!TD || !getAsTypeTemplateDecl(TD))
291 return false;
292
293 if (Template)
294 *Template = TemplateTy::make(TemplateName(TD));
295 return true;
296}
297
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000298bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
Douglas Gregor18473f32010-01-12 21:28:44 +0000299 SourceLocation IILoc,
300 Scope *S,
301 const CXXScopeSpec *SS,
302 TemplateTy &SuggestedTemplate,
303 TemplateNameKind &SuggestedKind) {
304 // We can't recover unless there's a dependent scope specifier preceding the
305 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000306 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000307 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
308 computeDeclContext(*SS))
309 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000310
Douglas Gregor18473f32010-01-12 21:28:44 +0000311 // The code is missing a 'template' keyword prior to the dependent template
312 // name.
313 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
314 Diag(IILoc, diag::err_template_kw_missing)
315 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000316 << FixItHint::CreateInsertion(IILoc, "template ");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000317 SuggestedTemplate
Douglas Gregor18473f32010-01-12 21:28:44 +0000318 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
319 SuggestedKind = TNK_Dependent_template_name;
320 return true;
321}
322
Richard Smith79810042018-05-11 02:43:08 +0000323bool Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000324 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000325 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000326 bool EnteringContext,
Richard Smith79810042018-05-11 02:43:08 +0000327 bool &MemberOfUnknownSpecialization,
328 SourceLocation TemplateKWLoc) {
Richard Smithafcfb6b2019-02-15 21:53:07 +0000329 Found.setTemplateNameLookup(true);
330
John McCalle66edc12009-11-24 19:00:30 +0000331 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000332 MemberOfUnknownSpecialization = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000333 DeclContext *LookupCtx = nullptr;
Richard Smith79810042018-05-11 02:43:08 +0000334 bool IsDependent = false;
John McCalle66edc12009-11-24 19:00:30 +0000335 if (!ObjectType.isNull()) {
336 // This nested-name-specifier occurs in a member access expression, e.g.,
337 // x->B::f, and we are looking into the type of the object.
338 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
339 LookupCtx = computeDeclContext(ObjectType);
Richard Smith79810042018-05-11 02:43:08 +0000340 IsDependent = !LookupCtx;
341 assert((IsDependent || !ObjectType->isIncompleteType() ||
Richard Smith5ed79562013-06-07 20:03:01 +0000342 ObjectType->castAs<TagType>()->isBeingDefined()) &&
John McCalle66edc12009-11-24 19:00:30 +0000343 "Caller should have completed object type");
Simon Pilgrim6905d222016-12-30 22:55:33 +0000344
Douglas Gregorbf3a8262012-01-12 16:11:24 +0000345 // Template names cannot appear inside an Objective-C class or object type.
346 if (ObjectType->isObjCObjectOrInterfaceType()) {
347 Found.clear();
Richard Smith79810042018-05-11 02:43:08 +0000348 return false;
Douglas Gregorbf3a8262012-01-12 16:11:24 +0000349 }
John McCalle66edc12009-11-24 19:00:30 +0000350 } else if (SS.isSet()) {
351 // This nested-name-specifier occurs after another nested-name-specifier,
352 // so long into the context associated with the prior nested-name-specifier.
353 LookupCtx = computeDeclContext(SS, EnteringContext);
Richard Smith79810042018-05-11 02:43:08 +0000354 IsDependent = !LookupCtx;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000355
John McCalle66edc12009-11-24 19:00:30 +0000356 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000357 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
Richard Smith79810042018-05-11 02:43:08 +0000358 return true;
John McCalle66edc12009-11-24 19:00:30 +0000359 }
360
361 bool ObjectTypeSearchedInScope = false;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000362 bool AllowFunctionTemplatesInLookup = true;
John McCalle66edc12009-11-24 19:00:30 +0000363 if (LookupCtx) {
364 // Perform "qualified" name lookup into the declaration context we
365 // computed, which is either the type of the base of a member access
366 // expression or the declaration context associated with a prior
367 // nested-name-specifier.
368 LookupQualifiedName(Found, LookupCtx);
Simon Pilgrim6905d222016-12-30 22:55:33 +0000369
Richard Smith79810042018-05-11 02:43:08 +0000370 // FIXME: The C++ standard does not clearly specify what happens in the
371 // case where the object type is dependent, and implementations vary. In
372 // Clang, we treat a name after a . or -> as a template-name if lookup
373 // finds a non-dependent member or member of the current instantiation that
374 // is a type template, or finds no such members and lookup in the context
375 // of the postfix-expression finds a type template. In the latter case, the
376 // name is nonetheless dependent, and we may resolve it to a member of an
377 // unknown specialization when we come to instantiate the template.
378 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
John McCalle66edc12009-11-24 19:00:30 +0000379 }
380
Richard Smith79810042018-05-11 02:43:08 +0000381 if (!SS.isSet() && (ObjectType.isNull() || Found.empty())) {
382 // C++ [basic.lookup.classref]p1:
383 // In a class member access expression (5.2.5), if the . or -> token is
384 // immediately followed by an identifier followed by a <, the
385 // identifier must be looked up to determine whether the < is the
386 // beginning of a template argument list (14.2) or a less-than operator.
387 // The identifier is first looked up in the class of the object
388 // expression. If the identifier is not found, it is then looked up in
389 // the context of the entire postfix-expression and shall name a class
390 // template.
391 if (S)
392 LookupName(Found, S);
393
394 if (!ObjectType.isNull()) {
395 // FIXME: We should filter out all non-type templates here, particularly
396 // variable templates and concepts. But the exclusion of alias templates
397 // and template template parameters is a wording defect.
398 AllowFunctionTemplatesInLookup = false;
399 ObjectTypeSearchedInScope = true;
400 }
401
402 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
403 }
404
Richard Smithafcfb6b2019-02-15 21:53:07 +0000405 if (Found.isAmbiguous())
406 return false;
407
Richard Smith79810042018-05-11 02:43:08 +0000408 if (Found.empty() && !IsDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000409 // If we did not find any names, attempt to correct any typos.
410 DeclarationName Name = Found.getLookupName();
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000411 Found.clear();
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000412 // Simple filter callback that, for keywords, only accepts the C++ *_cast
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000413 auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
414 FilterCCC->WantTypeSpecifiers = false;
415 FilterCCC->WantExpressionKeywords = false;
416 FilterCCC->WantRemainingKeywords = false;
417 FilterCCC->WantCXXNamedCasts = true;
418 if (TypoCorrection Corrected = CorrectTypo(
419 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
420 std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000421 Found.setLookupName(Corrected.getCorrection());
Richard Smithde6d6c42015-12-29 19:43:10 +0000422 if (auto *ND = Corrected.getFoundDecl())
423 Found.addDecl(ND);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000424 FilterAcceptableTemplateNames(Found);
Richard Smithafcfb6b2019-02-15 21:53:07 +0000425 if (Found.isAmbiguous()) {
426 Found.clear();
427 } else if (!Found.empty()) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000428 if (LookupCtx) {
Richard Smithf9b15102013-08-17 00:46:16 +0000429 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
430 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000431 Name.getAsString() == CorrectedStr;
Richard Smithf9b15102013-08-17 00:46:16 +0000432 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
433 << Name << LookupCtx << DroppedSpecifier
434 << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000435 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000436 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000437 }
John McCalle9cccd82010-06-16 08:42:20 +0000438 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000439 } else {
Douglas Gregorc048c522010-06-29 19:27:42 +0000440 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000441 }
442 }
443
Richard Smith79810042018-05-11 02:43:08 +0000444 NamedDecl *ExampleLookupResult =
445 Found.empty() ? nullptr : Found.getRepresentativeDecl();
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000446 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000447 if (Found.empty()) {
Richard Smith79810042018-05-11 02:43:08 +0000448 if (IsDependent) {
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000449 MemberOfUnknownSpecialization = true;
Richard Smith79810042018-05-11 02:43:08 +0000450 return false;
451 }
452
453 // If a 'template' keyword was used, a lookup that finds only non-template
454 // names is an error.
455 if (ExampleLookupResult && TemplateKWLoc.isValid()) {
456 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
457 << Found.getLookupName() << SS.getRange();
Richard Smithcbebd622018-05-14 20:52:48 +0000458 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
Richard Smith79810042018-05-11 02:43:08 +0000459 diag::note_template_kw_refers_to_non_template)
460 << Found.getLookupName();
461 return true;
462 }
463
464 return false;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000465 }
John McCalle66edc12009-11-24 19:00:30 +0000466
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000467 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
Richard Smithe7d67f22013-09-03 21:22:41 +0000468 !getLangOpts().CPlusPlus11) {
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000469 // C++03 [basic.lookup.classref]p1:
John McCalle66edc12009-11-24 19:00:30 +0000470 // [...] If the lookup in the class of the object expression finds a
471 // template, the name is also looked up in the context of the entire
472 // postfix-expression and [...]
473 //
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000474 // Note: C++11 does not perform this second lookup.
John McCalle66edc12009-11-24 19:00:30 +0000475 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
476 LookupOrdinaryName);
Richard Smithafcfb6b2019-02-15 21:53:07 +0000477 FoundOuter.setTemplateNameLookup(true);
John McCalle66edc12009-11-24 19:00:30 +0000478 LookupName(FoundOuter, S);
Richard Smithafcfb6b2019-02-15 21:53:07 +0000479 // FIXME: We silently accept an ambiguous lookup here, in violation of
480 // [basic.lookup]/1.
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000481 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000482
Richard Smithafcfb6b2019-02-15 21:53:07 +0000483 NamedDecl *OuterTemplate;
John McCalle66edc12009-11-24 19:00:30 +0000484 if (FoundOuter.empty()) {
485 // - if the name is not found, the name found in the class of the
486 // object expression is used, otherwise
Richard Smithafcfb6b2019-02-15 21:53:07 +0000487 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
488 !(OuterTemplate =
489 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
John McCalle66edc12009-11-24 19:00:30 +0000490 // - if the name is found in the context of the entire
491 // postfix-expression and does not name a class template, the name
492 // found in the class of the object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000493 FoundOuter.clear();
John McCalle9cccd82010-06-16 08:42:20 +0000494 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000495 // - if the name found is a class template, it must refer to the same
496 // entity as the one found in the class of the object expression,
497 // otherwise the program is ill-formed.
498 if (!Found.isSingleResult() ||
Richard Smithafcfb6b2019-02-15 21:53:07 +0000499 getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
500 OuterTemplate->getCanonicalDecl()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000501 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000502 diag::ext_nested_name_member_ref_lookup_ambiguous)
503 << Found.getLookupName()
504 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000505 Diag(Found.getRepresentativeDecl()->getLocation(),
506 diag::note_ambig_member_ref_object_type)
507 << ObjectType;
508 Diag(FoundOuter.getFoundDecl()->getLocation(),
509 diag::note_ambig_member_ref_scope);
510
511 // Recover by taking the template that we found in the object
512 // expression's type.
513 }
514 }
515 }
Richard Smith79810042018-05-11 02:43:08 +0000516
517 return false;
John McCalle66edc12009-11-24 19:00:30 +0000518}
519
Richard Smith42bc73a2017-05-10 02:30:28 +0000520void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
521 SourceLocation Less,
522 SourceLocation Greater) {
523 if (TemplateName.isInvalid())
524 return;
525
526 DeclarationNameInfo NameInfo;
527 CXXScopeSpec SS;
528 LookupNameKind LookupKind;
529
530 DeclContext *LookupCtx = nullptr;
531 NamedDecl *Found = nullptr;
Richard Smithbf5bcf22018-06-26 23:20:26 +0000532 bool MissingTemplateKeyword = false;
Richard Smith42bc73a2017-05-10 02:30:28 +0000533
534 // Figure out what name we looked up.
Richard Smithbf5bcf22018-06-26 23:20:26 +0000535 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
536 NameInfo = DRE->getNameInfo();
537 SS.Adopt(DRE->getQualifierLoc());
538 LookupKind = LookupOrdinaryName;
539 Found = DRE->getFoundDecl();
540 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
Richard Smith42bc73a2017-05-10 02:30:28 +0000541 NameInfo = ME->getMemberNameInfo();
542 SS.Adopt(ME->getQualifierLoc());
543 LookupKind = LookupMemberName;
544 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
545 Found = ME->getMemberDecl();
Richard Smithbf5bcf22018-06-26 23:20:26 +0000546 } else if (auto *DSDRE =
547 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
548 NameInfo = DSDRE->getNameInfo();
549 SS.Adopt(DSDRE->getQualifierLoc());
550 MissingTemplateKeyword = true;
551 } else if (auto *DSME =
552 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
553 NameInfo = DSME->getMemberNameInfo();
554 SS.Adopt(DSME->getQualifierLoc());
555 MissingTemplateKeyword = true;
Richard Smith42bc73a2017-05-10 02:30:28 +0000556 } else {
Richard Smithbf5bcf22018-06-26 23:20:26 +0000557 llvm_unreachable("unexpected kind of potential template name");
558 }
559
560 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
561 // was missing.
562 if (MissingTemplateKeyword) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000563 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
564 << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
Richard Smithbf5bcf22018-06-26 23:20:26 +0000565 return;
Richard Smith42bc73a2017-05-10 02:30:28 +0000566 }
567
568 // Try to correct the name by looking for templates and C++ named casts.
569 struct TemplateCandidateFilter : CorrectionCandidateCallback {
Richard Smithafcfb6b2019-02-15 21:53:07 +0000570 Sema &S;
571 TemplateCandidateFilter(Sema &S) : S(S) {
Richard Smith42bc73a2017-05-10 02:30:28 +0000572 WantTypeSpecifiers = false;
573 WantExpressionKeywords = false;
574 WantRemainingKeywords = false;
575 WantCXXNamedCasts = true;
576 };
577 bool ValidateCandidate(const TypoCorrection &Candidate) override {
578 if (auto *ND = Candidate.getCorrectionDecl())
Richard Smithafcfb6b2019-02-15 21:53:07 +0000579 return S.getAsTemplateNameDecl(ND);
Richard Smith42bc73a2017-05-10 02:30:28 +0000580 return Candidate.isKeyword();
581 }
582 };
583
584 DeclarationName Name = NameInfo.getName();
585 if (TypoCorrection Corrected =
586 CorrectTypo(NameInfo, LookupKind, S, &SS,
Richard Smithafcfb6b2019-02-15 21:53:07 +0000587 llvm::make_unique<TemplateCandidateFilter>(*this),
Richard Smith42bc73a2017-05-10 02:30:28 +0000588 CTK_ErrorRecovery, LookupCtx)) {
589 auto *ND = Corrected.getFoundDecl();
590 if (ND)
Richard Smithafcfb6b2019-02-15 21:53:07 +0000591 ND = getAsTemplateNameDecl(ND);
Richard Smith42bc73a2017-05-10 02:30:28 +0000592 if (ND || Corrected.isKeyword()) {
593 if (LookupCtx) {
594 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
595 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
596 Name.getAsString() == CorrectedStr;
597 diagnoseTypo(Corrected,
598 PDiag(diag::err_non_template_in_member_template_id_suggest)
599 << Name << LookupCtx << DroppedSpecifier
Richard Smith52f8d192017-05-10 21:32:16 +0000600 << SS.getRange(), false);
Richard Smith42bc73a2017-05-10 02:30:28 +0000601 } else {
602 diagnoseTypo(Corrected,
603 PDiag(diag::err_non_template_in_template_id_suggest)
Richard Smith52f8d192017-05-10 21:32:16 +0000604 << Name, false);
Richard Smith42bc73a2017-05-10 02:30:28 +0000605 }
606 if (Found)
607 Diag(Found->getLocation(),
608 diag::note_non_template_in_template_id_found);
609 return;
610 }
611 }
612
613 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
614 << Name << SourceRange(Less, Greater);
615 if (Found)
616 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
617}
618
John McCallcd4b4772009-12-02 03:53:29 +0000619/// ActOnDependentIdExpression - Handle a dependent id-expression that
620/// was just parsed. This is only possible with an explicit scope
621/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000622ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000623Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000624 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000625 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000626 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000627 const TemplateArgumentListInfo *TemplateArgs) {
John McCall87fe5d52010-05-20 01:18:31 +0000628 DeclContext *DC = getFunctionLevelDeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000629
Reid Kleckner1af391df2016-03-11 18:59:12 +0000630 // C++11 [expr.prim.general]p12:
631 // An id-expression that denotes a non-static data member or non-static
632 // member function of a class can only be used:
633 // (...)
634 // - if that id-expression denotes a non-static data member and it
635 // appears in an unevaluated operand.
636 //
637 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
638 // CXXDependentScopeMemberExpr. The former can instantiate to either
639 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
640 // always a MemberExpr.
641 bool MightBeCxx11UnevalField =
642 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
643
Akira Hatanakad644e022016-12-16 03:19:41 +0000644 // Check if the nested name specifier is an enum type.
645 bool IsEnum = false;
646 if (NestedNameSpecifier *NNS = SS.getScopeRep())
647 IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
648
649 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
Reid Kleckner1af391df2016-03-11 18:59:12 +0000650 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
Brian Gesiak5488ab42019-01-11 01:54:53 +0000651 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000652
John McCalle66edc12009-11-24 19:00:30 +0000653 // Since the 'this' expression is synthesized, we don't need to
654 // perform the double-lookup check.
Craig Topperc3ec1492014-05-26 06:22:03 +0000655 NamedDecl *FirstQualifierInScope = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000656
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000657 return CXXDependentScopeMemberExpr::Create(
658 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
659 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
660 FirstQualifierInScope, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000661 }
662
Abramo Bagnara7945c982012-01-27 09:46:47 +0000663 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000664}
665
John McCalldadc5752010-08-24 06:29:42 +0000666ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000667Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000668 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000669 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000670 const TemplateArgumentListInfo *TemplateArgs) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000671 return DependentScopeDeclRefExpr::Create(
672 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
673 TemplateArgs);
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000674}
675
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000676
677/// Determine whether we would be unable to instantiate this template (because
678/// it either has no definition, or is in the process of being instantiated).
679bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
680 NamedDecl *Instantiation,
681 bool InstantiatedFromMember,
682 const NamedDecl *Pattern,
683 const NamedDecl *PatternDef,
684 TemplateSpecializationKind TSK,
685 bool Complain /*= true*/) {
Richard Smithedbc6e92016-10-14 21:41:24 +0000686 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
687 isa<VarDecl>(Instantiation));
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000688
Richard Smithedbc6e92016-10-14 21:41:24 +0000689 bool IsEntityBeingDefined = false;
690 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
691 IsEntityBeingDefined = TD->isBeingDefined();
692
693 if (PatternDef && !IsEntityBeingDefined) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000694 NamedDecl *SuggestedDef = nullptr;
695 if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
696 /*OnlyNeedComplete*/false)) {
697 // If we're allowed to diagnose this and recover, do so.
698 bool Recover = Complain && !isSFINAEContext();
699 if (Complain)
700 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
701 Sema::MissingImportKind::Definition, Recover);
702 return !Recover;
703 }
704 return false;
705 }
706
Richard Smith6f4e2e02016-08-23 19:41:39 +0000707 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
708 return true;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000709
Richard Smithedbc6e92016-10-14 21:41:24 +0000710 llvm::Optional<unsigned> Note;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000711 QualType InstantiationTy;
712 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
713 InstantiationTy = Context.getTypeDeclType(TD);
Richard Smith6f4e2e02016-08-23 19:41:39 +0000714 if (PatternDef) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000715 Diag(PointOfInstantiation,
716 diag::err_template_instantiate_within_definition)
Richard Smithedbc6e92016-10-14 21:41:24 +0000717 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000718 << InstantiationTy;
719 // Not much point in noting the template declaration here, since
720 // we're lexically inside it.
721 Instantiation->setInvalidDecl();
722 } else if (InstantiatedFromMember) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000723 if (isa<FunctionDecl>(Instantiation)) {
724 Diag(PointOfInstantiation,
725 diag::err_explicit_instantiation_undefined_member)
Richard Smithedbc6e92016-10-14 21:41:24 +0000726 << /*member function*/ 1 << Instantiation->getDeclName()
727 << Instantiation->getDeclContext();
728 Note = diag::note_explicit_instantiation_here;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000729 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000730 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
Richard Smith6f4e2e02016-08-23 19:41:39 +0000731 Diag(PointOfInstantiation,
732 diag::err_implicit_instantiate_member_undefined)
733 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000734 Note = diag::note_member_declared_at;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000735 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000736 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000737 if (isa<FunctionDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000738 Diag(PointOfInstantiation,
739 diag::err_explicit_instantiation_undefined_func_template)
740 << Pattern;
Richard Smithedbc6e92016-10-14 21:41:24 +0000741 Note = diag::note_explicit_instantiation_here;
742 } else if (isa<TagDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000743 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
744 << (TSK != TSK_ImplicitInstantiation)
745 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000746 Note = diag::note_template_decl_here;
747 } else {
748 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
749 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
750 Diag(PointOfInstantiation,
751 diag::err_explicit_instantiation_undefined_var_template)
752 << Instantiation;
753 Instantiation->setInvalidDecl();
754 } else
755 Diag(PointOfInstantiation,
756 diag::err_explicit_instantiation_undefined_member)
757 << /*static data member*/ 2 << Instantiation->getDeclName()
758 << Instantiation->getDeclContext();
759 Note = diag::note_explicit_instantiation_here;
760 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000761 }
Richard Smithedbc6e92016-10-14 21:41:24 +0000762 if (Note) // Diagnostics were emitted.
763 Diag(Pattern->getLocation(), Note.getValue());
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000764
765 // In general, Instantiation isn't marked invalid to get more than one
766 // error for multiple undefined instantiations. But the code that does
767 // explicit declaration -> explicit definition conversion can't handle
768 // invalid declarations, so mark as invalid in that case.
769 if (TSK == TSK_ExplicitInstantiationDeclaration)
770 Instantiation->setInvalidDecl();
771 return true;
772}
773
Douglas Gregor5101c242008-12-05 18:15:24 +0000774/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
775/// that the template parameter 'PrevDecl' is being shadowed by a new
776/// declaration at location Loc. Returns true to indicate that this is
777/// an error, and false otherwise.
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000778void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000779 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000780
781 // Microsoft Visual C++ permits template parameters to be shadowed.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000782 if (getLangOpts().MicrosoftExt)
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000783 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000784
785 // C++ [temp.local]p4:
786 // A template-parameter shall not be redeclared within its
787 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000788 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000789 << cast<NamedDecl>(PrevDecl)->getDeclName();
790 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregor5101c242008-12-05 18:15:24 +0000791}
792
Douglas Gregor463421d2009-03-03 04:44:36 +0000793/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000794/// the parameter D to reference the templated declaration and return a pointer
795/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000796TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
797 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
798 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000799 return Temp;
800 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000801 return nullptr;
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000802}
803
Douglas Gregoreb29d182011-01-05 17:40:24 +0000804ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
805 SourceLocation EllipsisLoc) const {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000806 assert(Kind == Template &&
Douglas Gregoreb29d182011-01-05 17:40:24 +0000807 "Only template template arguments can be pack expansions here");
808 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
809 "Template template argument pack expansion without packs");
810 ParsedTemplateArgument Result(*this);
811 Result.EllipsisLoc = EllipsisLoc;
812 return Result;
813}
814
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000815static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
816 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000817
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000818 switch (Arg.getKind()) {
819 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000820 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000821 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000822 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000823 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000824 return TemplateArgumentLoc(TemplateArgument(T), DI);
825 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000826
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000827 case ParsedTemplateArgument::NonType: {
828 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
829 return TemplateArgumentLoc(TemplateArgument(E), E);
830 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000831
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000832 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000833 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregore1d60df2011-01-14 23:41:42 +0000834 TemplateArgument TArg;
835 if (Arg.getEllipsisLoc().isValid())
David Blaikie05785d12013-02-20 22:23:23 +0000836 TArg = TemplateArgument(Template, Optional<unsigned int>());
Douglas Gregore1d60df2011-01-14 23:41:42 +0000837 else
838 TArg = Template;
839 return TemplateArgumentLoc(TArg,
Douglas Gregor9d802122011-03-02 17:09:35 +0000840 Arg.getScopeSpec().getWithLocInContext(
841 SemaRef.Context),
Douglas Gregoreb29d182011-01-05 17:40:24 +0000842 Arg.getLocation(),
843 Arg.getEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000844 }
845 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000846
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000847 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000848}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000849
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000850/// Translates template arguments as provided by the parser
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000851/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000852void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
853 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000854 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000855 TemplateArgs.addArgument(translateTemplateArgument(*this,
856 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000857}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000858
Richard Smithb80d5402013-06-25 22:21:36 +0000859static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
860 SourceLocation Loc,
861 IdentifierInfo *Name) {
862 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
Richard Smithbecb92d2017-10-10 22:33:17 +0000863 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
Richard Smithb80d5402013-06-25 22:21:36 +0000864 if (PrevDecl && PrevDecl->isTemplateParameter())
865 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
866}
867
Richard Smith77a9c602018-02-28 03:02:23 +0000868/// Convert a parsed type into a parsed template argument. This is mostly
869/// trivial, except that we may have parsed a C++17 deduced class template
870/// specialization type, in which case we should form a template template
871/// argument instead of a type template argument.
872ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
873 TypeSourceInfo *TInfo;
874 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
875 if (T.isNull())
876 return ParsedTemplateArgument();
877 assert(TInfo && "template argument with no location");
878
879 // If we might have formed a deduced template specialization type, convert
880 // it to a template template argument.
881 if (getLangOpts().CPlusPlus17) {
882 TypeLoc TL = TInfo->getTypeLoc();
883 SourceLocation EllipsisLoc;
884 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
885 EllipsisLoc = PET.getEllipsisLoc();
886 TL = PET.getPatternLoc();
887 }
888
889 CXXScopeSpec SS;
890 if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
891 SS.Adopt(ET.getQualifierLoc());
892 TL = ET.getNamedTypeLoc();
893 }
894
895 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
896 TemplateName Name = DTST.getTypePtr()->getTemplateName();
897 if (SS.isSet())
898 Name = Context.getQualifiedTemplateName(SS.getScopeRep(),
899 /*HasTemplateKeyword*/ false,
900 Name.getAsTemplateDecl());
901 ParsedTemplateArgument Result(SS, TemplateTy::make(Name),
902 DTST.getTemplateNameLoc());
903 if (EllipsisLoc.isValid())
904 Result = Result.getTemplatePackExpansion(EllipsisLoc);
905 return Result;
906 }
907 }
908
909 // This is a normal type template argument. Note, if the type template
910 // argument is an injected-class-name for a template, it has a dual nature
Fangrui Song6907ce22018-07-30 19:24:48 +0000911 // and can be used as either a type or a template. We handle that in
Richard Smith77a9c602018-02-28 03:02:23 +0000912 // convertTypeTemplateArgumentToTemplate.
913 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
914 ParsedType.get().getAsOpaquePtr(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000915 TInfo->getTypeLoc().getBeginLoc());
Richard Smith77a9c602018-02-28 03:02:23 +0000916}
917
Douglas Gregor5101c242008-12-05 18:15:24 +0000918/// ActOnTypeParameter - Called when a C++ template type parameter
919/// (e.g., "typename T") has been parsed. Typename specifies whether
920/// the keyword "typename" was used to declare the type parameter
921/// (otherwise, "class" was used), and KeyLoc is the location of the
922/// "class" or "typename" keyword. ParamName is the name of the
923/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth08836322011-05-01 00:51:33 +0000924/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000925/// If the type parameter has a default argument, it will be added
926/// later via ActOnTypeParameterDefault.
Faisal Valibe294032017-12-23 18:56:34 +0000927NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
John McCall48871652010-08-21 09:40:31 +0000928 SourceLocation EllipsisLoc,
929 SourceLocation KeyLoc,
930 IdentifierInfo *ParamName,
931 SourceLocation ParamNameLoc,
932 unsigned Depth, unsigned Position,
933 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000934 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000935 assert(S->isTemplateParamScope() &&
936 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000937
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000938 SourceLocation Loc = ParamNameLoc;
939 if (!ParamName)
940 Loc = KeyLoc;
941
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000942 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregor5101c242008-12-05 18:15:24 +0000943 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000944 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000945 KeyLoc, Loc, Depth, Position, ParamName,
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000946 Typename, IsParameterPack);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000947 Param->setAccess(AS_public);
Douglas Gregor5101c242008-12-05 18:15:24 +0000948
949 if (ParamName) {
Richard Smithb80d5402013-06-25 22:21:36 +0000950 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
951
Douglas Gregor5101c242008-12-05 18:15:24 +0000952 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000953 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000954 IdResolver.AddDecl(Param);
955 }
956
Douglas Gregorf5500772011-01-05 15:48:55 +0000957 // C++0x [temp.param]p9:
958 // A default template-argument may be specified for any kind of
959 // template-parameter that is not a template parameter pack.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000960 if (DefaultArg && IsParameterPack) {
Douglas Gregorf5500772011-01-05 15:48:55 +0000961 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
David Blaikieefdccaa2016-01-15 23:43:34 +0000962 DefaultArg = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000963 }
964
Douglas Gregordc13ded2010-07-01 00:00:45 +0000965 // Handle the default argument, if provided.
966 if (DefaultArg) {
967 TypeSourceInfo *DefaultTInfo;
968 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000969
Douglas Gregordc13ded2010-07-01 00:00:45 +0000970 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000971
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000972 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000973 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000974 UPPC_DefaultArgument))
975 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000976
Douglas Gregordc13ded2010-07-01 00:00:45 +0000977 // Check the template argument itself.
978 if (CheckTemplateArgument(Param, DefaultTInfo)) {
979 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000980 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000981 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000982
Richard Smith1469b912015-06-10 00:29:03 +0000983 Param->setDefaultArgument(DefaultTInfo);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000984 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000985
John McCall48871652010-08-21 09:40:31 +0000986 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000987}
988
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000989/// Check that the type of a non-type template parameter is
Douglas Gregor463421d2009-03-03 04:44:36 +0000990/// well-formed.
991///
992/// \returns the (possibly-promoted) parameter type if valid;
993/// otherwise, produces a diagnostic and returns a NULL type.
Richard Smith15361a22016-12-28 06:27:18 +0000994QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
995 SourceLocation Loc) {
996 if (TSI->getType()->isUndeducedType()) {
Erik Pilkington9f9462a2018-08-07 22:59:02 +0000997 // C++17 [temp.dep.expr]p3:
Richard Smith15361a22016-12-28 06:27:18 +0000998 // An id-expression is type-dependent if it contains
999 // - an identifier associated by name lookup with a non-type
1000 // template-parameter declared with a type that contains a
1001 // placeholder type (7.1.7.4),
1002 TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
1003 }
1004
1005 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1006}
1007
1008QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
1009 SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +00001010 // We don't allow variably-modified types as the type of non-type template
1011 // parameters.
1012 if (T->isVariablyModifiedType()) {
1013 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1014 << T;
1015 return QualType();
1016 }
1017
Douglas Gregor463421d2009-03-03 04:44:36 +00001018 // C++ [temp.param]p4:
1019 //
1020 // A non-type template-parameter shall have one of the following
1021 // (optionally cv-qualified) types:
1022 //
1023 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +00001024 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +00001025 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +00001026 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +00001027 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +00001028 T->isReferenceType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +00001029 // -- pointer to member,
Douglas Gregor463421d2009-03-03 04:44:36 +00001030 T->isMemberPointerType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +00001031 // -- std::nullptr_t.
1032 T->isNullPtrType() ||
Douglas Gregor463421d2009-03-03 04:44:36 +00001033 // If T is a dependent type, we can't do the check now, so we
1034 // assume that it is well-formed.
Richard Smith5f274382016-09-28 23:55:27 +00001035 T->isDependentType() ||
1036 // Allow use of auto in template parameter declarations.
1037 T->isUndeducedType()) {
Richard Smithd0e1c952012-03-13 07:21:50 +00001038 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1039 // are ignored when determining its type.
1040 return T.getUnqualifiedType();
1041 }
1042
Douglas Gregor463421d2009-03-03 04:44:36 +00001043 // C++ [temp.param]p8:
1044 //
1045 // A non-type template-parameter of type "array of T" or
1046 // "function returning T" is adjusted to be of type "pointer to
1047 // T" or "pointer to function returning T", respectively.
Richard Smithd663fdd2014-12-17 20:42:37 +00001048 else if (T->isArrayType() || T->isFunctionType())
1049 return Context.getDecayedType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001050
Douglas Gregor463421d2009-03-03 04:44:36 +00001051 Diag(Loc, diag::err_template_nontype_parm_bad_type)
1052 << T;
1053
1054 return QualType();
1055}
1056
Faisal Valibe294032017-12-23 18:56:34 +00001057NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
John McCall48871652010-08-21 09:40:31 +00001058 unsigned Depth,
1059 unsigned Position,
1060 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +00001061 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +00001062 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Richard Smith15361a22016-12-28 06:27:18 +00001063
Faisal Valia223d1c2017-12-22 03:50:55 +00001064 // Check that we have valid decl-specifiers specified.
1065 auto CheckValidDeclSpecifiers = [this, &D] {
1066 // C++ [temp.param]
Fangrui Song6907ce22018-07-30 19:24:48 +00001067 // p1
Malcolm Parsonsfab36802018-04-16 08:31:08 +00001068 // template-parameter:
1069 // ...
1070 // parameter-declaration
Fangrui Song6907ce22018-07-30 19:24:48 +00001071 // p2
Faisal Valia223d1c2017-12-22 03:50:55 +00001072 // ... A storage class shall not be specified in a template-parameter
1073 // declaration.
Fangrui Song6907ce22018-07-30 19:24:48 +00001074 // [dcl.typedef]p1:
Faisal Valia223d1c2017-12-22 03:50:55 +00001075 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1076 // of a parameter-declaration
1077 const DeclSpec &DS = D.getDeclSpec();
1078 auto EmitDiag = [this](SourceLocation Loc) {
1079 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1080 << FixItHint::CreateRemoval(Loc);
1081 };
1082 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1083 EmitDiag(DS.getStorageClassSpecLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00001084
Sam McCall1371cba2017-12-22 07:09:51 +00001085 if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
Faisal Valia223d1c2017-12-22 03:50:55 +00001086 EmitDiag(DS.getThreadStorageClassSpecLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00001087
1088 // [dcl.inline]p1:
1089 // The inline specifier can be applied only to the declaration or
Faisal Valia223d1c2017-12-22 03:50:55 +00001090 // definition of a variable or function.
Fangrui Song6907ce22018-07-30 19:24:48 +00001091
Faisal Valia223d1c2017-12-22 03:50:55 +00001092 if (DS.isInlineSpecified())
1093 EmitDiag(DS.getInlineSpecLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00001094
Faisal Valia223d1c2017-12-22 03:50:55 +00001095 // [dcl.constexpr]p1:
Fangrui Song6907ce22018-07-30 19:24:48 +00001096 // The constexpr specifier shall be applied only to the definition of a
1097 // variable or variable template or the declaration of a function or
Faisal Valia223d1c2017-12-22 03:50:55 +00001098 // function template.
Fangrui Song6907ce22018-07-30 19:24:48 +00001099
Faisal Valia223d1c2017-12-22 03:50:55 +00001100 if (DS.isConstexprSpecified())
1101 EmitDiag(DS.getConstexprSpecLoc());
1102
1103 // [dcl.fct.spec]p1:
1104 // Function-specifiers can be used only in function declarations.
1105
1106 if (DS.isVirtualSpecified())
1107 EmitDiag(DS.getVirtualSpecLoc());
1108
1109 if (DS.isExplicitSpecified())
1110 EmitDiag(DS.getExplicitSpecLoc());
1111
1112 if (DS.isNoreturnSpecified())
1113 EmitDiag(DS.getNoreturnSpecLoc());
1114 };
1115
1116 CheckValidDeclSpecifiers();
Fangrui Song6907ce22018-07-30 19:24:48 +00001117
Richard Smith15361a22016-12-28 06:27:18 +00001118 if (TInfo->getType()->isUndeducedType()) {
1119 Diag(D.getIdentifierLoc(),
1120 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1121 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1122 }
Douglas Gregor5101c242008-12-05 18:15:24 +00001123
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001124 assert(S->isTemplateParamScope() &&
1125 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +00001126 bool Invalid = false;
1127
Richard Smith15361a22016-12-28 06:27:18 +00001128 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001129 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001130 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +00001131 Invalid = true;
1132 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001133
Richard Smithb80d5402013-06-25 22:21:36 +00001134 IdentifierInfo *ParamName = D.getIdentifier();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +00001135 bool IsParameterPack = D.hasEllipsis();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001136 NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
1137 Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1138 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1139 TInfo);
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001140 Param->setAccess(AS_public);
Richard Smithb80d5402013-06-25 22:21:36 +00001141
Douglas Gregor5101c242008-12-05 18:15:24 +00001142 if (Invalid)
1143 Param->setInvalidDecl();
1144
Richard Smithb80d5402013-06-25 22:21:36 +00001145 if (ParamName) {
1146 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1147 ParamName);
1148
Douglas Gregor5101c242008-12-05 18:15:24 +00001149 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +00001150 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +00001151 IdResolver.AddDecl(Param);
1152 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001153
Douglas Gregorf5500772011-01-05 15:48:55 +00001154 // C++0x [temp.param]p9:
1155 // A default template-argument may be specified for any kind of
1156 // template-parameter that is not a template parameter pack.
1157 if (Default && IsParameterPack) {
1158 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
Craig Topperc3ec1492014-05-26 06:22:03 +00001159 Default = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +00001160 }
1161
Douglas Gregordc13ded2010-07-01 00:00:45 +00001162 // Check the well-formedness of the default template argument, if provided.
Douglas Gregorda3cc0d2010-12-23 23:51:58 +00001163 if (Default) {
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001164 // Check for unexpanded parameter packs.
1165 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
1166 return Param;
1167
Douglas Gregordc13ded2010-07-01 00:00:45 +00001168 TemplateArgument Converted;
Richard Smithd663fdd2014-12-17 20:42:37 +00001169 ExprResult DefaultRes =
1170 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
John Wiegley01296292011-04-08 18:41:53 +00001171 if (DefaultRes.isInvalid()) {
Douglas Gregordc13ded2010-07-01 00:00:45 +00001172 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +00001173 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +00001174 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001175 Default = DefaultRes.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001176
Richard Smith1469b912015-06-10 00:29:03 +00001177 Param->setDefaultArgument(Default);
Douglas Gregordc13ded2010-07-01 00:00:45 +00001178 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001179
John McCall48871652010-08-21 09:40:31 +00001180 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +00001181}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001182
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001183/// ActOnTemplateTemplateParameter - Called when a C++ template template
James Dennett2a4d13c2012-06-15 07:13:21 +00001184/// parameter (e.g. T in template <template \<typename> class T> class array)
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001185/// has been parsed. S is the current scope.
Faisal Valibe294032017-12-23 18:56:34 +00001186NamedDecl *Sema::ActOnTemplateTemplateParameter(Scope* S,
John McCall48871652010-08-21 09:40:31 +00001187 SourceLocation TmpLoc,
Richard Trieu9becef62011-09-09 03:18:59 +00001188 TemplateParameterList *Params,
Douglas Gregorf5500772011-01-05 15:48:55 +00001189 SourceLocation EllipsisLoc,
John McCall48871652010-08-21 09:40:31 +00001190 IdentifierInfo *Name,
1191 SourceLocation NameLoc,
1192 unsigned Depth,
1193 unsigned Position,
1194 SourceLocation EqualLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +00001195 ParsedTemplateArgument Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001196 assert(S->isTemplateParamScope() &&
1197 "Template template parameter not in template parameter scope!");
1198
1199 // Construct the parameter object.
Douglas Gregorf5500772011-01-05 15:48:55 +00001200 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001201 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +00001202 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001203 NameLoc.isInvalid()? TmpLoc : NameLoc,
1204 Depth, Position, IsParameterPack,
Douglas Gregorf5500772011-01-05 15:48:55 +00001205 Name, Params);
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001206 Param->setAccess(AS_public);
Simon Pilgrim6905d222016-12-30 22:55:33 +00001207
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001208 // If the template template parameter has a name, then link the identifier
Douglas Gregordc13ded2010-07-01 00:00:45 +00001209 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001210 if (Name) {
Richard Smithb80d5402013-06-25 22:21:36 +00001211 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1212
John McCall48871652010-08-21 09:40:31 +00001213 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001214 IdResolver.AddDecl(Param);
1215 }
1216
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001217 if (Params->size() == 0) {
1218 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1219 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1220 Param->setInvalidDecl();
1221 }
1222
Douglas Gregorf5500772011-01-05 15:48:55 +00001223 // C++0x [temp.param]p9:
1224 // A default template-argument may be specified for any kind of
1225 // template-parameter that is not a template parameter pack.
1226 if (IsParameterPack && !Default.isInvalid()) {
1227 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1228 Default = ParsedTemplateArgument();
1229 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001230
Douglas Gregordc13ded2010-07-01 00:00:45 +00001231 if (!Default.isInvalid()) {
1232 // Check only that we have a template template argument. We don't want to
1233 // try to check well-formedness now, because our template template parameter
1234 // might have dependent types in its template parameters, which we wouldn't
1235 // be able to match now.
1236 //
1237 // If none of the template template parameter's template arguments mention
1238 // other template parameters, we could actually perform more checking here.
1239 // However, it isn't worth doing.
1240 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1241 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
Faisal Valib8b04f82016-03-26 20:46:45 +00001242 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
Douglas Gregordc13ded2010-07-01 00:00:45 +00001243 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00001244 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +00001245 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001246
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001247 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001248 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001249 DefaultArg.getArgument().getAsTemplate(),
1250 UPPC_DefaultArgument))
1251 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001252
Richard Smith1469b912015-06-10 00:29:03 +00001253 Param->setDefaultArgument(Context, DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +00001254 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001255
John McCall48871652010-08-21 09:40:31 +00001256 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +00001257}
1258
Hubert Tongf608c052016-04-29 18:05:37 +00001259/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1260/// constrained by RequiresClause, that contains the template parameters in
1261/// Params.
Richard Trieu9becef62011-09-09 03:18:59 +00001262TemplateParameterList *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001263Sema::ActOnTemplateParameterList(unsigned Depth,
1264 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001265 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001266 SourceLocation LAngleLoc,
Faisal Valif241b0d2017-08-25 18:24:20 +00001267 ArrayRef<NamedDecl *> Params,
Hubert Tongf608c052016-04-29 18:05:37 +00001268 SourceLocation RAngleLoc,
1269 Expr *RequiresClause) {
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001270 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001271 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001272
David Majnemer902f8c62015-12-27 07:16:27 +00001273 return TemplateParameterList::Create(
1274 Context, TemplateLoc, LAngleLoc,
Faisal Valif241b0d2017-08-25 18:24:20 +00001275 llvm::makeArrayRef(Params.data(), Params.size()),
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00001276 RAngleLoc, RequiresClause);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001277}
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001278
Bruno Ricci4224c872018-12-21 14:35:24 +00001279static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
1280 const CXXScopeSpec &SS) {
John McCall3e11ebe2010-03-15 10:12:16 +00001281 if (SS.isSet())
Bruno Ricci4224c872018-12-21 14:35:24 +00001282 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
John McCall3e11ebe2010-03-15 10:12:16 +00001283}
1284
Erich Keanec480f302018-07-12 21:09:05 +00001285DeclResult Sema::CheckClassTemplate(
1286 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1287 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1288 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1289 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1290 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1291 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
Mike Stump11289f42009-09-09 15:08:12 +00001292 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001293 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +00001294 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +00001295 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001296
1297 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001298 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001299 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001300
Abramo Bagnara6150c882010-05-11 21:36:43 +00001301 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1302 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001303
1304 // There is no such thing as an unnamed class template.
1305 if (!Name) {
1306 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001307 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001308 }
1309
Richard Smith6483d222012-04-21 01:27:54 +00001310 // Find any previous declaration with this name. For a friend with no
1311 // scope explicitly specified, we only look for tag declarations (per
1312 // C++11 [basic.lookup.elab]p2).
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001313 DeclContext *SemanticContext;
Richard Smith6483d222012-04-21 01:27:54 +00001314 LookupResult Previous(*this, Name, NameLoc,
1315 (SS.isEmpty() && TUK == TUK_Friend)
1316 ? LookupTagName : LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00001317 forRedeclarationInCurContext());
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001318 if (SS.isNotEmpty() && !SS.isInvalid()) {
1319 SemanticContext = computeDeclContext(SS, true);
1320 if (!SemanticContext) {
Douglas Gregor67daacb2012-03-30 16:20:47 +00001321 // FIXME: Horrible, horrible hack! We can't currently represent this
1322 // in the AST, and historically we have just ignored such friend
1323 // class templates, so don't complain here.
Richard Smithcd556eb2013-11-08 18:59:56 +00001324 Diag(NameLoc, TUK == TUK_Friend
1325 ? diag::warn_template_qualified_friend_ignored
1326 : diag::err_template_qualified_declarator_no_match)
Douglas Gregor67daacb2012-03-30 16:20:47 +00001327 << SS.getScopeRep() << SS.getRange();
Richard Smithcd556eb2013-11-08 18:59:56 +00001328 return TUK != TUK_Friend;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001329 }
Mike Stump11289f42009-09-09 15:08:12 +00001330
John McCall0b66eb32010-05-01 00:40:08 +00001331 if (RequireCompleteDeclContext(SS, SemanticContext))
1332 return true;
1333
Simon Pilgrim6905d222016-12-30 22:55:33 +00001334 // If we're adding a template to a dependent context, we may need to
1335 // rebuilding some of the types used within the template parameter list,
Douglas Gregor041b0842011-10-14 15:31:12 +00001336 // now that we know what the current instantiation is.
1337 if (SemanticContext->isDependentContext()) {
1338 ContextRAII SavedContext(*this, SemanticContext);
1339 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1340 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00001341 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
Richard Smithc660c8f2018-03-16 13:36:56 +00001342 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc, false);
Richard Smith6483d222012-04-21 01:27:54 +00001343
John McCall27b18f82009-11-17 02:14:36 +00001344 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001345 } else {
1346 SemanticContext = CurContext;
Richard Smith88fe69c2015-07-06 01:45:27 +00001347
1348 // C++14 [class.mem]p14:
1349 // If T is the name of a class, then each of the following shall have a
1350 // name different from T:
1351 // -- every member template of class T
1352 if (TUK != TUK_Friend &&
1353 DiagnoseClassNameShadow(SemanticContext,
1354 DeclarationNameInfo(Name, NameLoc)))
1355 return true;
1356
John McCall27b18f82009-11-17 02:14:36 +00001357 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001358 }
Mike Stump11289f42009-09-09 15:08:12 +00001359
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001360 if (Previous.isAmbiguous())
1361 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001362
Craig Topperc3ec1492014-05-26 06:22:03 +00001363 NamedDecl *PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001364 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001365 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001366
Serge Pavlove50bf752016-06-10 04:39:07 +00001367 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1368 // Maybe we will complain about the shadowed template parameter.
1369 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1370 // Just pretend that we didn't see the previous declaration.
1371 PrevDecl = nullptr;
1372 }
1373
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001374 // If there is a previous declaration with the same name, check
1375 // whether this is a valid redeclaration.
Richard Smithbecb92d2017-10-10 22:33:17 +00001376 ClassTemplateDecl *PrevClassTemplate =
1377 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001378
1379 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001380 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001381 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001382 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001383 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1384 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001385 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001386 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1387 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1388 PrevClassTemplate
1389 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1390 ->getSpecializedTemplate();
1391 }
1392 }
1393
John McCalld43784f2009-12-18 11:25:59 +00001394 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +00001395 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001396 // [...] When looking for a prior declaration of a class or a function
1397 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +00001398 // function is neither a qualified name nor a template-id, scopes outside
1399 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +00001400 if (!SS.isSet()) {
1401 DeclContext *OutermostContext = CurContext;
1402 while (!OutermostContext->isFileContext())
1403 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +00001404
Richard Smith61e582f2012-04-20 07:12:26 +00001405 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +00001406 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1407 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1408 SemanticContext = PrevDecl->getDeclContext();
1409 } else {
1410 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001411 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +00001412 // declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00001413 PrevDecl = PrevClassTemplate = nullptr;
Douglas Gregorb74b1032010-04-18 17:37:40 +00001414 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +00001415
1416 // Check that the chosen semantic context doesn't already contain a
1417 // declaration of this name as a non-tag type.
Richard Smithfc805ca2015-07-06 04:43:58 +00001418 Previous.clear(LookupOrdinaryName);
Richard Smith6483d222012-04-21 01:27:54 +00001419 DeclContext *LookupContext = SemanticContext;
1420 while (LookupContext->isTransparentContext())
1421 LookupContext = LookupContext->getLookupParent();
1422 LookupQualifiedName(Previous, LookupContext);
1423
1424 if (Previous.isAmbiguous())
1425 return true;
1426
1427 if (Previous.begin() != Previous.end())
1428 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +00001429 }
John McCall90d3bb92009-12-17 23:21:11 +00001430 }
Richard Smith72bcaec2013-12-05 04:30:04 +00001431 } else if (PrevDecl &&
Richard Smithfc805ca2015-07-06 04:43:58 +00001432 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1433 S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +00001434 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001435
Richard Smithfc805ca2015-07-06 04:43:58 +00001436 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1437 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1438 if (SS.isEmpty() &&
1439 !(PrevClassTemplate &&
1440 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1441 SemanticContext->getRedeclContext()))) {
1442 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1443 Diag(Shadow->getTargetDecl()->getLocation(),
1444 diag::note_using_decl_target);
1445 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1446 // Recover by ignoring the old declaration.
1447 PrevDecl = PrevClassTemplate = nullptr;
1448 }
1449 }
1450
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001451 // TODO Memory management; associated constraints are not always stored.
1452 Expr *const CurAC = formAssociatedConstraints(TemplateParams, nullptr);
1453
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001454 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +00001455 // Ensure that the template parameter lists are compatible. Skip this check
1456 // for a friend in a dependent context: the template parameter list itself
1457 // could be dependent.
1458 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1459 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001460 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001461 /*Complain=*/true,
1462 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001463 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001464
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001465 // Check for matching associated constraints on redeclarations.
1466 const Expr *const PrevAC = PrevClassTemplate->getAssociatedConstraints();
1467 const bool RedeclACMismatch = [&] {
1468 if (!(CurAC || PrevAC))
1469 return false; // Nothing to check; no mismatch.
1470 if (CurAC && PrevAC) {
1471 llvm::FoldingSetNodeID CurACInfo, PrevACInfo;
1472 CurAC->Profile(CurACInfo, Context, /*Canonical=*/true);
1473 PrevAC->Profile(PrevACInfo, Context, /*Canonical=*/true);
1474 if (CurACInfo == PrevACInfo)
1475 return false; // All good; no mismatch.
1476 }
1477 return true;
1478 }();
1479
1480 if (RedeclACMismatch) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001481 Diag(CurAC ? CurAC->getBeginLoc() : NameLoc,
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001482 diag::err_template_different_associated_constraints);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001483 Diag(PrevAC ? PrevAC->getBeginLoc() : PrevClassTemplate->getLocation(),
1484 diag::note_template_prev_declaration)
1485 << /*declaration*/ 0;
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001486 return true;
1487 }
1488
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001489 // C++ [temp.class]p4:
1490 // In a redeclaration, partial specialization, explicit
1491 // specialization or explicit instantiation of a class template,
1492 // the class-key shall agree in kind with the original class
1493 // template declaration (7.1.5.3).
1494 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +00001495 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001496 TUK == TUK_Definition, KWLoc, Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00001497 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00001498 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00001499 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001500 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00001501 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001502 }
1503
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001504 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +00001505 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001506 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001507 // If we have a prior definition that is not visible, treat this as
1508 // simply making that previous definition visible.
1509 NamedDecl *Hidden = nullptr;
1510 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
Richard Smithd9ba2242015-05-07 03:54:19 +00001511 SkipBody->ShouldSkip = true;
Richard Smithc4577662018-09-12 02:13:47 +00001512 SkipBody->Previous = Def;
Richard Smithbe3980b2015-03-27 00:41:57 +00001513 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1514 assert(Tmpl && "original definition of a class template is not a "
1515 "class template?");
Richard Smith858e0e02017-05-11 23:11:16 +00001516 makeMergedDefinitionVisible(Hidden);
1517 makeMergedDefinitionVisible(Tmpl);
Richard Smithc4577662018-09-12 02:13:47 +00001518 } else {
1519 Diag(NameLoc, diag::err_redefinition) << Name;
1520 Diag(Def->getLocation(), diag::note_previous_definition);
1521 // FIXME: Would it make sense to try to "forget" the previous
1522 // definition, as part of error recovery?
1523 return true;
Richard Smithbe3980b2015-03-27 00:41:57 +00001524 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001525 }
Serge Pavlove50bf752016-06-10 04:39:07 +00001526 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001527 } else if (PrevDecl) {
1528 // C++ [temp]p5:
1529 // A class template shall not have the same name as any other
1530 // template, class, function, object, enumeration, enumerator,
1531 // namespace, or type in the same scope (3.3), except as specified
1532 // in (14.5.4).
1533 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1534 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001535 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001536 }
1537
Douglas Gregordba32632009-02-10 19:49:53 +00001538 // Check the template parameter list of this declaration, possibly
1539 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001540 // template declaration. Skip this check for a friend in a dependent
1541 // context, because the template parameter list might be dependent.
1542 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001543 CheckTemplateParameterList(
1544 TemplateParams,
Richard Smithc4577662018-09-12 02:13:47 +00001545 PrevClassTemplate
1546 ? PrevClassTemplate->getMostRecentDecl()->getTemplateParameters()
1547 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001548 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1549 SemanticContext->isDependentContext())
1550 ? TPC_ClassTemplateMember
Richard Smithc4577662018-09-12 02:13:47 +00001551 : TUK == TUK_Friend ? TPC_FriendClassTemplate : TPC_ClassTemplate,
1552 SkipBody))
Douglas Gregordba32632009-02-10 19:49:53 +00001553 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001554
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001555 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001556 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001557 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001558 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1559 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001560 : diag::err_member_decl_does_not_match)
1561 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001562 Invalid = true;
1563 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001564 }
1565
Vassil Vassilev352e4412017-01-12 09:16:26 +00001566 // If this is a templated friend in a dependent context we should not put it
1567 // on the redecl chain. In some cases, the templated friend can be the most
1568 // recent declaration tricking the template instantiator to make substitutions
1569 // there.
1570 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1571 bool ShouldAddRedecl
1572 = !(TUK == TUK_Friend && CurContext->isDependentContext());
1573
Mike Stump11289f42009-09-09 15:08:12 +00001574 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001575 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Vassil Vassilev352e4412017-01-12 09:16:26 +00001576 PrevClassTemplate && ShouldAddRedecl ?
Craig Topperc3ec1492014-05-26 06:22:03 +00001577 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001578 /*DelayTypeCreation=*/true);
Bruno Ricci4224c872018-12-21 14:35:24 +00001579 SetNestedNameSpecifier(*this, NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001580 if (NumOuterTemplateParamLists > 0)
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001581 NewClass->setTemplateParameterListsInfo(
1582 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1583 NumOuterTemplateParamLists));
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001584
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001585 // Add alignment attributes if necessary; these attributes are checked when
1586 // the ASTContext lays out the structure.
Richard Smithc4577662018-09-12 02:13:47 +00001587 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
Eli Friedman0415f3e12012-08-08 21:08:34 +00001588 AddAlignmentAttributesForRecord(NewClass);
1589 AddMsStructLayoutForRecord(NewClass);
1590 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001591
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001592 // Attach the associated constraints when the declaration will not be part of
1593 // a decl chain.
1594 Expr *const ACtoAttach =
1595 PrevClassTemplate && ShouldAddRedecl ? nullptr : CurAC;
1596
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001597 ClassTemplateDecl *NewTemplate
1598 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1599 DeclarationName(Name), TemplateParams,
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001600 NewClass, ACtoAttach);
Vassil Vassilev352e4412017-01-12 09:16:26 +00001601
1602 if (ShouldAddRedecl)
1603 NewTemplate->setPreviousDecl(PrevClassTemplate);
1604
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001605 NewClass->setDescribedClassTemplate(NewTemplate);
Simon Pilgrim6905d222016-12-30 22:55:33 +00001606
Douglas Gregor21823bf2011-12-20 18:11:52 +00001607 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001608 NewTemplate->setModulePrivate();
Simon Pilgrim6905d222016-12-30 22:55:33 +00001609
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001610 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001611 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001612 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001613 assert(T->isDependentType() && "Class template type is not dependent?");
1614 (void)T;
1615
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001616 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001617 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001618 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001619 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1620 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001621
Anders Carlsson137108d2009-03-26 01:24:28 +00001622 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001623 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001624 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001625
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001626 // Set the lexical context of these templates
1627 NewClass->setLexicalDeclContext(CurContext);
1628 NewTemplate->setLexicalDeclContext(CurContext);
1629
Richard Smithc4577662018-09-12 02:13:47 +00001630 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001631 NewClass->startDefinition();
1632
Erich Keanec480f302018-07-12 21:09:05 +00001633 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001634
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001635 if (PrevClassTemplate)
1636 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1637
Rafael Espindola385c0422012-07-13 18:04:45 +00001638 AddPushedVisibilityAttribute(NewClass);
1639
Richard Smith234ff472014-08-23 00:49:01 +00001640 if (TUK != TUK_Friend) {
1641 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1642 Scope *Outer = S;
1643 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1644 Outer = Outer->getParent();
1645 PushOnScopeChains(NewTemplate, Outer);
1646 } else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001647 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001648 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001649 NewClass->setAccess(PrevClassTemplate->getAccess());
1650 }
John McCall27b5c252009-09-14 21:59:20 +00001651
Richard Smith64017682013-07-17 23:53:16 +00001652 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001653
John McCall27b5c252009-09-14 21:59:20 +00001654 // Friend templates are visible in fairly strange ways.
1655 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001656 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001657 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001658 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1659 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001660 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001661 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001662
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001663 FriendDecl *Friend = FriendDecl::Create(
1664 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
Douglas Gregor3dad8422009-09-26 06:47:28 +00001665 Friend->setAccess(AS_public);
1666 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001667 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001668
Richard Smithbecb92d2017-10-10 22:33:17 +00001669 if (PrevClassTemplate)
1670 CheckRedeclarationModuleOwnership(NewTemplate, PrevClassTemplate);
1671
Douglas Gregordba32632009-02-10 19:49:53 +00001672 if (Invalid) {
1673 NewTemplate->setInvalidDecl();
1674 NewClass->setInvalidDecl();
1675 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001676
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001677 ActOnDocumentableDecl(NewTemplate);
1678
Richard Smithc4577662018-09-12 02:13:47 +00001679 if (SkipBody && SkipBody->ShouldSkip)
1680 return SkipBody->Previous;
1681
John McCall48871652010-08-21 09:40:31 +00001682 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001683}
1684
Richard Smith32918772017-02-14 00:25:28 +00001685namespace {
Erik Pilkington69770d32018-07-27 21:23:48 +00001686/// Tree transform to "extract" a transformed type from a class template's
1687/// constructor to a deduction guide.
1688class ExtractTypeForDeductionGuide
1689 : public TreeTransform<ExtractTypeForDeductionGuide> {
1690public:
1691 typedef TreeTransform<ExtractTypeForDeductionGuide> Base;
1692 ExtractTypeForDeductionGuide(Sema &SemaRef) : Base(SemaRef) {}
1693
1694 TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); }
1695
1696 QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) {
1697 return TransformType(
1698 TLB,
1699 TL.getTypedefNameDecl()->getTypeSourceInfo()->getTypeLoc());
1700 }
1701};
1702
Richard Smith32918772017-02-14 00:25:28 +00001703/// Transform to convert portions of a constructor declaration into the
1704/// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
1705struct ConvertConstructorToDeductionGuideTransform {
1706 ConvertConstructorToDeductionGuideTransform(Sema &S,
1707 ClassTemplateDecl *Template)
1708 : SemaRef(S), Template(Template) {}
1709
1710 Sema &SemaRef;
1711 ClassTemplateDecl *Template;
1712
1713 DeclContext *DC = Template->getDeclContext();
1714 CXXRecordDecl *Primary = Template->getTemplatedDecl();
1715 DeclarationName DeductionGuideName =
1716 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
1717
1718 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
1719
1720 // Index adjustment to apply to convert depth-1 template parameters into
1721 // depth-0 template parameters.
1722 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
1723
1724 /// Transform a constructor declaration into a deduction guide.
Richard Smithbc491202017-02-17 20:05:37 +00001725 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
1726 CXXConstructorDecl *CD) {
Richard Smith32918772017-02-14 00:25:28 +00001727 SmallVector<TemplateArgument, 16> SubstArgs;
1728
Richard Smithb4f96252017-02-21 06:30:38 +00001729 LocalInstantiationScope Scope(SemaRef);
1730
Richard Smith32918772017-02-14 00:25:28 +00001731 // C++ [over.match.class.deduct]p1:
1732 // -- For each constructor of the class template designated by the
1733 // template-name, a function template with the following properties:
1734
1735 // -- The template parameters are the template parameters of the class
1736 // template followed by the template parameters (including default
1737 // template arguments) of the constructor, if any.
1738 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
1739 if (FTD) {
1740 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
1741 SmallVector<NamedDecl *, 16> AllParams;
1742 AllParams.reserve(TemplateParams->size() + InnerParams->size());
1743 AllParams.insert(AllParams.begin(),
1744 TemplateParams->begin(), TemplateParams->end());
1745 SubstArgs.reserve(InnerParams->size());
1746
1747 // Later template parameters could refer to earlier ones, so build up
1748 // a list of substituted template arguments as we go.
1749 for (NamedDecl *Param : *InnerParams) {
1750 MultiLevelTemplateArgumentList Args;
1751 Args.addOuterTemplateArguments(SubstArgs);
Richard Smithb4f96252017-02-21 06:30:38 +00001752 Args.addOuterRetainedLevel();
Richard Smith32918772017-02-14 00:25:28 +00001753 NamedDecl *NewParam = transformTemplateParameter(Param, Args);
1754 if (!NewParam)
1755 return nullptr;
1756 AllParams.push_back(NewParam);
1757 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
1758 SemaRef.Context.getInjectedTemplateArg(NewParam)));
1759 }
1760 TemplateParams = TemplateParameterList::Create(
1761 SemaRef.Context, InnerParams->getTemplateLoc(),
1762 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
1763 /*FIXME: RequiresClause*/ nullptr);
1764 }
1765
1766 // If we built a new template-parameter-list, track that we need to
1767 // substitute references to the old parameters into references to the
1768 // new ones.
1769 MultiLevelTemplateArgumentList Args;
1770 if (FTD) {
1771 Args.addOuterTemplateArguments(SubstArgs);
Richard Smithb4f96252017-02-21 06:30:38 +00001772 Args.addOuterRetainedLevel();
Richard Smith32918772017-02-14 00:25:28 +00001773 }
1774
Richard Smithbc491202017-02-17 20:05:37 +00001775 FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
Richard Smith32918772017-02-14 00:25:28 +00001776 .getAsAdjusted<FunctionProtoTypeLoc>();
1777 assert(FPTL && "no prototype for constructor declaration");
1778
1779 // Transform the type of the function, adjusting the return type and
1780 // replacing references to the old parameters with references to the
1781 // new ones.
1782 TypeLocBuilder TLB;
1783 SmallVector<ParmVarDecl*, 8> Params;
1784 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args);
1785 if (NewType.isNull())
1786 return nullptr;
1787 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
1788
Richard Smithbc491202017-02-17 20:05:37 +00001789 return buildDeductionGuide(TemplateParams, CD->isExplicit(), NewTInfo,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001790 CD->getBeginLoc(), CD->getLocation(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001791 CD->getEndLoc());
Richard Smith32918772017-02-14 00:25:28 +00001792 }
1793
1794 /// Build a deduction guide with the specified parameter types.
1795 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
1796 SourceLocation Loc = Template->getLocation();
1797
1798 // Build the requested type.
1799 FunctionProtoType::ExtProtoInfo EPI;
1800 EPI.HasTrailingReturn = true;
1801 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
1802 DeductionGuideName, EPI);
1803 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
1804
1805 FunctionProtoTypeLoc FPTL =
1806 TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
1807
1808 // Build the parameters, needed during deduction / substitution.
1809 SmallVector<ParmVarDecl*, 4> Params;
1810 for (auto T : ParamTypes) {
1811 ParmVarDecl *NewParam = ParmVarDecl::Create(
1812 SemaRef.Context, DC, Loc, Loc, nullptr, T,
1813 SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
1814 NewParam->setScopeInfo(0, Params.size());
1815 FPTL.setParam(Params.size(), NewParam);
1816 Params.push_back(NewParam);
1817 }
1818
1819 return buildDeductionGuide(Template->getTemplateParameters(), false, TSI,
1820 Loc, Loc, Loc);
1821 }
1822
1823private:
1824 /// Transform a constructor template parameter into a deduction guide template
1825 /// parameter, rebuilding any internal references to earlier parameters and
1826 /// renumbering as we go.
1827 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
1828 MultiLevelTemplateArgumentList &Args) {
1829 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
1830 // TemplateTypeParmDecl's index cannot be changed after creation, so
1831 // substitute it directly.
1832 auto *NewTTP = TemplateTypeParmDecl::Create(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001833 SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(),
1834 /*Depth*/ 0, Depth1IndexAdjustment + TTP->getIndex(),
Richard Smith32918772017-02-14 00:25:28 +00001835 TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
1836 TTP->isParameterPack());
1837 if (TTP->hasDefaultArgument()) {
1838 TypeSourceInfo *InstantiatedDefaultArg =
1839 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
1840 TTP->getDefaultArgumentLoc(), TTP->getDeclName());
1841 if (InstantiatedDefaultArg)
1842 NewTTP->setDefaultArgument(InstantiatedDefaultArg);
1843 }
Richard Smithb4f96252017-02-21 06:30:38 +00001844 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
1845 NewTTP);
Richard Smith32918772017-02-14 00:25:28 +00001846 return NewTTP;
1847 }
1848
1849 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
1850 return transformTemplateParameterImpl(TTP, Args);
1851
1852 return transformTemplateParameterImpl(
1853 cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
1854 }
1855 template<typename TemplateParmDecl>
1856 TemplateParmDecl *
1857 transformTemplateParameterImpl(TemplateParmDecl *OldParam,
1858 MultiLevelTemplateArgumentList &Args) {
1859 // Ask the template instantiator to do the heavy lifting for us, then adjust
1860 // the index of the parameter once it's done.
1861 auto *NewParam =
1862 cast_or_null<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
1863 assert(NewParam->getDepth() == 0 && "unexpected template param depth");
1864 NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
1865 return NewParam;
1866 }
1867
1868 QualType transformFunctionProtoType(TypeLocBuilder &TLB,
1869 FunctionProtoTypeLoc TL,
1870 SmallVectorImpl<ParmVarDecl*> &Params,
1871 MultiLevelTemplateArgumentList &Args) {
1872 SmallVector<QualType, 4> ParamTypes;
1873 const FunctionProtoType *T = TL.getTypePtr();
1874
1875 // -- The types of the function parameters are those of the constructor.
1876 for (auto *OldParam : TL.getParams()) {
Richard Smithc27b3d72017-02-14 01:49:59 +00001877 ParmVarDecl *NewParam = transformFunctionTypeParam(OldParam, Args);
Richard Smith32918772017-02-14 00:25:28 +00001878 if (!NewParam)
1879 return QualType();
1880 ParamTypes.push_back(NewParam->getType());
1881 Params.push_back(NewParam);
1882 }
1883
1884 // -- The return type is the class template specialization designated by
1885 // the template-name and template arguments corresponding to the
1886 // template parameters obtained from the class template.
1887 //
1888 // We use the injected-class-name type of the primary template instead.
1889 // This has the convenient property that it is different from any type that
1890 // the user can write in a deduction-guide (because they cannot enter the
1891 // context of the template), so implicit deduction guides can never collide
1892 // with explicit ones.
1893 QualType ReturnType = DeducedType;
1894 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
1895
1896 // Resolving a wording defect, we also inherit the variadicness of the
1897 // constructor.
1898 FunctionProtoType::ExtProtoInfo EPI;
1899 EPI.Variadic = T->isVariadic();
1900 EPI.HasTrailingReturn = true;
1901
1902 QualType Result = SemaRef.BuildFunctionType(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001903 ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI);
Richard Smith32918772017-02-14 00:25:28 +00001904 if (Result.isNull())
1905 return QualType();
1906
1907 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
1908 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
1909 NewTL.setLParenLoc(TL.getLParenLoc());
1910 NewTL.setRParenLoc(TL.getRParenLoc());
1911 NewTL.setExceptionSpecRange(SourceRange());
1912 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
1913 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
1914 NewTL.setParam(I, Params[I]);
1915
1916 return Result;
1917 }
1918
1919 ParmVarDecl *
1920 transformFunctionTypeParam(ParmVarDecl *OldParam,
1921 MultiLevelTemplateArgumentList &Args) {
1922 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
Richard Smith479ba8e2017-04-20 01:15:31 +00001923 TypeSourceInfo *NewDI;
Erik Pilkington69770d32018-07-27 21:23:48 +00001924 if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
Richard Smith479ba8e2017-04-20 01:15:31 +00001925 // Expand out the one and only element in each inner pack.
1926 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
1927 NewDI =
1928 SemaRef.SubstType(PackTL.getPatternLoc(), Args,
1929 OldParam->getLocation(), OldParam->getDeclName());
1930 if (!NewDI) return nullptr;
1931 NewDI =
1932 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
1933 PackTL.getTypePtr()->getNumExpansions());
1934 } else
1935 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
1936 OldParam->getDeclName());
Richard Smith32918772017-02-14 00:25:28 +00001937 if (!NewDI)
1938 return nullptr;
1939
Erik Pilkington69770d32018-07-27 21:23:48 +00001940 // Extract the type. This (for instance) replaces references to typedef
1941 // members of the current instantiations with the definitions of those
1942 // typedefs, avoiding triggering instantiation of the deduced type during
1943 // deduction.
1944 NewDI = ExtractTypeForDeductionGuide(SemaRef).transform(NewDI);
Richard Smithc27b3d72017-02-14 01:49:59 +00001945
Richard Smith32918772017-02-14 00:25:28 +00001946 // Resolving a wording defect, we also inherit default arguments from the
1947 // constructor.
1948 ExprResult NewDefArg;
1949 if (OldParam->hasDefaultArg()) {
Erik Pilkington69770d32018-07-27 21:23:48 +00001950 NewDefArg = SemaRef.SubstExpr(OldParam->getDefaultArg(), Args);
Richard Smith32918772017-02-14 00:25:28 +00001951 if (NewDefArg.isInvalid())
1952 return nullptr;
1953 }
1954
1955 ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
1956 OldParam->getInnerLocStart(),
1957 OldParam->getLocation(),
1958 OldParam->getIdentifier(),
1959 NewDI->getType(),
1960 NewDI,
1961 OldParam->getStorageClass(),
1962 NewDefArg.get());
1963 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
1964 OldParam->getFunctionScopeIndex());
Erik Pilkington69770d32018-07-27 21:23:48 +00001965 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);
Richard Smith32918772017-02-14 00:25:28 +00001966 return NewParam;
1967 }
1968
1969 NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams,
1970 bool Explicit, TypeSourceInfo *TInfo,
1971 SourceLocation LocStart, SourceLocation Loc,
1972 SourceLocation LocEnd) {
Richard Smithbc491202017-02-17 20:05:37 +00001973 DeclarationNameInfo Name(DeductionGuideName, Loc);
Richard Smithefa919a2017-02-16 21:29:21 +00001974 ArrayRef<ParmVarDecl *> Params =
1975 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
1976
Richard Smith32918772017-02-14 00:25:28 +00001977 // Build the implicit deduction guide template.
Richard Smithbc491202017-02-17 20:05:37 +00001978 auto *Guide =
1979 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, Explicit,
1980 Name, TInfo->getType(), TInfo, LocEnd);
Richard Smith32918772017-02-14 00:25:28 +00001981 Guide->setImplicit();
Richard Smithefa919a2017-02-16 21:29:21 +00001982 Guide->setParams(Params);
1983
1984 for (auto *Param : Params)
1985 Param->setDeclContext(Guide);
Richard Smith32918772017-02-14 00:25:28 +00001986
1987 auto *GuideTemplate = FunctionTemplateDecl::Create(
1988 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
1989 GuideTemplate->setImplicit();
1990 Guide->setDescribedFunctionTemplate(GuideTemplate);
1991
1992 if (isa<CXXRecordDecl>(DC)) {
1993 Guide->setAccess(AS_public);
1994 GuideTemplate->setAccess(AS_public);
1995 }
1996
1997 DC->addDecl(GuideTemplate);
1998 return GuideTemplate;
1999 }
2000};
2001}
2002
2003void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
2004 SourceLocation Loc) {
2005 DeclContext *DC = Template->getDeclContext();
2006 if (DC->isDependentContext())
2007 return;
2008
2009 ConvertConstructorToDeductionGuideTransform Transform(
2010 *this, cast<ClassTemplateDecl>(Template));
2011 if (!isCompleteType(Loc, Transform.DeducedType))
2012 return;
2013
2014 // Check whether we've already declared deduction guides for this template.
2015 // FIXME: Consider storing a flag on the template to indicate this.
2016 auto Existing = DC->lookup(Transform.DeductionGuideName);
2017 for (auto *D : Existing)
2018 if (D->isImplicit())
2019 return;
2020
2021 // In case we were expanding a pack when we attempted to declare deduction
2022 // guides, turn off pack expansion for everything we're about to do.
2023 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2024 // Create a template instantiation record to track the "instantiation" of
2025 // constructors into deduction guides.
2026 // FIXME: Add a kind for this to give more meaningful diagnostics. But can
2027 // this substitution process actually fail?
2028 InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
Volodymyr Sapsai2f649f32018-05-14 22:49:44 +00002029 if (BuildingDeductionGuides.isInvalid())
2030 return;
Richard Smith32918772017-02-14 00:25:28 +00002031
2032 // Convert declared constructors into deduction guide templates.
2033 // FIXME: Skip constructors for which deduction must necessarily fail (those
2034 // for which some class template parameter without a default argument never
2035 // appears in a deduced context).
2036 bool AddedAny = false;
Richard Smith32918772017-02-14 00:25:28 +00002037 for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
2038 D = D->getUnderlyingDecl();
2039 if (D->isInvalidDecl() || D->isImplicit())
2040 continue;
2041 D = cast<NamedDecl>(D->getCanonicalDecl());
2042
2043 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
Richard Smithbc491202017-02-17 20:05:37 +00002044 auto *CD =
2045 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
Richard Smith32918772017-02-14 00:25:28 +00002046 // Class-scope explicit specializations (MS extension) do not result in
2047 // deduction guides.
Richard Smithbc491202017-02-17 20:05:37 +00002048 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
Richard Smith32918772017-02-14 00:25:28 +00002049 continue;
2050
Richard Smithbc491202017-02-17 20:05:37 +00002051 Transform.transformConstructor(FTD, CD);
Richard Smith32918772017-02-14 00:25:28 +00002052 AddedAny = true;
Richard Smith32918772017-02-14 00:25:28 +00002053 }
2054
Faisal Vali81b756e2017-10-22 14:45:08 +00002055 // C++17 [over.match.class.deduct]
2056 // -- If C is not defined or does not declare any constructors, an
2057 // additional function template derived as above from a hypothetical
2058 // constructor C().
Richard Smith32918772017-02-14 00:25:28 +00002059 if (!AddedAny)
2060 Transform.buildSimpleDeductionGuide(None);
2061
Faisal Vali81b756e2017-10-22 14:45:08 +00002062 // -- An additional function template derived as above from a hypothetical
2063 // constructor C(C), called the copy deduction candidate.
2064 cast<CXXDeductionGuideDecl>(
2065 cast<FunctionTemplateDecl>(
2066 Transform.buildSimpleDeductionGuide(Transform.DeducedType))
2067 ->getTemplatedDecl())
2068 ->setIsCopyDeductionCandidate();
Richard Smith32918772017-02-14 00:25:28 +00002069}
2070
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002071/// Diagnose the presence of a default template argument on a
Douglas Gregored5731f2009-11-25 17:50:39 +00002072/// template parameter, which is ill-formed in certain contexts.
2073///
2074/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002075static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00002076 Sema::TemplateParamListContext TPC,
2077 SourceLocation ParamLoc,
2078 SourceRange DefArgRange) {
2079 switch (TPC) {
2080 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00002081 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00002082 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00002083 return false;
2084
2085 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00002086 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002087 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00002088 // A default template-argument shall not be specified in a
2089 // function template declaration or a function template
2090 // definition [...]
Simon Pilgrim6905d222016-12-30 22:55:33 +00002091 // If a friend function template declaration specifies a default
Douglas Gregora99fb4c2011-02-04 04:20:44 +00002092 // template-argument, that declaration shall be a definition and shall be
2093 // the only declaration of the function template in the translation unit.
2094 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002095 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002096 diag::warn_cxx98_compat_template_parameter_default_in_function_template
2097 : diag::ext_template_parameter_default_in_function_template)
2098 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00002099 return false;
2100
2101 case Sema::TPC_ClassTemplateMember:
2102 // C++0x [temp.param]p9:
2103 // A default template-argument shall not be specified in the
2104 // template-parameter-lists of the definition of a member of a
2105 // class template that appears outside of the member's class.
2106 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2107 << DefArgRange;
2108 return true;
2109
David Majnemerba8f17a2013-06-25 22:08:55 +00002110 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00002111 case Sema::TPC_FriendFunctionTemplate:
2112 // C++ [temp.param]p9:
2113 // A default template-argument shall not be specified in a
2114 // friend template declaration.
2115 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2116 << DefArgRange;
2117 return true;
2118
2119 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2120 // for friend function templates if there is only a single
2121 // declaration (and it is a definition). Strange!
2122 }
2123
David Blaikie8a40f702012-01-17 06:56:22 +00002124 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00002125}
2126
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002127/// Check for unexpanded parameter packs within the template parameters
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002128/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00002129static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2130 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00002131 // A template template parameter which is a parameter pack is also a pack
2132 // expansion.
2133 if (TTP->isParameterPack())
2134 return false;
2135
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002136 TemplateParameterList *Params = TTP->getTemplateParameters();
2137 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2138 NamedDecl *P = Params->getParam(I);
2139 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00002140 if (!NTTP->isParameterPack() &&
2141 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002142 NTTP->getTypeSourceInfo(),
2143 Sema::UPPC_NonTypeTemplateParameterType))
2144 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002145
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002146 continue;
2147 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002148
2149 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002150 = dyn_cast<TemplateTemplateParmDecl>(P))
2151 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2152 return true;
2153 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002154
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002155 return false;
2156}
2157
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002158/// Checks the validity of a template parameter list, possibly
Douglas Gregordba32632009-02-10 19:49:53 +00002159/// considering the template parameter list from a previous
2160/// declaration.
2161///
2162/// If an "old" template parameter list is provided, it must be
2163/// equivalent (per TemplateParameterListsAreEqual) to the "new"
2164/// template parameter list.
2165///
2166/// \param NewParams Template parameter list for a new template
2167/// declaration. This template parameter list will be updated with any
2168/// default arguments that are carried through from the previous
2169/// template parameter list.
2170///
2171/// \param OldParams If provided, template parameter list from a
2172/// previous declaration of the same template. Default template
2173/// arguments will be merged from the old template parameter list to
2174/// the new template parameter list.
2175///
Douglas Gregored5731f2009-11-25 17:50:39 +00002176/// \param TPC Describes the context in which we are checking the given
2177/// template parameter list.
2178///
Richard Smithc4577662018-09-12 02:13:47 +00002179/// \param SkipBody If we might have already made a prior merged definition
2180/// of this template visible, the corresponding body-skipping information.
2181/// Default argument redefinition is not an error when skipping such a body,
2182/// because (under the ODR) we can assume the default arguments are the same
2183/// as the prior merged definition.
2184///
Douglas Gregordba32632009-02-10 19:49:53 +00002185/// \returns true if an error occurred, false otherwise.
2186bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00002187 TemplateParameterList *OldParams,
Richard Smithc4577662018-09-12 02:13:47 +00002188 TemplateParamListContext TPC,
2189 SkipBodyInfo *SkipBody) {
Douglas Gregordba32632009-02-10 19:49:53 +00002190 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00002191
Douglas Gregordba32632009-02-10 19:49:53 +00002192 // C++ [temp.param]p10:
2193 // The set of default template-arguments available for use with a
2194 // template declaration or definition is obtained by merging the
2195 // default arguments from the definition (if in scope) and all
2196 // declarations in scope in the same way default function
2197 // arguments are (8.3.6).
2198 bool SawDefaultArgument = false;
2199 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00002200
Mike Stumpc89c8e32009-02-11 23:03:27 +00002201 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00002202 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00002203 if (OldParams)
2204 OldParam = OldParams->begin();
2205
Douglas Gregor0693def2011-01-27 01:40:17 +00002206 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00002207 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2208 NewParamEnd = NewParams->end();
2209 NewParam != NewParamEnd; ++NewParam) {
2210 // Variables used to diagnose redundant default arguments
2211 bool RedundantDefaultArg = false;
2212 SourceLocation OldDefaultLoc;
2213 SourceLocation NewDefaultLoc;
2214
David Blaikie651c73c2011-10-19 05:19:50 +00002215 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00002216 bool MissingDefaultArg = false;
2217
David Blaikie651c73c2011-10-19 05:19:50 +00002218 // Variable used to diagnose non-final parameter packs
2219 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00002220
Douglas Gregordba32632009-02-10 19:49:53 +00002221 if (TemplateTypeParmDecl *NewTypeParm
2222 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00002223 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002224 if (NewTypeParm->hasDefaultArgument() &&
2225 DiagnoseDefaultTemplateArgument(*this, TPC,
2226 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002227 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002228 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00002229 NewTypeParm->removeDefaultArgument();
2230
2231 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00002232 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002233 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Anders Carlsson327865d2009-06-12 23:20:15 +00002234 if (NewTypeParm->isParameterPack()) {
2235 assert(!NewTypeParm->hasDefaultArgument() &&
2236 "Parameter packs can't have a default argument!");
2237 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002238 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
Richard Smithc4577662018-09-12 02:13:47 +00002239 NewTypeParm->hasDefaultArgument() &&
2240 (!SkipBody || !SkipBody->ShouldSkip)) {
Douglas Gregordba32632009-02-10 19:49:53 +00002241 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2242 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2243 SawDefaultArgument = true;
2244 RedundantDefaultArg = true;
2245 PreviousDefaultArgLoc = NewDefaultLoc;
2246 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2247 // Merge the default argument from the old declaration to the
2248 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002249 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00002250 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2251 } else if (NewTypeParm->hasDefaultArgument()) {
2252 SawDefaultArgument = true;
2253 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2254 } else if (SawDefaultArgument)
2255 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00002256 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00002257 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002258 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002259 if (!NewNonTypeParm->isParameterPack() &&
2260 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002261 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002262 UPPC_NonTypeTemplateParameterType)) {
2263 Invalid = true;
2264 continue;
2265 }
2266
Douglas Gregored5731f2009-11-25 17:50:39 +00002267 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002268 if (NewNonTypeParm->hasDefaultArgument() &&
2269 DiagnoseDefaultTemplateArgument(*this, TPC,
2270 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002271 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00002272 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00002273 }
2274
Mike Stump12b8ce12009-08-04 21:02:39 +00002275 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00002276 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002277 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00002278 if (NewNonTypeParm->isParameterPack()) {
2279 assert(!NewNonTypeParm->hasDefaultArgument() &&
2280 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00002281 if (!NewNonTypeParm->isPackExpansion())
2282 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002283 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
Richard Smithc4577662018-09-12 02:13:47 +00002284 NewNonTypeParm->hasDefaultArgument() &&
2285 (!SkipBody || !SkipBody->ShouldSkip)) {
Douglas Gregordba32632009-02-10 19:49:53 +00002286 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2287 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2288 SawDefaultArgument = true;
2289 RedundantDefaultArg = true;
2290 PreviousDefaultArgLoc = NewDefaultLoc;
2291 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2292 // Merge the default argument from the old declaration to the
2293 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002294 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00002295 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2296 } else if (NewNonTypeParm->hasDefaultArgument()) {
2297 SawDefaultArgument = true;
2298 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2299 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002300 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00002301 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00002302 TemplateTemplateParmDecl *NewTemplateParm
2303 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002304
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002305 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00002306 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002307 Invalid = true;
2308 continue;
2309 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002310
David Blaikie651c73c2011-10-19 05:19:50 +00002311 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002312 if (NewTemplateParm->hasDefaultArgument() &&
2313 DiagnoseDefaultTemplateArgument(*this, TPC,
2314 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002315 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00002316 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00002317
2318 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00002319 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002320 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00002321 if (NewTemplateParm->isParameterPack()) {
2322 assert(!NewTemplateParm->hasDefaultArgument() &&
2323 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00002324 if (!NewTemplateParm->isPackExpansion())
2325 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002326 } else if (OldTemplateParm &&
2327 hasVisibleDefaultArgument(OldTemplateParm) &&
Richard Smithc4577662018-09-12 02:13:47 +00002328 NewTemplateParm->hasDefaultArgument() &&
2329 (!SkipBody || !SkipBody->ShouldSkip)) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002330 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2331 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002332 SawDefaultArgument = true;
2333 RedundantDefaultArg = true;
2334 PreviousDefaultArgLoc = NewDefaultLoc;
2335 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2336 // Merge the default argument from the old declaration to the
2337 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002338 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002339 PreviousDefaultArgLoc
2340 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002341 } else if (NewTemplateParm->hasDefaultArgument()) {
2342 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002343 PreviousDefaultArgLoc
2344 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002345 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002346 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00002347 }
2348
Richard Smith1fde8ec2012-09-07 02:06:42 +00002349 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00002350 // If a template parameter of a primary class template or alias template
2351 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002352 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00002353 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2354 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00002355 Diag((*NewParam)->getLocation(),
2356 diag::err_template_param_pack_must_be_last_template_parameter);
2357 Invalid = true;
2358 }
2359
Douglas Gregordba32632009-02-10 19:49:53 +00002360 if (RedundantDefaultArg) {
2361 // C++ [temp.param]p12:
2362 // A template-parameter shall not be given default arguments
2363 // by two different declarations in the same scope.
2364 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2365 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2366 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00002367 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00002368 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002369 // If a template-parameter of a class template has a default
2370 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00002371 // have a default template-argument supplied or be a template parameter
2372 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00002373 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00002374 diag::err_template_param_default_arg_missing);
2375 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2376 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00002377 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00002378 }
2379
2380 // If we have an old template parameter list that we're merging
2381 // in, move on to the next parameter.
2382 if (OldParams)
2383 ++OldParam;
2384 }
2385
Douglas Gregor0693def2011-01-27 01:40:17 +00002386 // We were missing some default arguments at the end of the list, so remove
2387 // all of the default arguments.
2388 if (RemoveDefaultArguments) {
2389 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2390 NewParamEnd = NewParams->end();
2391 NewParam != NewParamEnd; ++NewParam) {
2392 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2393 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002394 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00002395 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2396 NTTP->removeDefaultArgument();
2397 else
2398 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2399 }
2400 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002401
Douglas Gregordba32632009-02-10 19:49:53 +00002402 return Invalid;
2403}
Douglas Gregord32e0282009-02-09 23:23:08 +00002404
John McCalla020a012010-10-20 05:44:58 +00002405namespace {
2406
2407/// A class which looks for a use of a certain level of template
2408/// parameter.
2409struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2410 typedef RecursiveASTVisitor<DependencyChecker> super;
2411
2412 unsigned Depth;
Richard Smith57aae072016-12-28 02:37:25 +00002413
2414 // Whether we're looking for a use of a template parameter that makes the
2415 // overall construct type-dependent / a dependent type. This is strictly
2416 // best-effort for now; we may fail to match at all for a dependent type
2417 // in some cases if this is set.
2418 bool IgnoreNonTypeDependent;
2419
John McCalla020a012010-10-20 05:44:58 +00002420 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00002421 SourceLocation MatchLoc;
2422
Richard Smith13894182017-04-13 21:37:24 +00002423 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2424 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2425 Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00002426
Richard Smith57aae072016-12-28 02:37:25 +00002427 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
Richard Smith13894182017-04-13 21:37:24 +00002428 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2429 NamedDecl *ND = Params->getParam(0);
2430 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2431 Depth = PD->getDepth();
2432 } else if (NonTypeTemplateParmDecl *PD =
2433 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2434 Depth = PD->getDepth();
2435 } else {
2436 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2437 }
2438 }
John McCalla020a012010-10-20 05:44:58 +00002439
Richard Smith6056d5e2014-02-09 00:54:43 +00002440 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
Richard Smith13894182017-04-13 21:37:24 +00002441 if (ParmDepth >= Depth) {
John McCalla020a012010-10-20 05:44:58 +00002442 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00002443 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00002444 return true;
2445 }
2446 return false;
2447 }
2448
Richard Smith57aae072016-12-28 02:37:25 +00002449 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2450 // Prune out non-type-dependent expressions if requested. This can
2451 // sometimes result in us failing to find a template parameter reference
2452 // (if a value-dependent expression creates a dependent type), but this
2453 // mode is best-effort only.
2454 if (auto *E = dyn_cast_or_null<Expr>(S))
2455 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2456 return true;
2457 return super::TraverseStmt(S, Q);
2458 }
2459
2460 bool TraverseTypeLoc(TypeLoc TL) {
2461 if (IgnoreNonTypeDependent && !TL.isNull() &&
2462 !TL.getType()->isDependentType())
2463 return true;
2464 return super::TraverseTypeLoc(TL);
2465 }
2466
Richard Smith6056d5e2014-02-09 00:54:43 +00002467 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2468 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2469 }
2470
John McCalla020a012010-10-20 05:44:58 +00002471 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
Richard Smith57aae072016-12-28 02:37:25 +00002472 // For a best-effort search, keep looking until we find a location.
2473 return IgnoreNonTypeDependent || !Matches(T->getDepth());
John McCalla020a012010-10-20 05:44:58 +00002474 }
2475
2476 bool TraverseTemplateName(TemplateName N) {
2477 if (TemplateTemplateParmDecl *PD =
2478 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00002479 if (Matches(PD->getDepth()))
2480 return false;
John McCalla020a012010-10-20 05:44:58 +00002481 return super::TraverseTemplateName(N);
2482 }
2483
2484 bool VisitDeclRefExpr(DeclRefExpr *E) {
2485 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00002486 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2487 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00002488 return false;
John McCalla020a012010-10-20 05:44:58 +00002489 return super::VisitDeclRefExpr(E);
2490 }
Richard Smith6056d5e2014-02-09 00:54:43 +00002491
2492 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2493 return TraverseType(T->getReplacementType());
2494 }
2495
2496 bool
2497 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2498 return TraverseTemplateArgument(T->getArgumentPack());
2499 }
2500
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00002501 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2502 return TraverseType(T->getInjectedSpecializationType());
2503 }
John McCalla020a012010-10-20 05:44:58 +00002504};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002505} // end anonymous namespace
John McCalla020a012010-10-20 05:44:58 +00002506
Douglas Gregor972fe532011-05-10 18:27:06 +00002507/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00002508/// list.
2509static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00002510DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
Richard Smith57aae072016-12-28 02:37:25 +00002511 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
Douglas Gregor972fe532011-05-10 18:27:06 +00002512 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00002513 return Checker.Match;
2514}
2515
Douglas Gregor972fe532011-05-10 18:27:06 +00002516// Find the source range corresponding to the named type in the given
2517// nested-name-specifier, if any.
2518static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2519 QualType T,
2520 const CXXScopeSpec &SS) {
2521 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2522 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2523 if (const Type *CurType = NNS->getAsType()) {
2524 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2525 return NNSLoc.getTypeLoc().getSourceRange();
2526 } else
2527 break;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002528
Douglas Gregor972fe532011-05-10 18:27:06 +00002529 NNSLoc = NNSLoc.getPrefix();
2530 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002531
Douglas Gregor972fe532011-05-10 18:27:06 +00002532 return SourceRange();
2533}
2534
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002535/// Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00002536/// specifier, returning the template parameter list that applies to the
2537/// name.
2538///
2539/// \param DeclStartLoc the start of the declaration that has a scope
2540/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00002541///
Douglas Gregor972fe532011-05-10 18:27:06 +00002542/// \param DeclLoc The location of the declaration itself.
2543///
Douglas Gregord8d297c2009-07-21 23:53:31 +00002544/// \param SS the scope specifier that will be matched to the given template
2545/// parameter lists. This scope specifier precedes a qualified name that is
2546/// being declared.
2547///
Richard Smith4b55a9c2014-04-17 03:29:33 +00002548/// \param TemplateId The template-id following the scope specifier, if there
2549/// is one. Used to check for a missing 'template<>'.
2550///
Douglas Gregord8d297c2009-07-21 23:53:31 +00002551/// \param ParamLists the template parameter lists, from the outermost to the
2552/// innermost template parameter lists.
2553///
John McCalle820e5e2010-04-13 20:37:33 +00002554/// \param IsFriend Whether to apply the slightly different rules for
2555/// matching template parameters to scope specifiers in friend
2556/// declarations.
2557///
Richard Smithf445f192017-02-09 21:04:43 +00002558/// \param IsMemberSpecialization will be set true if the scope specifier
2559/// denotes a fully-specialized type, and therefore this is a declaration of
2560/// a member specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002561///
Mike Stump11289f42009-09-09 15:08:12 +00002562/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00002563/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00002564/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00002565/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00002566/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00002567/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002568TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2569 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00002570 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002571 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
Richard Smithf445f192017-02-09 21:04:43 +00002572 bool &IsMemberSpecialization, bool &Invalid) {
2573 IsMemberSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00002574 Invalid = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002575
Douglas Gregor972fe532011-05-10 18:27:06 +00002576 // The sequence of nested types to which we will match up the template
2577 // parameter lists. We first build this list by starting with the type named
2578 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002579 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00002580 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00002581 if (SS.getScopeRep()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002582 if (CXXRecordDecl *Record
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00002583 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2584 T = Context.getTypeDeclType(Record);
2585 else
2586 T = QualType(SS.getScopeRep()->getAsType(), 0);
2587 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002588
Douglas Gregor972fe532011-05-10 18:27:06 +00002589 // If we found an explicit specialization that prevents us from needing
2590 // 'template<>' headers, this will be set to the location of that
2591 // explicit specialization.
2592 SourceLocation ExplicitSpecLoc;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002593
Douglas Gregor972fe532011-05-10 18:27:06 +00002594 while (!T.isNull()) {
2595 NestedTypes.push_back(T);
Simon Pilgrim6905d222016-12-30 22:55:33 +00002596
Douglas Gregor972fe532011-05-10 18:27:06 +00002597 // Retrieve the parent of a record type.
2598 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2599 // If this type is an explicit specialization, we're done.
2600 if (ClassTemplateSpecializationDecl *Spec
2601 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002602 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002603 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2604 ExplicitSpecLoc = Spec->getLocation();
2605 break;
Douglas Gregor65911492009-11-23 12:11:45 +00002606 }
Douglas Gregor972fe532011-05-10 18:27:06 +00002607 } else if (Record->getTemplateSpecializationKind()
2608 == TSK_ExplicitSpecialization) {
2609 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00002610 break;
2611 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002612
Douglas Gregor972fe532011-05-10 18:27:06 +00002613 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2614 T = Context.getTypeDeclType(Parent);
2615 else
2616 T = QualType();
2617 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002618 }
2619
Douglas Gregor972fe532011-05-10 18:27:06 +00002620 if (const TemplateSpecializationType *TST
2621 = T->getAs<TemplateSpecializationType>()) {
2622 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2623 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2624 T = Context.getTypeDeclType(Parent);
2625 else
2626 T = QualType();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002627 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002628 }
Douglas Gregor972fe532011-05-10 18:27:06 +00002629 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002630
Douglas Gregor972fe532011-05-10 18:27:06 +00002631 // Look one step prior in a dependent template specialization type.
2632 if (const DependentTemplateSpecializationType *DependentTST
2633 = T->getAs<DependentTemplateSpecializationType>()) {
2634 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2635 T = QualType(NNS->getAsType(), 0);
2636 else
2637 T = QualType();
2638 continue;
2639 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002640
Douglas Gregor972fe532011-05-10 18:27:06 +00002641 // Look one step prior in a dependent name type.
2642 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2643 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2644 T = QualType(NNS->getAsType(), 0);
2645 else
2646 T = QualType();
2647 continue;
2648 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002649
Douglas Gregor972fe532011-05-10 18:27:06 +00002650 // Retrieve the parent of an enumeration type.
2651 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2652 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2653 // check here.
2654 EnumDecl *Enum = EnumT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002655
Douglas Gregor972fe532011-05-10 18:27:06 +00002656 // Get to the parent type.
2657 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2658 T = Context.getTypeDeclType(Parent);
2659 else
Simon Pilgrim6905d222016-12-30 22:55:33 +00002660 T = QualType();
Douglas Gregor972fe532011-05-10 18:27:06 +00002661 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002662 }
Mike Stump11289f42009-09-09 15:08:12 +00002663
Douglas Gregor972fe532011-05-10 18:27:06 +00002664 T = QualType();
2665 }
2666 // Reverse the nested types list, since we want to traverse from the outermost
2667 // to the innermost while checking template-parameter-lists.
2668 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00002669
Douglas Gregor972fe532011-05-10 18:27:06 +00002670 // C++0x [temp.expl.spec]p17:
2671 // A member or a member template may be nested within many
2672 // enclosing class templates. In an explicit specialization for
2673 // such a member, the member declaration shall be preceded by a
2674 // template<> for each enclosing class template that is
2675 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002676 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00002677
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002678 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00002679 if (SawNonEmptyTemplateParameterList) {
2680 Diag(DeclLoc, diag::err_specialize_member_of_template)
2681 << !Recovery << Range;
2682 Invalid = true;
Richard Smithf445f192017-02-09 21:04:43 +00002683 IsMemberSpecialization = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00002684 return true;
2685 }
2686
2687 return false;
2688 };
2689
2690 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2691 // Check that we can have an explicit specialization here.
2692 if (CheckExplicitSpecialization(Range, true))
2693 return true;
2694
2695 // We don't have a template header, but we should.
2696 SourceLocation ExpectedTemplateLoc;
2697 if (!ParamLists.empty())
2698 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2699 else
2700 ExpectedTemplateLoc = DeclStartLoc;
2701
2702 Diag(DeclLoc, diag::err_template_spec_needs_header)
2703 << Range
2704 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2705 return false;
2706 };
2707
Douglas Gregor972fe532011-05-10 18:27:06 +00002708 unsigned ParamIdx = 0;
2709 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2710 ++TypeIdx) {
2711 T = NestedTypes[TypeIdx];
Simon Pilgrim6905d222016-12-30 22:55:33 +00002712
Douglas Gregor972fe532011-05-10 18:27:06 +00002713 // Whether we expect a 'template<>' header.
2714 bool NeedEmptyTemplateHeader = false;
2715
2716 // Whether we expect a template header with parameters.
2717 bool NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002718
Douglas Gregor972fe532011-05-10 18:27:06 +00002719 // For a dependent type, the set of template parameters that we
2720 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00002721 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002722
Douglas Gregor373af9b2011-05-11 23:26:17 +00002723 // C++0x [temp.expl.spec]p15:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002724 // A member or a member template may be nested within many enclosing
2725 // class templates. In an explicit specialization for such a member, the
2726 // member declaration shall be preceded by a template<> for each
Douglas Gregor373af9b2011-05-11 23:26:17 +00002727 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00002728 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2729 if (ClassTemplatePartialSpecializationDecl *Partial
2730 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2731 ExpectedTemplateParams = Partial->getTemplateParameters();
2732 NeedNonemptyTemplateHeader = true;
2733 } else if (Record->isDependentType()) {
2734 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00002735 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00002736 ->getTemplateParameters();
2737 NeedNonemptyTemplateHeader = true;
2738 }
2739 } else if (ClassTemplateSpecializationDecl *Spec
2740 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2741 // C++0x [temp.expl.spec]p4:
2742 // Members of an explicitly specialized class template are defined
Simon Pilgrim6905d222016-12-30 22:55:33 +00002743 // in the same manner as members of normal classes, and not using
2744 // the template<> syntax.
Douglas Gregor972fe532011-05-10 18:27:06 +00002745 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2746 NeedEmptyTemplateHeader = true;
2747 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00002748 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002749 } else if (Record->getTemplateSpecializationKind()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002750 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00002751 != TSK_ExplicitSpecialization &&
2752 TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002753 IsMemberSpecialization = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002754
Douglas Gregor373af9b2011-05-11 23:26:17 +00002755 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002756 }
2757 } else if (const TemplateSpecializationType *TST
2758 = T->getAs<TemplateSpecializationType>()) {
Nico Weber28900612015-01-30 02:35:21 +00002759 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002760 ExpectedTemplateParams = Template->getTemplateParameters();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002761 NeedNonemptyTemplateHeader = true;
Douglas Gregor972fe532011-05-10 18:27:06 +00002762 }
2763 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2764 // FIXME: We actually could/should check the template arguments here
2765 // against the corresponding template parameter list.
2766 NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002767 }
2768
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002769 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002770 // In an explicit specialization declaration for a member of a class
2771 // template or a member template that ap- pears in namespace scope, the
2772 // member template and some of its enclosing class templates may remain
2773 // unspecialized, except that the declaration shall not explicitly
2774 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002775 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002776 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002777 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002778 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2779 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002780 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002781 } else
2782 SawNonEmptyTemplateParameterList = true;
2783 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002784
Douglas Gregor972fe532011-05-10 18:27:06 +00002785 if (NeedEmptyTemplateHeader) {
2786 // If we're on the last of the types, and we need a 'template<>' header
Richard Smithf445f192017-02-09 21:04:43 +00002787 // here, then it's a member specialization.
Douglas Gregor972fe532011-05-10 18:27:06 +00002788 if (TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002789 IsMemberSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002790
2791 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002792 if (ParamLists[ParamIdx]->size() > 0) {
2793 // The header has template parameters when it shouldn't. Complain.
Simon Pilgrim6905d222016-12-30 22:55:33 +00002794 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregor972fe532011-05-10 18:27:06 +00002795 diag::err_template_param_list_matches_nontemplate)
2796 << T
2797 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2798 ParamLists[ParamIdx]->getRAngleLoc())
2799 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2800 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002801 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002802 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002803
Douglas Gregor972fe532011-05-10 18:27:06 +00002804 // Consume this template header.
2805 ++ParamIdx;
2806 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002807 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002808
2809 if (!IsFriend)
2810 if (DiagnoseMissingExplicitSpecialization(
2811 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00002812 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002813
Douglas Gregor972fe532011-05-10 18:27:06 +00002814 continue;
2815 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002816
Douglas Gregor972fe532011-05-10 18:27:06 +00002817 if (NeedNonemptyTemplateHeader) {
2818 // In friend declarations we can have template-ids which don't
2819 // depend on the corresponding template parameter lists. But
2820 // assume that empty parameter lists are supposed to match this
2821 // template-id.
2822 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002823 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002824 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00002825 ExpectedTemplateParams = nullptr;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002826 else
Douglas Gregor972fe532011-05-10 18:27:06 +00002827 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002828 }
Douglas Gregored5731f2009-11-25 17:50:39 +00002829
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002830 if (ParamIdx < ParamLists.size()) {
2831 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00002832 if (ExpectedTemplateParams &&
2833 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2834 ExpectedTemplateParams,
2835 true, TPL_TemplateMatch))
2836 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002837
Douglas Gregor972fe532011-05-10 18:27:06 +00002838 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00002839 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00002840 TPC_ClassTemplateMember))
2841 Invalid = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002842
Douglas Gregor972fe532011-05-10 18:27:06 +00002843 ++ParamIdx;
2844 continue;
2845 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002846
Douglas Gregor972fe532011-05-10 18:27:06 +00002847 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2848 << T
2849 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2850 Invalid = true;
2851 continue;
2852 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00002853 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00002854
Douglas Gregord8d297c2009-07-21 23:53:31 +00002855 // If there were at least as many template-ids as there were template
2856 // parameter lists, then there are no template parameter lists remaining for
2857 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00002858 if (ParamIdx >= ParamLists.size()) {
2859 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00002860 // We don't have a template header for the declaration itself, but we
2861 // should.
Richard Smith11a80dc2014-04-17 03:52:20 +00002862 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2863 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00002864
2865 // Fabricate an empty template parameter list for the invented header.
2866 return TemplateParameterList::Create(Context, SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +00002867 SourceLocation(), None,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00002868 SourceLocation(), nullptr);
Richard Smith4b55a9c2014-04-17 03:29:33 +00002869 }
2870
Craig Topperc3ec1492014-05-26 06:22:03 +00002871 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002872 }
Mike Stump11289f42009-09-09 15:08:12 +00002873
Douglas Gregord8d297c2009-07-21 23:53:31 +00002874 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002875 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002876 bool HasAnyExplicitSpecHeader = false;
2877 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002878 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002879 if (ParamLists[I]->size() == 0)
2880 HasAnyExplicitSpecHeader = true;
2881 else
2882 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002883 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002884
Douglas Gregor972fe532011-05-10 18:27:06 +00002885 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002886 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2887 : diag::err_template_spec_extra_headers)
2888 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2889 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00002890
2891 // If there was a specialization somewhere, such that 'template<>' is
2892 // not required, and there were any 'template<>' headers, note where the
2893 // specialization occurred.
2894 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
Simon Pilgrim6905d222016-12-30 22:55:33 +00002895 Diag(ExplicitSpecLoc,
Douglas Gregor972fe532011-05-10 18:27:06 +00002896 diag::note_explicit_template_spec_does_not_need_header)
2897 << NestedTypes.back();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002898
Douglas Gregor972fe532011-05-10 18:27:06 +00002899 // We have a template parameter list with no corresponding scope, which
2900 // means that the resulting template declaration can't be instantiated
2901 // properly (we'll end up with dependent nodes when we shouldn't).
2902 if (!AllExplicitSpecHeaders)
2903 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002904 }
Mike Stump11289f42009-09-09 15:08:12 +00002905
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002906 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002907 // In an explicit specialization declaration for a member of a class
2908 // template or a member template that ap- pears in namespace scope, the
2909 // member template and some of its enclosing class templates may remain
2910 // unspecialized, except that the declaration shall not explicitly
2911 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002912 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00002913 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002914 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2915 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002916 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002917
Douglas Gregord8d297c2009-07-21 23:53:31 +00002918 // Return the last template parameter list, which corresponds to the
2919 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002920 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00002921}
2922
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002923void Sema::NoteAllFoundTemplates(TemplateName Name) {
2924 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2925 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002926 << (isa<FunctionTemplateDecl>(Template)
2927 ? 0
2928 : isa<ClassTemplateDecl>(Template)
2929 ? 1
2930 : isa<VarTemplateDecl>(Template)
2931 ? 2
2932 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2933 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002934 return;
2935 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002936
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002937 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002938 for (OverloadedTemplateStorage::iterator I = OST->begin(),
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002939 IEnd = OST->end();
2940 I != IEnd; ++I)
2941 Diag((*I)->getLocation(), diag::note_template_declared_here)
2942 << 0 << (*I)->getDeclName();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002943
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002944 return;
2945 }
2946}
2947
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002948static QualType
2949checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2950 const SmallVectorImpl<TemplateArgument> &Converted,
2951 SourceLocation TemplateLoc,
2952 TemplateArgumentListInfo &TemplateArgs) {
2953 ASTContext &Context = SemaRef.getASTContext();
2954 switch (BTD->getBuiltinTemplateKind()) {
Eric Fiselier6ad68552016-07-01 01:24:09 +00002955 case BTK__make_integer_seq: {
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002956 // Specializations of __make_integer_seq<S, T, N> are treated like
2957 // S<T, 0, ..., N-1>.
2958
2959 // C++14 [inteseq.intseq]p1:
2960 // T shall be an integer type.
2961 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2962 SemaRef.Diag(TemplateArgs[1].getLocation(),
2963 diag::err_integer_sequence_integral_element_type);
2964 return QualType();
2965 }
2966
2967 // C++14 [inteseq.make]p1:
2968 // If N is negative the program is ill-formed.
2969 TemplateArgument NumArgsArg = Converted[2];
2970 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2971 if (NumArgs < 0) {
2972 SemaRef.Diag(TemplateArgs[2].getLocation(),
2973 diag::err_integer_sequence_negative_length);
2974 return QualType();
2975 }
2976
2977 QualType ArgTy = NumArgsArg.getIntegralType();
2978 TemplateArgumentListInfo SyntheticTemplateArgs;
2979 // The type argument gets reused as the first template argument in the
2980 // synthetic template argument list.
2981 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2982 // Expand N into 0 ... N-1.
2983 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2984 I < NumArgs; ++I) {
2985 TemplateArgument TA(Context, I, ArgTy);
Richard Smith7873de02016-08-11 22:25:46 +00002986 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
2987 TA, ArgTy, TemplateArgs[2].getLocation()));
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002988 }
2989 // The first template argument will be reused as the template decl that
2990 // our synthetic template arguments will be applied to.
2991 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2992 TemplateLoc, SyntheticTemplateArgs);
2993 }
Eric Fiselier6ad68552016-07-01 01:24:09 +00002994
2995 case BTK__type_pack_element:
2996 // Specializations of
2997 // __type_pack_element<Index, T_1, ..., T_N>
2998 // are treated like T_Index.
2999 assert(Converted.size() == 2 &&
3000 "__type_pack_element should be given an index and a parameter pack");
3001
3002 // If the Index is out of bounds, the program is ill-formed.
3003 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3004 llvm::APSInt Index = IndexArg.getAsIntegral();
3005 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3006 "type std::size_t, and hence be non-negative");
3007 if (Index >= Ts.pack_size()) {
3008 SemaRef.Diag(TemplateArgs[0].getLocation(),
3009 diag::err_type_pack_element_out_of_bounds);
3010 return QualType();
3011 }
3012
3013 // We simply return the type at index `Index`.
3014 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
3015 return Nth->getAsType();
3016 }
David Majnemerd9b1a4f2015-11-04 03:40:30 +00003017 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3018}
3019
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003020/// Determine whether this alias template is "enable_if_t".
3021static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3022 return AliasTemplate->getName().equals("enable_if_t");
3023}
3024
3025/// Collect all of the separable terms in the given condition, which
3026/// might be a conjunction.
3027///
3028/// FIXME: The right answer is to convert the logical expression into
3029/// disjunctive normal form, so we can find the first failed term
3030/// within each possible clause.
3031static void collectConjunctionTerms(Expr *Clause,
3032 SmallVectorImpl<Expr *> &Terms) {
3033 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3034 if (BinOp->getOpcode() == BO_LAnd) {
3035 collectConjunctionTerms(BinOp->getLHS(), Terms);
3036 collectConjunctionTerms(BinOp->getRHS(), Terms);
3037 }
3038
3039 return;
3040 }
3041
3042 Terms.push_back(Clause);
3043}
3044
Douglas Gregorbb33f572017-07-05 20:20:15 +00003045// The ranges-v3 library uses an odd pattern of a top-level "||" with
3046// a left-hand side that is value-dependent but never true. Identify
3047// the idiom and ignore that term.
3048static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3049 // Top-level '||'.
3050 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3051 if (!BinOp) return Cond;
3052
3053 if (BinOp->getOpcode() != BO_LOr) return Cond;
3054
3055 // With an inner '==' that has a literal on the right-hand side.
3056 Expr *LHS = BinOp->getLHS();
Douglas Gregorc0fe1f22017-07-05 21:12:37 +00003057 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
Douglas Gregorbb33f572017-07-05 20:20:15 +00003058 if (!InnerBinOp) return Cond;
3059
3060 if (InnerBinOp->getOpcode() != BO_EQ ||
3061 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3062 return Cond;
3063
3064 // If the inner binary operation came from a macro expansion named
3065 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3066 // of the '||', which is the real, user-provided condition.
Douglas Gregorc0fe1f22017-07-05 21:12:37 +00003067 SourceLocation Loc = InnerBinOp->getExprLoc();
Douglas Gregorbb33f572017-07-05 20:20:15 +00003068 if (!Loc.isMacroID()) return Cond;
3069
3070 StringRef MacroName = PP.getImmediateMacroName(Loc);
3071 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3072 return BinOp->getRHS();
3073
3074 return Cond;
3075}
3076
Clement Courbetf44c6f42018-12-11 08:39:11 +00003077namespace {
3078
3079// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3080// within failing boolean expression, such as substituting template parameters
3081// for actual types.
3082class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3083public:
3084 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3085 : Policy(P) {}
3086
3087 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3088 const auto *DR = dyn_cast<DeclRefExpr>(E);
3089 if (DR && DR->getQualifier()) {
3090 // If this is a qualified name, expand the template arguments in nested
3091 // qualifiers.
3092 DR->getQualifier()->print(OS, Policy, true);
3093 // Then print the decl itself.
3094 const ValueDecl *VD = DR->getDecl();
3095 OS << VD->getName();
3096 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3097 // This is a template variable, print the expanded template arguments.
3098 printTemplateArgumentList(OS, IV->getTemplateArgs().asArray(), Policy);
3099 }
3100 return true;
Clement Courbet9d432e02018-12-04 07:59:57 +00003101 }
Clement Courbetf44c6f42018-12-11 08:39:11 +00003102 return false;
Clement Courbet9d432e02018-12-04 07:59:57 +00003103 }
Clement Courbetf44c6f42018-12-11 08:39:11 +00003104
3105private:
3106 const PrintingPolicy Policy;
3107};
3108
3109} // end anonymous namespace
Clement Courbet9d432e02018-12-04 07:59:57 +00003110
Douglas Gregor672281a2017-09-14 23:38:42 +00003111std::pair<Expr *, std::string>
Clement Courbetf44c6f42018-12-11 08:39:11 +00003112Sema::findFailedBooleanCondition(Expr *Cond) {
Douglas Gregor672281a2017-09-14 23:38:42 +00003113 Cond = lookThroughRangesV3Condition(PP, Cond);
Douglas Gregorbb33f572017-07-05 20:20:15 +00003114
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003115 // Separate out all of the terms in a conjunction.
3116 SmallVector<Expr *, 4> Terms;
3117 collectConjunctionTerms(Cond, Terms);
3118
3119 // Determine which term failed.
3120 Expr *FailedCond = nullptr;
3121 for (Expr *Term : Terms) {
Douglas Gregor672281a2017-09-14 23:38:42 +00003122 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3123
Clement Courbetd8720412018-12-10 08:53:17 +00003124 // Literals are uninteresting.
3125 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3126 isa<IntegerLiteral>(TermAsWritten))
3127 continue;
3128
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003129 // The initialization of the parameter from the argument is
3130 // a constant-evaluated context.
3131 EnterExpressionEvaluationContext ConstantEvaluated(
Douglas Gregor672281a2017-09-14 23:38:42 +00003132 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003133
3134 bool Succeeded;
Douglas Gregor672281a2017-09-14 23:38:42 +00003135 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003136 !Succeeded) {
Douglas Gregor672281a2017-09-14 23:38:42 +00003137 FailedCond = TermAsWritten;
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003138 break;
3139 }
3140 }
Clement Courbetf44c6f42018-12-11 08:39:11 +00003141 if (!FailedCond)
Clement Courbetd8720412018-12-10 08:53:17 +00003142 FailedCond = Cond->IgnoreParenImpCasts();
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003143
3144 std::string Description;
3145 {
3146 llvm::raw_string_ostream Out(Description);
Clement Courbetfb2c74d2018-12-20 09:05:15 +00003147 PrintingPolicy Policy = getPrintingPolicy();
3148 Policy.PrintCanonicalTypes = true;
3149 FailedBooleanConditionPrinterHelper Helper(Policy);
3150 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003151 }
3152 return { FailedCond, Description };
3153}
3154
Douglas Gregordc572a32009-03-30 22:58:21 +00003155QualType Sema::CheckTemplateIdType(TemplateName Name,
3156 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003157 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00003158 DependentTemplateName *DTN
3159 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00003160 if (DTN && DTN->isIdentifier())
3161 // When building a template-id where the template-name is dependent,
3162 // assume the template is a type template. Either our assumption is
3163 // correct, or the code is ill-formed and will be diagnosed when the
3164 // dependent name is substituted.
3165 return Context.getDependentTemplateSpecializationType(ETK_None,
3166 DTN->getQualifier(),
3167 DTN->getIdentifier(),
3168 TemplateArgs);
3169
Douglas Gregordc572a32009-03-30 22:58:21 +00003170 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00003171 if (!Template || isa<FunctionTemplateDecl>(Template) ||
Faisal Valia534f072018-04-26 00:42:40 +00003172 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00003173 // We might have a substituted template template parameter pack. If so,
3174 // build a template specialization type for it.
3175 if (Name.getAsSubstTemplateTemplateParmPack())
3176 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003177
Douglas Gregor8b6070b2011-03-04 21:37:14 +00003178 Diag(TemplateLoc, diag::err_template_id_not_a_type)
3179 << Name;
3180 NoteAllFoundTemplates(Name);
3181 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00003182 }
Douglas Gregordc572a32009-03-30 22:58:21 +00003183
Douglas Gregorc40290e2009-03-09 23:48:35 +00003184 // Check that the template argument list is well-formed for this
3185 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003186 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00003187 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00003188 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00003189 return QualType();
3190
Douglas Gregorc40290e2009-03-09 23:48:35 +00003191 QualType CanonType;
3192
Douglas Gregor678d76c2011-07-01 01:22:09 +00003193 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00003194 if (TypeAliasTemplateDecl *AliasTemplate =
3195 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00003196 // Find the canonical type for this type alias template specialization.
3197 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3198 if (Pattern->isInvalidDecl())
3199 return QualType();
3200
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003201 TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack,
3202 Converted);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003203
3204 // Only substitute for the innermost template argument list.
3205 MultiLevelTemplateArgumentList TemplateArgLists;
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003206 TemplateArgLists.addOuterTemplateArguments(&StackTemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00003207 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
3208 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00003209 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003210
Richard Smith802c4b72012-08-23 06:16:52 +00003211 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003212 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003213 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003214 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00003215
Richard Smith3f1b5d02011-05-05 21:57:07 +00003216 CanonType = SubstType(Pattern->getUnderlyingType(),
3217 TemplateArgLists, AliasTemplate->getLocation(),
3218 AliasTemplate->getDeclName());
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003219 if (CanonType.isNull()) {
3220 // If this was enable_if and we failed to find the nested type
3221 // within enable_if in a SFINAE context, dig out the specific
3222 // enable_if condition that failed and present that instead.
3223 if (isEnableIfAliasTemplate(AliasTemplate)) {
3224 if (auto DeductionInfo = isSFINAEContext()) {
3225 if (*DeductionInfo &&
3226 (*DeductionInfo)->hasSFINAEDiagnostic() &&
3227 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3228 diag::err_typename_nested_not_found_enable_if &&
3229 TemplateArgs[0].getArgument().getKind()
3230 == TemplateArgument::Expression) {
3231 Expr *FailedCond;
3232 std::string FailedDescription;
3233 std::tie(FailedCond, FailedDescription) =
Clement Courbetf44c6f42018-12-11 08:39:11 +00003234 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003235
3236 // Remove the old SFINAE diagnostic.
3237 PartialDiagnosticAt OldDiag =
3238 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3239 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3240
3241 // Add a new SFINAE diagnostic specifying which condition
3242 // failed.
3243 (*DeductionInfo)->addSFINAEDiagnostic(
3244 OldDiag.first,
3245 PDiag(diag::err_typename_nested_not_found_requirement)
3246 << FailedDescription
3247 << FailedCond->getSourceRange());
3248 }
3249 }
3250 }
3251
Richard Smith3f1b5d02011-05-05 21:57:07 +00003252 return QualType();
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003253 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00003254 } else if (Name.isDependent() ||
3255 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00003256 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00003257 // This class template specialization is a dependent
3258 // type. Therefore, its canonical type is another class template
3259 // specialization type that contains all of the converted
3260 // arguments in canonical form. This ensures that, e.g., A<T> and
3261 // A<T, T> have identical types when A is declared as:
3262 //
3263 // template<typename T, typename U = T> struct A;
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00003264 CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
John McCall2408e322010-04-27 00:57:59 +00003265
3266 // This might work out to be a current instantiation, in which
3267 // case the canonical type needs to be the InjectedClassNameType.
3268 //
3269 // TODO: in theory this could be a simple hashtable lookup; most
3270 // changes to CurContext don't change the set of current
3271 // instantiations.
3272 if (isa<ClassTemplateDecl>(Template)) {
3273 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3274 // If we get out to a namespace, we're done.
3275 if (Ctx->isFileContext()) break;
3276
3277 // If this isn't a record, keep looking.
3278 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3279 if (!Record) continue;
3280
3281 // Look for one of the two cases with InjectedClassNameTypes
3282 // and check whether it's the same template.
3283 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3284 !Record->getDescribedClassTemplate())
3285 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003286
John McCall2408e322010-04-27 00:57:59 +00003287 // Fetch the injected class name type and check whether its
3288 // injected type is equal to the type we just built.
3289 QualType ICNT = Context.getTypeDeclType(Record);
3290 QualType Injected = cast<InjectedClassNameType>(ICNT)
3291 ->getInjectedSpecializationType();
3292
3293 if (CanonType != Injected->getCanonicalTypeInternal())
3294 continue;
3295
3296 // If so, the canonical type of this TST is the injected
3297 // class name type of the record we just found.
3298 assert(ICNT.isCanonical());
3299 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00003300 break;
3301 }
3302 }
Mike Stump11289f42009-09-09 15:08:12 +00003303 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00003304 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00003305 // Find the class template specialization declaration that
3306 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00003307 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00003308 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00003309 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003310 if (!Decl) {
3311 // This is the first time we have referenced this class template
3312 // specialization. Create the canonical declaration and add it to
3313 // the set of specializations.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003314 Decl = ClassTemplateSpecializationDecl::Create(
3315 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3316 ClassTemplate->getDeclContext(),
3317 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3318 ClassTemplate->getLocation(), ClassTemplate, Converted, nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003319 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00003320 if (ClassTemplate->isOutOfLine())
3321 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00003322 }
3323
Erich Keanea32910d2017-03-23 18:51:54 +00003324 if (Decl->getSpecializationKind() == TSK_Undeclared) {
3325 MultiLevelTemplateArgumentList TemplateArgLists;
3326 TemplateArgLists.addOuterTemplateArguments(Converted);
3327 InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(),
3328 Decl);
3329 }
3330
Chandler Carruth2acfb222013-09-27 22:14:40 +00003331 // Diagnose uses of this specialization.
3332 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3333
Douglas Gregorc40290e2009-03-09 23:48:35 +00003334 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00003335 assert(isa<RecordType>(CanonType) &&
3336 "type of non-dependent specialization is not a RecordType");
David Majnemerd9b1a4f2015-11-04 03:40:30 +00003337 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3338 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
3339 TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003340 }
Mike Stump11289f42009-09-09 15:08:12 +00003341
Douglas Gregorc40290e2009-03-09 23:48:35 +00003342 // Build the fully-sugared type for this class template
3343 // specialization, which refers back to the class template
3344 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00003345 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003346}
3347
John McCallfaf5fb42010-08-26 23:41:50 +00003348TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003349Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Richard Smith74f02342017-01-19 21:00:13 +00003350 TemplateTy TemplateD, IdentifierInfo *TemplateII,
3351 SourceLocation TemplateIILoc,
Mike Stump11289f42009-09-09 15:08:12 +00003352 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00003353 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnara4244b432012-01-27 08:46:19 +00003354 SourceLocation RAngleLoc,
Richard Smith62559bd2017-02-01 21:36:38 +00003355 bool IsCtorOrDtorName, bool IsClassName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00003356 if (SS.isInvalid())
3357 return true;
3358
Richard Smith62559bd2017-02-01 21:36:38 +00003359 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3360 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3361
3362 // C++ [temp.res]p3:
3363 // A qualified-id that refers to a type and in which the
3364 // nested-name-specifier depends on a template-parameter (14.6.2)
3365 // shall be prefixed by the keyword typename to indicate that the
3366 // qualified-id denotes a type, forming an
3367 // elaborated-type-specifier (7.1.5.3).
3368 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
Richard Smith3411fbf2017-02-01 21:41:18 +00003369 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
Richard Smith62559bd2017-02-01 21:36:38 +00003370 << SS.getScopeRep() << TemplateII->getName();
3371 // Recover as if 'typename' were specified.
3372 // FIXME: This is not quite correct recovery as we don't transform SS
3373 // into the corresponding dependent form (and we don't diagnose missing
3374 // 'template' keywords within SS as a result).
3375 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3376 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3377 TemplateArgsIn, RAngleLoc);
3378 }
3379
3380 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3381 // it's not actually allowed to be used as a type in most cases. Because
3382 // we annotate it before we know whether it's valid, we have to check for
3383 // this case here.
3384 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
Richard Smith74f02342017-01-19 21:00:13 +00003385 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3386 Diag(TemplateIILoc,
3387 TemplateKWLoc.isInvalid()
3388 ? diag::err_out_of_line_qualified_id_type_names_constructor
3389 : diag::ext_out_of_line_qualified_id_type_names_constructor)
3390 << TemplateII << 0 /*injected-class-name used as template name*/
3391 << 1 /*if any keyword was present, it was 'template'*/;
3392 }
3393 }
3394
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003395 TemplateName Template = TemplateD.get();
Douglas Gregor8bf42052009-02-09 18:46:07 +00003396
Douglas Gregorc40290e2009-03-09 23:48:35 +00003397 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003398 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003399 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00003400
Douglas Gregor5a064722011-02-28 17:23:35 +00003401 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00003402 QualType T
3403 = Context.getDependentTemplateSpecializationType(ETK_None,
3404 DTN->getQualifier(),
3405 DTN->getIdentifier(),
3406 TemplateArgs);
3407 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00003408 TypeLocBuilder TLB;
3409 DependentTemplateSpecializationTypeLoc SpecTL
3410 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003411 SpecTL.setElaboratedKeywordLoc(SourceLocation());
3412 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00003413 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00003414 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00003415 SpecTL.setLAngleLoc(LAngleLoc);
3416 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00003417 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3418 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3419 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3420 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003421
Richard Smith74f02342017-01-19 21:00:13 +00003422 QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003423 if (Result.isNull())
3424 return true;
3425
Douglas Gregore7c20652011-03-02 00:47:37 +00003426 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003427 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00003428 TemplateSpecializationTypeLoc SpecTL
3429 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003430 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00003431 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003432 SpecTL.setLAngleLoc(LAngleLoc);
3433 SpecTL.setRAngleLoc(RAngleLoc);
3434 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3435 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00003436
Abramo Bagnara4244b432012-01-27 08:46:19 +00003437 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
3438 // constructor or destructor name (in such a case, the scope specifier
3439 // will be attached to the enclosing Decl or Expr node).
3440 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00003441 // Create an elaborated-type-specifier containing the nested-name-specifier.
3442 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
3443 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00003444 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00003445 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3446 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003447
Douglas Gregore7c20652011-03-02 00:47:37 +00003448 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00003449}
John McCall06f6fe8d2009-09-04 01:14:41 +00003450
Douglas Gregore7c20652011-03-02 00:47:37 +00003451TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00003452 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00003453 SourceLocation TagLoc,
3454 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003455 SourceLocation TemplateKWLoc,
3456 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00003457 SourceLocation TemplateLoc,
3458 SourceLocation LAngleLoc,
3459 ASTTemplateArgsPtr TemplateArgsIn,
3460 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003461 TemplateName Template = TemplateD.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00003462
Douglas Gregore7c20652011-03-02 00:47:37 +00003463 // Translate the parser's template argument list in our AST format.
3464 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3465 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003466
Douglas Gregore7c20652011-03-02 00:47:37 +00003467 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00003468 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00003469 ElaboratedTypeKeyword Keyword
3470 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00003471
Douglas Gregore7c20652011-03-02 00:47:37 +00003472 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3473 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
Simon Pilgrim6905d222016-12-30 22:55:33 +00003474 DTN->getQualifier(),
3475 DTN->getIdentifier(),
Douglas Gregore7c20652011-03-02 00:47:37 +00003476 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003477
3478 // Build type-source information.
Douglas Gregore7c20652011-03-02 00:47:37 +00003479 TypeLocBuilder TLB;
3480 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003481 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3482 SpecTL.setElaboratedKeywordLoc(TagLoc);
3483 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00003484 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003485 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003486 SpecTL.setLAngleLoc(LAngleLoc);
3487 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003488 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3489 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3490 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3491 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00003492
3493 if (TypeAliasTemplateDecl *TAT =
3494 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3495 // C++0x [dcl.type.elab]p2:
3496 // If the identifier resolves to a typedef-name or the simple-template-id
3497 // resolves to an alias template specialization, the
3498 // elaborated-type-specifier is ill-formed.
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00003499 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3500 << TAT << NTK_TypeAliasTemplate << TagKind;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003501 Diag(TAT->getLocation(), diag::note_declared_at);
3502 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003503
Douglas Gregore7c20652011-03-02 00:47:37 +00003504 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3505 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00003506 return TypeResult(true);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003507
Douglas Gregore7c20652011-03-02 00:47:37 +00003508 // Check the tag kind
3509 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00003510 RecordDecl *D = RT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00003511
John McCalld8fe9af2009-09-08 17:47:29 +00003512 IdentifierInfo *Id = D->getIdentifier();
3513 assert(Id && "templated class must have an identifier");
Simon Pilgrim6905d222016-12-30 22:55:33 +00003514
Richard Trieucaa33d32011-06-10 03:11:26 +00003515 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00003516 TagLoc, Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00003517 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00003518 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00003519 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00003520 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00003521 }
3522 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003523
Douglas Gregore7c20652011-03-02 00:47:37 +00003524 // Provide source-location information for the template specialization.
3525 TypeLocBuilder TLB;
3526 TemplateSpecializationTypeLoc SpecTL
3527 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003528 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003529 SpecTL.setTemplateNameLoc(TemplateLoc);
3530 SpecTL.setLAngleLoc(LAngleLoc);
3531 SpecTL.setRAngleLoc(RAngleLoc);
3532 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3533 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00003534
Douglas Gregore7c20652011-03-02 00:47:37 +00003535 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003536 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00003537 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3538 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00003539 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003540 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3541 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003542}
3543
Larisse Voufo39a1e502013-08-06 01:03:05 +00003544static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3545 NamedDecl *PrevDecl,
3546 SourceLocation Loc,
3547 bool IsPartialSpecialization);
3548
3549static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003550
Richard Smith300e0c32013-09-24 04:49:23 +00003551static bool isTemplateArgumentTemplateParameter(
3552 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3553 switch (Arg.getKind()) {
3554 case TemplateArgument::Null:
3555 case TemplateArgument::NullPtr:
3556 case TemplateArgument::Integral:
3557 case TemplateArgument::Declaration:
3558 case TemplateArgument::Pack:
3559 case TemplateArgument::TemplateExpansion:
3560 return false;
3561
3562 case TemplateArgument::Type: {
3563 QualType Type = Arg.getAsType();
3564 const TemplateTypeParmType *TPT =
3565 Arg.getAsType()->getAs<TemplateTypeParmType>();
3566 return TPT && !Type.hasQualifiers() &&
3567 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3568 }
3569
3570 case TemplateArgument::Expression: {
3571 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3572 if (!DRE || !DRE->getDecl())
3573 return false;
3574 const NonTypeTemplateParmDecl *NTTP =
3575 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3576 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3577 }
3578
3579 case TemplateArgument::Template:
3580 const TemplateTemplateParmDecl *TTP =
3581 dyn_cast_or_null<TemplateTemplateParmDecl>(
3582 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
3583 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3584 }
3585 llvm_unreachable("unexpected kind of template argument");
3586}
3587
3588static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
3589 ArrayRef<TemplateArgument> Args) {
3590 if (Params->size() != Args.size())
3591 return false;
3592
3593 unsigned Depth = Params->getDepth();
3594
3595 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3596 TemplateArgument Arg = Args[I];
3597
3598 // If the parameter is a pack expansion, the argument must be a pack
3599 // whose only element is a pack expansion.
3600 if (Params->getParam(I)->isParameterPack()) {
3601 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3602 !Arg.pack_begin()->isPackExpansion())
3603 return false;
3604 Arg = Arg.pack_begin()->getPackExpansionPattern();
3605 }
3606
3607 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3608 return false;
3609 }
3610
3611 return true;
3612}
3613
Richard Smith4b55a9c2014-04-17 03:29:33 +00003614/// Convert the parser's template argument list representation into our form.
3615static TemplateArgumentListInfo
3616makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
3617 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
3618 TemplateId.RAngleLoc);
3619 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
3620 TemplateId.NumArgs);
3621 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
3622 return TemplateArgs;
3623}
3624
Richard Smith0e617ec2016-12-27 07:56:27 +00003625template<typename PartialSpecDecl>
3626static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3627 if (Partial->getDeclContext()->isDependentContext())
3628 return;
3629
3630 // FIXME: Get the TDK from deduction in order to provide better diagnostics
3631 // for non-substitution-failure issues?
3632 TemplateDeductionInfo Info(Partial->getLocation());
3633 if (S.isMoreSpecializedThanPrimary(Partial, Info))
3634 return;
3635
3636 auto *Template = Partial->getSpecializedTemplate();
3637 S.Diag(Partial->getLocation(),
Richard Smithfa4a09d2016-12-27 20:03:09 +00003638 diag::ext_partial_spec_not_more_specialized_than_primary)
3639 << isa<VarTemplateDecl>(Template);
Richard Smith0e617ec2016-12-27 07:56:27 +00003640
3641 if (Info.hasSFINAEDiagnostic()) {
3642 PartialDiagnosticAt Diag = {SourceLocation(),
3643 PartialDiagnostic::NullDiagnostic()};
3644 Info.takeSFINAEDiagnostic(Diag);
3645 SmallString<128> SFINAEArgString;
3646 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3647 S.Diag(Diag.first,
3648 diag::note_partial_spec_not_more_specialized_than_primary)
3649 << SFINAEArgString;
3650 }
3651
3652 S.Diag(Template->getLocation(), diag::note_template_decl_here);
3653}
3654
Richard Smith4e05eaa2017-02-16 00:36:47 +00003655static void
3656noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
3657 const llvm::SmallBitVector &DeducibleParams) {
3658 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3659 if (!DeducibleParams[I]) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00003660 NamedDecl *Param = TemplateParams->getParam(I);
Richard Smith4e05eaa2017-02-16 00:36:47 +00003661 if (Param->getDeclName())
3662 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3663 << Param->getDeclName();
3664 else
3665 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3666 << "(anonymous)";
3667 }
3668 }
3669}
3670
3671
Richard Smith57aae072016-12-28 02:37:25 +00003672template<typename PartialSpecDecl>
3673static void checkTemplatePartialSpecialization(Sema &S,
3674 PartialSpecDecl *Partial) {
3675 // C++1z [temp.class.spec]p8: (DR1495)
3676 // - The specialization shall be more specialized than the primary
3677 // template (14.5.5.2).
3678 checkMoreSpecializedThanPrimary(S, Partial);
3679
3680 // C++ [temp.class.spec]p8: (DR1315)
3681 // - Each template-parameter shall appear at least once in the
3682 // template-id outside a non-deduced context.
3683 // C++1z [temp.class.spec.match]p3 (P0127R2)
3684 // If the template arguments of a partial specialization cannot be
3685 // deduced because of the structure of its template-parameter-list
3686 // and the template-id, the program is ill-formed.
3687 auto *TemplateParams = Partial->getTemplateParameters();
3688 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3689 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3690 TemplateParams->getDepth(), DeducibleParams);
3691
3692 if (!DeducibleParams.all()) {
3693 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3694 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3695 << isa<VarTemplatePartialSpecializationDecl>(Partial)
3696 << (NumNonDeducible > 1)
3697 << SourceRange(Partial->getLocation(),
3698 Partial->getTemplateArgsAsWritten()->RAngleLoc);
Richard Smith4e05eaa2017-02-16 00:36:47 +00003699 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
Richard Smith57aae072016-12-28 02:37:25 +00003700 }
3701}
3702
3703void Sema::CheckTemplatePartialSpecialization(
3704 ClassTemplatePartialSpecializationDecl *Partial) {
3705 checkTemplatePartialSpecialization(*this, Partial);
3706}
3707
3708void Sema::CheckTemplatePartialSpecialization(
3709 VarTemplatePartialSpecializationDecl *Partial) {
3710 checkTemplatePartialSpecialization(*this, Partial);
3711}
3712
Richard Smith4e05eaa2017-02-16 00:36:47 +00003713void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
3714 // C++1z [temp.param]p11:
3715 // A template parameter of a deduction guide template that does not have a
3716 // default-argument shall be deducible from the parameter-type-list of the
3717 // deduction guide template.
3718 auto *TemplateParams = TD->getTemplateParameters();
3719 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3720 MarkDeducedTemplateParameters(TD, DeducibleParams);
3721 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3722 // A parameter pack is deducible (to an empty pack).
3723 auto *Param = TemplateParams->getParam(I);
3724 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3725 DeducibleParams[I] = true;
3726 }
3727
3728 if (!DeducibleParams.all()) {
3729 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3730 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3731 << (NumNonDeducible > 1);
3732 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3733 }
3734}
3735
Larisse Voufo39a1e502013-08-06 01:03:05 +00003736DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00003737 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00003738 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00003739 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003740 // D must be variable template id.
Faisal Vali2ab8c152017-12-30 04:15:27 +00003741 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00003742 "Variable template specialization is declared with a template it.");
3743
3744 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00003745 TemplateArgumentListInfo TemplateArgs =
3746 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003747 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3748 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3749 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00003750
Richard Smithbeef3452014-01-16 23:39:20 +00003751 TemplateName Name = TemplateId->Template.get();
3752
3753 // The template-id must name a variable template.
3754 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00003755 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3756 if (!VarTemplate) {
3757 NamedDecl *FnTemplate;
3758 if (auto *OTS = Name.getAsOverloadedTemplate())
3759 FnTemplate = *OTS->begin();
3760 else
3761 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3762 if (FnTemplate)
3763 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3764 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00003765 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3766 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00003767 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003768
3769 // Check for unexpanded parameter packs in any of the template arguments.
3770 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3771 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3772 UPPC_PartialSpecialization))
3773 return true;
3774
3775 // Check that the template argument list is well-formed for this
3776 // template.
3777 SmallVector<TemplateArgument, 4> Converted;
3778 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
3779 false, Converted))
3780 return true;
3781
Larisse Voufo39a1e502013-08-06 01:03:05 +00003782 // Find the variable template (partial) specialization declaration that
3783 // corresponds to these arguments.
3784 if (IsPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00003785 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
3786 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00003787 return true;
3788
Richard Smith57aae072016-12-28 02:37:25 +00003789 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
3790 // also do them during instantiation.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003791 bool InstantiationDependent;
3792 if (!Name.isDependent() &&
3793 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00003794 TemplateArgs.arguments(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00003795 InstantiationDependent)) {
3796 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3797 << VarTemplate->getDeclName();
3798 IsPartialSpecialization = false;
3799 }
Richard Smith300e0c32013-09-24 04:49:23 +00003800
3801 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
3802 Converted)) {
3803 // C++ [temp.class.spec]p9b3:
3804 //
3805 // -- The argument list of the specialization shall not be identical
3806 // to the implicit argument list of the primary template.
3807 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3808 << /*variable template*/ 1
3809 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
3810 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
3811 // FIXME: Recover from this by treating the declaration as a redeclaration
3812 // of the primary template.
3813 return true;
3814 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003815 }
3816
Craig Topperc3ec1492014-05-26 06:22:03 +00003817 void *InsertPos = nullptr;
3818 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003819
3820 if (IsPartialSpecialization)
3821 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00003822 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003823 else
Craig Topper7e0daca2014-06-26 04:58:53 +00003824 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003825
Craig Topperc3ec1492014-05-26 06:22:03 +00003826 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003827
3828 // Check whether we can declare a variable template specialization in
3829 // the current scope.
3830 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
3831 TemplateNameLoc,
3832 IsPartialSpecialization))
3833 return true;
3834
3835 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3836 // Since the only prior variable template specialization with these
3837 // arguments was referenced but not declared, reuse that
3838 // declaration node as our own, updating its source location and
3839 // the list of outer template parameters to reflect our new declaration.
3840 Specialization = PrevDecl;
3841 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00003842 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003843 } else if (IsPartialSpecialization) {
3844 // Create a new class template partial specialization declaration node.
3845 VarTemplatePartialSpecializationDecl *PrevPartial =
3846 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003847 VarTemplatePartialSpecializationDecl *Partial =
3848 VarTemplatePartialSpecializationDecl::Create(
3849 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
3850 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
David Majnemer8b622692016-07-03 21:17:51 +00003851 Converted, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003852
3853 if (!PrevPartial)
3854 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
3855 Specialization = Partial;
3856
3857 // If we are providing an explicit specialization of a member variable
3858 // template specialization, make a note of that.
3859 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00003860 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00003861
Richard Smith57aae072016-12-28 02:37:25 +00003862 CheckTemplatePartialSpecialization(Partial);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003863 } else {
3864 // Create a new class template specialization declaration node for
3865 // this explicit specialization or friend declaration.
3866 Specialization = VarTemplateSpecializationDecl::Create(
3867 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
David Majnemer8b622692016-07-03 21:17:51 +00003868 VarTemplate, DI->getType(), DI, SC, Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003869 Specialization->setTemplateArgsInfo(TemplateArgs);
3870
3871 if (!PrevDecl)
3872 VarTemplate->AddSpecialization(Specialization, InsertPos);
3873 }
3874
3875 // C++ [temp.expl.spec]p6:
3876 // If a template, a member template or the member of a class template is
3877 // explicitly specialized then that specialization shall be declared
3878 // before the first use of that specialization that would cause an implicit
3879 // instantiation to take place, in every translation unit in which such a
3880 // use occurs; no diagnostic is required.
3881 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3882 bool Okay = false;
3883 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
3884 // Is there any previous explicit specialization declaration?
3885 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3886 Okay = true;
3887 break;
3888 }
3889 }
3890
3891 if (!Okay) {
3892 SourceRange Range(TemplateNameLoc, RAngleLoc);
3893 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3894 << Name << Range;
3895
3896 Diag(PrevDecl->getPointOfInstantiation(),
3897 diag::note_instantiation_required_here)
3898 << (PrevDecl->getTemplateSpecializationKind() !=
3899 TSK_ImplicitInstantiation);
3900 return true;
3901 }
3902 }
3903
3904 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
3905 Specialization->setLexicalDeclContext(CurContext);
3906
3907 // Add the specialization into its lexical context, so that it can
3908 // be seen when iterating through the list of declarations in that
3909 // context. However, specializations are not found by name lookup.
3910 CurContext->addDecl(Specialization);
3911
3912 // Note that this is an explicit specialization.
3913 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
3914
3915 if (PrevDecl) {
3916 // Check that this isn't a redefinition of this specialization,
3917 // merging with previous declarations.
3918 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00003919 forRedeclarationInCurContext());
Larisse Voufo39a1e502013-08-06 01:03:05 +00003920 PrevSpec.addDecl(PrevDecl);
3921 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00003922 } else if (Specialization->isStaticDataMember() &&
3923 Specialization->isOutOfLine()) {
3924 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00003925 }
3926
3927 // Link instantiations of static data members back to the template from
3928 // which they were instantiated.
3929 if (Specialization->isStaticDataMember())
3930 Specialization->setInstantiationOfStaticDataMember(
3931 VarTemplate->getTemplatedDecl(),
3932 Specialization->getSpecializationKind());
3933
3934 return Specialization;
3935}
3936
3937namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003938/// A partial specialization whose template arguments have matched
Larisse Voufo39a1e502013-08-06 01:03:05 +00003939/// a given template-id.
3940struct PartialSpecMatchResult {
3941 VarTemplatePartialSpecializationDecl *Partial;
3942 TemplateArgumentList *Args;
3943};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003944} // end anonymous namespace
Larisse Voufo39a1e502013-08-06 01:03:05 +00003945
3946DeclResult
3947Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
3948 SourceLocation TemplateNameLoc,
3949 const TemplateArgumentListInfo &TemplateArgs) {
3950 assert(Template && "A variable template id without template?");
3951
3952 // Check that the template argument list is well-formed for this template.
3953 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003954 if (CheckTemplateArgumentList(
3955 Template, TemplateNameLoc,
3956 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00003957 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00003958 return true;
3959
3960 // Find the variable template specialization declaration that
3961 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00003962 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003963 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Richard Smith6739a102016-05-05 00:56:12 +00003964 Converted, InsertPos)) {
3965 checkSpecializationVisibility(TemplateNameLoc, Spec);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003966 // If we already have a variable template specialization, return it.
3967 return Spec;
Richard Smith6739a102016-05-05 00:56:12 +00003968 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003969
3970 // This is the first time we have referenced this variable template
3971 // specialization. Create the canonical declaration and add it to
3972 // the set of specializations, based on the closest partial specialization
3973 // that it represents. That is,
3974 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
3975 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00003976 Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003977 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
3978 bool AmbiguousPartialSpec = false;
3979 typedef PartialSpecMatchResult MatchResult;
3980 SmallVector<MatchResult, 4> Matched;
3981 SourceLocation PointOfInstantiation = TemplateNameLoc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003982 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
3983 /*ForTakingAddress=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003984
3985 // 1. Attempt to find the closest partial specialization that this
3986 // specializes, if any.
3987 // If any of the template arguments is dependent, then this is probably
3988 // a placeholder for an incomplete declarative context; which must be
3989 // complete by instantiation time. Thus, do not search through the partial
3990 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00003991 // TODO: Unify with InstantiateClassTemplateSpecialization()?
3992 // Perhaps better after unification of DeduceTemplateArguments() and
3993 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00003994 bool InstantiationDependent = false;
3995 if (!TemplateSpecializationType::anyDependentTemplateArguments(
3996 TemplateArgs, InstantiationDependent)) {
3997
3998 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3999 Template->getPartialSpecializations(PartialSpecs);
4000
4001 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
4002 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
4003 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4004
4005 if (TemplateDeductionResult Result =
4006 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
4007 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00004008 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00004009 FailedCandidates.addCandidate().set(
4010 DeclAccessPair::make(Template, AS_public), Partial,
4011 MakeDeductionFailureInfo(Context, Result, Info));
Larisse Voufo39a1e502013-08-06 01:03:05 +00004012 (void)Result;
4013 } else {
4014 Matched.push_back(PartialSpecMatchResult());
4015 Matched.back().Partial = Partial;
4016 Matched.back().Args = Info.take();
4017 }
4018 }
4019
Larisse Voufo39a1e502013-08-06 01:03:05 +00004020 if (Matched.size() >= 1) {
4021 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4022 if (Matched.size() == 1) {
4023 // -- If exactly one matching specialization is found, the
4024 // instantiation is generated from that specialization.
4025 // We don't need to do anything for this.
4026 } else {
4027 // -- If more than one matching specialization is found, the
4028 // partial order rules (14.5.4.2) are used to determine
4029 // whether one of the specializations is more specialized
4030 // than the others. If none of the specializations is more
4031 // specialized than all of the other matching
4032 // specializations, then the use of the variable template is
4033 // ambiguous and the program is ill-formed.
4034 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4035 PEnd = Matched.end();
4036 P != PEnd; ++P) {
4037 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4038 PointOfInstantiation) ==
4039 P->Partial)
4040 Best = P;
4041 }
4042
4043 // Determine if the best partial specialization is more specialized than
4044 // the others.
4045 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4046 PEnd = Matched.end();
4047 P != PEnd; ++P) {
4048 if (P != Best && getMoreSpecializedPartialSpecialization(
4049 P->Partial, Best->Partial,
4050 PointOfInstantiation) != Best->Partial) {
4051 AmbiguousPartialSpec = true;
4052 break;
4053 }
4054 }
4055 }
4056
4057 // Instantiate using the best variable template partial specialization.
4058 InstantiationPattern = Best->Partial;
4059 InstantiationArgs = Best->Args;
4060 } else {
4061 // -- If no match is found, the instantiation is generated
4062 // from the primary template.
4063 // InstantiationPattern = Template->getTemplatedDecl();
4064 }
4065 }
4066
Larisse Voufo39a1e502013-08-06 01:03:05 +00004067 // 2. Create the canonical declaration.
Richard Smith6739a102016-05-05 00:56:12 +00004068 // Note that we do not instantiate a definition until we see an odr-use
4069 // in DoMarkVarDeclReferenced().
Larisse Voufo39a1e502013-08-06 01:03:05 +00004070 // FIXME: LateAttrs et al.?
4071 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4072 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
4073 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
4074 if (!Decl)
4075 return true;
4076
4077 if (AmbiguousPartialSpec) {
4078 // Partial ordering did not produce a clear winner. Complain.
4079 Decl->setInvalidDecl();
4080 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4081 << Decl;
4082
4083 // Print the matching partial specializations.
Yaron Keren1cb81462016-11-16 13:45:34 +00004084 for (MatchResult P : Matched)
4085 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4086 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4087 *P.Args);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004088 return true;
4089 }
4090
4091 if (VarTemplatePartialSpecializationDecl *D =
4092 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4093 Decl->setInstantiationOf(D, InstantiationArgs);
4094
Richard Smith6739a102016-05-05 00:56:12 +00004095 checkSpecializationVisibility(TemplateNameLoc, Decl);
4096
Larisse Voufo39a1e502013-08-06 01:03:05 +00004097 assert(Decl && "No variable template specialization?");
4098 return Decl;
4099}
4100
4101ExprResult
4102Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
4103 const DeclarationNameInfo &NameInfo,
4104 VarTemplateDecl *Template, SourceLocation TemplateLoc,
4105 const TemplateArgumentListInfo *TemplateArgs) {
4106
4107 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4108 *TemplateArgs);
4109 if (Decl.isInvalid())
4110 return ExprError();
4111
4112 VarDecl *Var = cast<VarDecl>(Decl.get());
4113 if (!Var->getTemplateSpecializationKind())
4114 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
4115 NameInfo.getLoc());
4116
4117 // Build an ordinary singleton decl ref.
4118 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00004119 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004120}
4121
Richard Smithecad88d2018-04-26 01:08:00 +00004122void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4123 SourceLocation Loc) {
4124 Diag(Loc, diag::err_template_missing_args)
4125 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4126 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4127 Diag(TD->getLocation(), diag::note_template_decl_here)
4128 << TD->getTemplateParameters()->getSourceRange();
4129 }
4130}
4131
John McCalldadc5752010-08-24 06:29:42 +00004132ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004133 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00004134 LookupResult &R,
4135 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00004136 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00004137 // FIXME: Can we do any checking at this point? I guess we could check the
4138 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00004139 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00004140 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00004141 // foo<int> could identify a single function unambiguously
4142 // This approach does NOT work, since f<int>(1);
4143 // gets resolved prior to resorting to overload resolution
4144 // i.e., template<class T> void f(double);
4145 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00004146
4147 // These should be filtered out by our callers.
4148 assert(!R.empty() && "empty lookup results when building templateid");
4149 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4150
Richard Smith04100942018-04-26 02:10:22 +00004151 // Non-function templates require a template argument list.
4152 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4153 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4154 diagnoseMissingTemplateArguments(TemplateName(TD), R.getNameLoc());
4155 return ExprError();
4156 }
4157 }
4158
Richard Smith0bf96f92018-04-25 22:58:55 +00004159 auto AnyDependentArguments = [&]() -> bool {
4160 bool InstantiationDependent;
4161 return TemplateArgs &&
4162 TemplateSpecializationType::anyDependentTemplateArguments(
4163 *TemplateArgs, InstantiationDependent);
4164 };
4165
Larisse Voufo39a1e502013-08-06 01:03:05 +00004166 // In C++1y, check variable template ids.
Richard Smith0bf96f92018-04-25 22:58:55 +00004167 if (R.getAsSingle<VarTemplateDecl>() && !AnyDependentArguments()) {
Richard Smithd7d11ef2014-02-03 20:09:56 +00004168 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
4169 R.getAsSingle<VarTemplateDecl>(),
4170 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004171 }
4172
John McCall58cc69d2010-01-27 01:50:18 +00004173 // We don't want lookup warnings at this point.
4174 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004175
John McCalle66edc12009-11-24 19:00:30 +00004176 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00004177 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00004178 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00004179 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004180 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004181 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00004182 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00004183
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004184 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00004185}
4186
John McCalle66edc12009-11-24 19:00:30 +00004187// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00004188ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004189Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004190 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004191 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00004192 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004193
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00004194 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00004195 DeclContext *DC;
4196 if (!(DC = computeDeclContext(SS, false)) ||
4197 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00004198 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00004199 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004200
Douglas Gregor786123d2010-05-21 23:18:07 +00004201 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004202 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Richard Smith79810042018-05-11 02:43:08 +00004203 if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(),
4204 /*Entering*/false, MemberOfUnknownSpecialization,
4205 TemplateKWLoc))
4206 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004207
John McCalle66edc12009-11-24 19:00:30 +00004208 if (R.isAmbiguous())
4209 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004210
John McCalle66edc12009-11-24 19:00:30 +00004211 if (R.empty()) {
Richard Smith79810042018-05-11 02:43:08 +00004212 Diag(NameInfo.getLoc(), diag::err_no_member)
4213 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00004214 return ExprError();
4215 }
4216
4217 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004218 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00004219 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00004220 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00004221 Diag(Temp->getLocation(), diag::note_referenced_class_template);
4222 return ExprError();
4223 }
4224
Abramo Bagnara7945c982012-01-27 09:46:47 +00004225 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00004226}
4227
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004228/// Form a dependent template name.
Douglas Gregorb67535d2009-03-31 00:43:58 +00004229///
4230/// This action forms a dependent template name given the template
4231/// name and its (presumably dependent) scope specifier. For
4232/// example, given "MetaFun::template apply", the scope specifier \p
4233/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
4234/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004235TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00004236 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004237 SourceLocation TemplateKWLoc,
Richard Smithc08b6932018-04-27 02:00:13 +00004238 const UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00004239 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00004240 bool EnteringContext,
Richard Smithfd3dae02017-01-20 00:20:39 +00004241 TemplateTy &Result,
4242 bool AllowInjectedClassName) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004243 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4244 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004245 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004246 diag::warn_cxx98_compat_template_outside_of_template :
4247 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004248 << FixItHint::CreateRemoval(TemplateKWLoc);
4249
Craig Topperc3ec1492014-05-26 06:22:03 +00004250 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00004251 if (SS.isSet())
4252 LookupCtx = computeDeclContext(SS, EnteringContext);
4253 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00004254 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00004255 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00004256 // C++0x [temp.names]p5:
4257 // If a name prefixed by the keyword template is not the name of
4258 // a template, the program is ill-formed. [Note: the keyword
4259 // template may not be applied to non-template members of class
4260 // templates. -end note ] [ Note: as is the case with the
4261 // typename prefix, the template prefix is allowed in cases
4262 // where it is not strictly necessary; i.e., when the
4263 // nested-name-specifier or the expression on the left of the ->
4264 // or . is not dependent on a template-parameter, or the use
4265 // does not appear in the scope of a template. -end note]
4266 //
4267 // Note: C++03 was more strict here, because it banned the use of
4268 // the "template" keyword prior to a template-name that was not a
4269 // dependent name. C++ DR468 relaxed this requirement (the
4270 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00004271 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00004272 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00004273 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00004274 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00004275 MemberOfUnknownSpecialization);
Richard Smith79810042018-05-11 02:43:08 +00004276 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization) {
Douglas Gregorbb119652010-06-16 23:00:59 +00004277 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00004278 } else if (TNK == TNK_Non_template) {
Richard Smith79810042018-05-11 02:43:08 +00004279 // Do the lookup again to determine if this is a "nothing found" case or
4280 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
4281 // need to do this.
4282 DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004283 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
Richard Smith79810042018-05-11 02:43:08 +00004284 LookupOrdinaryName);
4285 bool MOUS;
4286 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext,
Richard Smithafcfb6b2019-02-15 21:53:07 +00004287 MOUS, TemplateKWLoc) && !R.isAmbiguous())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004288 Diag(Name.getBeginLoc(), diag::err_no_member)
Richard Smith79810042018-05-11 02:43:08 +00004289 << DNI.getName() << LookupCtx << SS.getRange();
Douglas Gregorbb119652010-06-16 23:00:59 +00004290 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00004291 } else {
4292 // We found something; return it.
Richard Smithfd3dae02017-01-20 00:20:39 +00004293 auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
4294 if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
Faisal Vali2ab8c152017-12-30 04:15:27 +00004295 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4296 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
Richard Smithfd3dae02017-01-20 00:20:39 +00004297 // C++14 [class.qual]p2:
4298 // In a lookup in which function names are not ignored and the
4299 // nested-name-specifier nominates a class C, if the name specified
4300 // [...] is the injected-class-name of C, [...] the name is instead
4301 // considered to name the constructor
4302 //
4303 // We don't get here if naming the constructor would be valid, so we
4304 // just reject immediately and recover by treating the
4305 // injected-class-name as naming the template.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004306 Diag(Name.getBeginLoc(),
Richard Smithfd3dae02017-01-20 00:20:39 +00004307 diag::ext_out_of_line_qualified_id_type_names_constructor)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004308 << Name.Identifier
4309 << 0 /*injected-class-name used as template name*/
4310 << 1 /*'template' keyword was used*/;
Richard Smithfd3dae02017-01-20 00:20:39 +00004311 }
Douglas Gregorbb119652010-06-16 23:00:59 +00004312 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00004313 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00004314 }
4315
Aaron Ballman4a979672014-01-03 13:56:08 +00004316 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004317
Douglas Gregor3cf81312009-11-03 23:16:33 +00004318 switch (Name.getKind()) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00004319 case UnqualifiedIdKind::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004320 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00004321 Name.Identifier));
4322 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004323
Faisal Vali2ab8c152017-12-30 04:15:27 +00004324 case UnqualifiedIdKind::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00004325 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00004326 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00004327 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00004328
Faisal Vali2ab8c152017-12-30 04:15:27 +00004329 case UnqualifiedIdKind::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00004330 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00004331
Douglas Gregor3cf81312009-11-03 23:16:33 +00004332 default:
4333 break;
4334 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004335
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004336 Diag(Name.getBeginLoc(), diag::err_template_kw_refers_to_non_template)
4337 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
4338 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00004339 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00004340}
4341
Mike Stump11289f42009-09-09 15:08:12 +00004342bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00004343 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004344 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00004345 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00004346 QualType ArgType;
4347 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00004348
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004349 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004350 switch(Arg.getKind()) {
4351 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004352 // C++ [temp.arg.type]p1:
4353 // A template-argument for a template-parameter which is a
4354 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00004355 ArgType = Arg.getAsType();
4356 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004357 break;
Richard Smith77a9c602018-02-28 03:02:23 +00004358 case TemplateArgument::Template:
4359 case TemplateArgument::TemplateExpansion: {
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004360 // We have a template type parameter but the template argument
4361 // is a template without any arguments.
4362 SourceRange SR = AL.getSourceRange();
Richard Smith77a9c602018-02-28 03:02:23 +00004363 TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
Richard Smithecad88d2018-04-26 01:08:00 +00004364 diagnoseMissingTemplateArguments(Name, SR.getEnd());
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004365 return true;
4366 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004367 case TemplateArgument::Expression: {
4368 // We have a template type parameter but the template argument is an
4369 // expression; see if maybe it is missing the "typename" keyword.
4370 CXXScopeSpec SS;
4371 DeclarationNameInfo NameInfo;
4372
4373 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
4374 SS.Adopt(ArgExpr->getQualifierLoc());
4375 NameInfo = ArgExpr->getNameInfo();
4376 } else if (DependentScopeDeclRefExpr *ArgExpr =
4377 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4378 SS.Adopt(ArgExpr->getQualifierLoc());
4379 NameInfo = ArgExpr->getNameInfo();
4380 } else if (CXXDependentScopeMemberExpr *ArgExpr =
4381 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00004382 if (ArgExpr->isImplicitAccess()) {
4383 SS.Adopt(ArgExpr->getQualifierLoc());
4384 NameInfo = ArgExpr->getMemberNameInfo();
4385 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004386 }
4387
Reid Kleckner377c1592014-06-10 23:29:48 +00004388 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004389 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4390 LookupParsedName(Result, CurScope, &SS);
4391
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00004392 if (Result.getAsSingle<TypeDecl>() ||
4393 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00004394 LookupResult::NotFoundInCurrentInstantiation) {
4395 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004396 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00004397 Diag(Loc, getLangOpts().MSVCCompat
4398 ? diag::ext_ms_template_type_arg_missing_typename
4399 : diag::err_template_arg_must_be_type_suggest)
4400 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004401 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00004402
4403 // Recover by synthesizing a type using the location information that we
4404 // already have.
4405 ArgType =
4406 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
4407 TypeLocBuilder TLB;
4408 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
4409 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4410 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4411 TL.setNameLoc(NameInfo.getLoc());
4412 TSI = TLB.getTypeSourceInfo(Context, ArgType);
4413
4414 // Overwrite our input TemplateArgumentLoc so that we can recover
4415 // properly.
4416 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
4417 TemplateArgumentLocInfo(TSI));
4418
4419 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004420 }
4421 }
4422 // fallthrough
Galina Kistanova3779cb32017-06-07 06:25:05 +00004423 LLVM_FALLTHROUGH;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004424 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004425 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004426 // We have a template type parameter but the template argument
4427 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00004428 SourceRange SR = AL.getSourceRange();
4429 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004430 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00004431
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004432 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004433 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004434 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004435
Reid Kleckner377c1592014-06-10 23:29:48 +00004436 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004437 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004438
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004439 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00004440 ArgType = Context.getCanonicalType(ArgType);
Simon Pilgrim6905d222016-12-30 22:55:33 +00004441
Douglas Gregore46db902011-06-17 22:11:49 +00004442 // Objective-C ARC:
4443 // If an explicitly-specified template argument type is a lifetime type
4444 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004445 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00004446 ArgType->isObjCLifetimeType() &&
4447 !ArgType.getObjCLifetime()) {
4448 Qualifiers Qs;
4449 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
4450 ArgType = Context.getQualifiedType(ArgType, Qs);
4451 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00004452
Douglas Gregore46db902011-06-17 22:11:49 +00004453 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004454 return false;
4455}
4456
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004457/// Substitute template arguments into the default template argument for
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004458/// the given template type parameter.
4459///
4460/// \param SemaRef the semantic analysis object for which we are performing
4461/// the substitution.
4462///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004463/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004464/// for.
4465///
4466/// \param TemplateLoc the location of the template name that started the
4467/// template-id we are checking.
4468///
4469/// \param RAngleLoc the location of the right angle bracket ('>') that
4470/// terminates the template-id.
4471///
4472/// \param Param the template template parameter whose default we are
4473/// substituting into.
4474///
4475/// \param Converted the list of template arguments provided for template
4476/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004477/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00004478static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004479SubstDefaultTemplateArgument(Sema &SemaRef,
4480 TemplateDecl *Template,
4481 SourceLocation TemplateLoc,
4482 SourceLocation RAngleLoc,
4483 TemplateTypeParmDecl *Param,
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00004484 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00004485 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004486
4487 // If the argument type is dependent, instantiate it now based
4488 // on the previously-computed template arguments.
Erik Pilkingtonba88e212018-11-12 21:31:06 +00004489 if (ArgType->getType()->isInstantiationDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004490 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00004491 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004492 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004493 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00004494 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004495
David Majnemer8b622692016-07-03 21:17:51 +00004496 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004497
4498 // Only substitute for the innermost template argument list.
4499 MultiLevelTemplateArgumentList TemplateArgLists;
4500 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4501 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4502 TemplateArgLists.addOuterTemplateArguments(None);
4503
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00004504 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00004505 ArgType =
4506 SemaRef.SubstType(ArgType, TemplateArgLists,
4507 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004508 }
4509
4510 return ArgType;
4511}
4512
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004513/// Substitute template arguments into the default template argument for
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004514/// the given non-type template parameter.
4515///
4516/// \param SemaRef the semantic analysis object for which we are performing
4517/// the substitution.
4518///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004519/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004520/// for.
4521///
4522/// \param TemplateLoc the location of the template name that started the
4523/// template-id we are checking.
4524///
4525/// \param RAngleLoc the location of the right angle bracket ('>') that
4526/// terminates the template-id.
4527///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004528/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004529/// substituting into.
4530///
4531/// \param Converted the list of template arguments provided for template
4532/// parameters that precede \p Param in the template parameter list.
4533///
4534/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00004535static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004536SubstDefaultTemplateArgument(Sema &SemaRef,
4537 TemplateDecl *Template,
4538 SourceLocation TemplateLoc,
4539 SourceLocation RAngleLoc,
4540 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004541 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004542 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00004543 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004544 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004545 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004546 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004547
David Majnemer8b622692016-07-03 21:17:51 +00004548 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004549
4550 // Only substitute for the innermost template argument list.
4551 MultiLevelTemplateArgumentList TemplateArgLists;
4552 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4553 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4554 TemplateArgLists.addOuterTemplateArguments(None);
4555
Faisal Valid143a0c2017-04-01 21:30:49 +00004556 EnterExpressionEvaluationContext ConstantEvaluated(
4557 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00004558 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004559}
4560
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004561/// Substitute template arguments into the default template argument for
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004562/// the given template template parameter.
4563///
4564/// \param SemaRef the semantic analysis object for which we are performing
4565/// the substitution.
4566///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004567/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004568/// for.
4569///
4570/// \param TemplateLoc the location of the template name that started the
4571/// template-id we are checking.
4572///
4573/// \param RAngleLoc the location of the right angle bracket ('>') that
4574/// terminates the template-id.
4575///
4576/// \param Param the template template parameter whose default we are
4577/// substituting into.
4578///
4579/// \param Converted the list of template arguments provided for template
4580/// parameters that precede \p Param in the template parameter list.
4581///
Simon Pilgrim6905d222016-12-30 22:55:33 +00004582/// \param QualifierLoc Will be set to the nested-name-specifier (with
Douglas Gregordf846d12011-03-02 18:46:51 +00004583/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00004584///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004585/// \returns the substituted template argument, or NULL if an error occurred.
4586static TemplateName
4587SubstDefaultTemplateArgument(Sema &SemaRef,
4588 TemplateDecl *Template,
4589 SourceLocation TemplateLoc,
4590 SourceLocation RAngleLoc,
4591 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004592 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00004593 NestedNameSpecifierLoc &QualifierLoc) {
Richard Smith54f18e82016-08-31 02:15:21 +00004594 Sema::InstantiatingTemplate Inst(
4595 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
4596 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004597 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004598 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004599
David Majnemer8b622692016-07-03 21:17:51 +00004600 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004601
4602 // Only substitute for the innermost template argument list.
4603 MultiLevelTemplateArgumentList TemplateArgLists;
4604 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4605 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4606 TemplateArgLists.addOuterTemplateArguments(None);
4607
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00004608 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00004609 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00004610 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00004611 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00004612 QualifierLoc =
4613 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00004614 if (!QualifierLoc)
4615 return TemplateName();
4616 }
David Majnemer89189202013-08-28 23:48:32 +00004617
4618 return SemaRef.SubstTemplateName(
4619 QualifierLoc,
4620 Param->getDefaultArgument().getArgument().getAsTemplate(),
4621 Param->getDefaultArgument().getTemplateNameLoc(),
4622 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004623}
4624
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004625/// If the given template parameter has a default template
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004626/// argument, substitute into that default template argument and
4627/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004628TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004629Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
4630 SourceLocation TemplateLoc,
4631 SourceLocation RAngleLoc,
4632 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00004633 SmallVectorImpl<TemplateArgument>
4634 &Converted,
4635 bool &HasDefaultArg) {
4636 HasDefaultArg = false;
4637
4638 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004639 if (!hasVisibleDefaultArgument(TypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004640 return TemplateArgumentLoc();
4641
Richard Smithc87b9382013-07-04 01:01:24 +00004642 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00004643 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004644 TemplateLoc,
4645 RAngleLoc,
4646 TypeParm,
4647 Converted);
4648 if (DI)
4649 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4650
4651 return TemplateArgumentLoc();
4652 }
4653
4654 if (NonTypeTemplateParmDecl *NonTypeParm
4655 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004656 if (!hasVisibleDefaultArgument(NonTypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004657 return TemplateArgumentLoc();
4658
Richard Smithc87b9382013-07-04 01:01:24 +00004659 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00004660 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00004661 TemplateLoc,
4662 RAngleLoc,
4663 NonTypeParm,
4664 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004665 if (Arg.isInvalid())
4666 return TemplateArgumentLoc();
4667
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004668 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004669 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
4670 }
4671
4672 TemplateTemplateParmDecl *TempTempParm
4673 = cast<TemplateTemplateParmDecl>(Param);
Richard Smith95d83952015-06-10 20:36:34 +00004674 if (!hasVisibleDefaultArgument(TempTempParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004675 return TemplateArgumentLoc();
4676
Richard Smithc87b9382013-07-04 01:01:24 +00004677 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00004678 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004679 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004680 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004681 RAngleLoc,
4682 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00004683 Converted,
4684 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004685 if (TName.isNull())
4686 return TemplateArgumentLoc();
4687
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004688 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00004689 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004690 TempTempParm->getDefaultArgument().getTemplateNameLoc());
4691}
4692
Richard Smith11255ec2017-01-18 19:19:22 +00004693/// Convert a template-argument that we parsed as a type into a template, if
4694/// possible. C++ permits injected-class-names to perform dual service as
4695/// template template arguments and as template type arguments.
4696static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
4697 // Extract and step over any surrounding nested-name-specifier.
4698 NestedNameSpecifierLoc QualLoc;
4699 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4700 if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
4701 return TemplateArgumentLoc();
4702
4703 QualLoc = ETLoc.getQualifierLoc();
4704 TLoc = ETLoc.getNamedTypeLoc();
4705 }
4706
4707 // If this type was written as an injected-class-name, it can be used as a
4708 // template template argument.
4709 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4710 return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
4711 QualLoc, InjLoc.getNameLoc());
4712
4713 // If this type was written as an injected-class-name, it may have been
4714 // converted to a RecordType during instantiation. If the RecordType is
4715 // *not* wrapped in a TemplateSpecializationType and denotes a class
4716 // template specialization, it must have come from an injected-class-name.
4717 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
4718 if (auto *CTSD =
4719 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
4720 return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
4721 QualLoc, RecLoc.getNameLoc());
4722
4723 return TemplateArgumentLoc();
4724}
4725
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004726/// Check that the given template argument corresponds to the given
Douglas Gregorda0fb532009-11-11 19:31:23 +00004727/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004728///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004729/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004730/// checked.
4731///
Richard Trieu15b66532015-01-24 02:48:32 +00004732/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004733///
4734/// \param Template The template in which the template argument resides.
4735///
4736/// \param TemplateLoc The location of the template name for the template
4737/// whose argument list we're matching.
4738///
4739/// \param RAngleLoc The location of the right angle bracket ('>') that closes
4740/// the template argument list.
4741///
4742/// \param ArgumentPackIndex The index into the argument pack where this
4743/// argument will be placed. Only valid if the parameter is a parameter pack.
4744///
4745/// \param Converted The checked, converted argument will be added to the
4746/// end of this small vector.
4747///
4748/// \param CTAK Describes how we arrived at this particular template argument:
4749/// explicitly written, deduced, etc.
4750///
4751/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004752bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00004753 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00004754 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004755 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004756 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004757 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004758 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00004759 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00004760 // Check template type parameters.
4761 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004762 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004763
Douglas Gregoreebed722009-11-11 19:41:09 +00004764 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004765 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004766 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00004767 // with the template arguments we've seen thus far. But if the
4768 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004769 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004770 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
4771 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004772
Richard Smith5d331022018-03-08 01:07:33 +00004773 // FIXME: Do we need to substitute into parameters here if they're
4774 // instantiation-dependent but not dependent?
Peter Collingbourne01687632010-12-10 17:08:53 +00004775 if (NTTPType->isDependentType() &&
4776 !isa<TemplateTemplateParmDecl>(Template) &&
4777 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004778 // Do substitution on the type of the non-type template parameter.
4779 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00004780 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004781 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004782 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004783 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004784
4785 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00004786 Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004787 NTTPType = SubstType(NTTPType,
4788 MultiLevelTemplateArgumentList(TemplateArgs),
4789 NTTP->getLocation(),
4790 NTTP->getDeclName());
4791 // If that worked, check the non-type template parameter type
4792 // for validity.
4793 if (!NTTPType.isNull())
4794 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
4795 NTTP->getLocation());
4796 if (NTTPType.isNull())
4797 return true;
4798 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004799
Douglas Gregorda0fb532009-11-11 19:31:23 +00004800 switch (Arg.getArgument().getKind()) {
4801 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00004802 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004803
Douglas Gregorda0fb532009-11-11 19:31:23 +00004804 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004805 TemplateArgument Result;
Erich Keanec90bb6d2018-05-07 17:05:20 +00004806 unsigned CurSFINAEErrors = NumSFINAEErrors;
John Wiegley01296292011-04-08 18:41:53 +00004807 ExprResult Res =
4808 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
4809 Result, CTAK);
4810 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00004811 return true;
Erich Keanec90bb6d2018-05-07 17:05:20 +00004812 // If the current template argument causes an error, give up now.
4813 if (CurSFINAEErrors < NumSFINAEErrors)
4814 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004815
Richard Trieu15b66532015-01-24 02:48:32 +00004816 // If the resulting expression is new, then use it in place of the
4817 // old expression in the template argument.
4818 if (Res.get() != Arg.getArgument().getAsExpr()) {
4819 TemplateArgument TA(Res.get());
4820 Arg = TemplateArgumentLoc(TA, Res.get());
4821 }
4822
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004823 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004824 break;
4825 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004826
Douglas Gregorda0fb532009-11-11 19:31:23 +00004827 case TemplateArgument::Declaration:
4828 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00004829 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00004830 // We've already checked this template argument, so just copy
4831 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004832 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00004833 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004834
Douglas Gregorda0fb532009-11-11 19:31:23 +00004835 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004836 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00004837 // We were given a template template argument. It may not be ill-formed;
4838 // see below.
4839 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004840 = Arg.getArgument().getAsTemplateOrTemplatePattern()
4841 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004842 // We have a template argument such as \c T::template X, which we
4843 // parsed as a template template argument. However, since we now
4844 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004845 // template name into an expression.
4846
4847 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
4848 Arg.getTemplateNameLoc());
4849
Douglas Gregor3a43fd62011-02-25 20:49:16 +00004850 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00004851 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00004852 // FIXME: the template-template arg was a DependentTemplateName,
4853 // so it was provided with a template keyword. However, its source
4854 // location is not stored in the template argument structure.
4855 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004856 ExprResult E = DependentScopeDeclRefExpr::Create(
4857 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
4858 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004859
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004860 // If we parsed the template argument as a pack expansion, create a
4861 // pack expansion expression.
4862 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004863 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00004864 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004865 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004866 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004867
Douglas Gregorda0fb532009-11-11 19:31:23 +00004868 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004869 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00004870 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00004871 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004872
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004873 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004874 break;
4875 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004876
Douglas Gregorda0fb532009-11-11 19:31:23 +00004877 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00004878 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00004879 // therefore cannot be a non-type template argument.
4880 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
4881 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004882
Douglas Gregorda0fb532009-11-11 19:31:23 +00004883 Diag(Param->getLocation(), diag::note_template_param_here);
4884 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004885
Douglas Gregorda0fb532009-11-11 19:31:23 +00004886 case TemplateArgument::Type: {
4887 // We have a non-type template parameter but the template
4888 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004889
Douglas Gregorda0fb532009-11-11 19:31:23 +00004890 // C++ [temp.arg]p2:
4891 // In a template-argument, an ambiguity between a type-id and
4892 // an expression is resolved to a type-id, regardless of the
4893 // form of the corresponding template-parameter.
4894 //
4895 // We warn specifically about this case, since it can be rather
4896 // confusing for users.
4897 QualType T = Arg.getArgument().getAsType();
4898 SourceRange SR = Arg.getSourceRange();
4899 if (T->isFunctionType())
4900 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
4901 else
4902 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
4903 Diag(Param->getLocation(), diag::note_template_param_here);
4904 return true;
4905 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004906
Douglas Gregorda0fb532009-11-11 19:31:23 +00004907 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004908 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004909 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004910
Douglas Gregorda0fb532009-11-11 19:31:23 +00004911 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004912 }
4913
4914
Douglas Gregorda0fb532009-11-11 19:31:23 +00004915 // Check template template parameters.
4916 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004917
Richard Smith5d331022018-03-08 01:07:33 +00004918 TemplateParameterList *Params = TempParm->getTemplateParameters();
4919 if (TempParm->isExpandedParameterPack())
4920 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
4921
Douglas Gregorda0fb532009-11-11 19:31:23 +00004922 // Substitute into the template parameter list of the template
4923 // template parameter, since previously-supplied template arguments
4924 // may appear within the template template parameter.
Richard Smith5d331022018-03-08 01:07:33 +00004925 //
4926 // FIXME: Skip this if the parameters aren't instantiation-dependent.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004927 {
4928 // Set up a template instantiation context.
4929 LocalInstantiationScope Scope(*this);
4930 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00004931 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004932 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004933 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004934 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004935
David Majnemer8b622692016-07-03 21:17:51 +00004936 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
Richard Smith5d331022018-03-08 01:07:33 +00004937 Params = SubstTemplateParams(Params, CurContext,
4938 MultiLevelTemplateArgumentList(TemplateArgs));
4939 if (!Params)
Douglas Gregorda0fb532009-11-11 19:31:23 +00004940 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00004941 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004942
Richard Smith11255ec2017-01-18 19:19:22 +00004943 // C++1z [temp.local]p1: (DR1004)
4944 // When [the injected-class-name] is used [...] as a template-argument for
4945 // a template template-parameter [...] it refers to the class template
4946 // itself.
4947 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
4948 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
4949 Arg.getTypeSourceInfo()->getTypeLoc());
4950 if (!ConvertedArg.getArgument().isNull())
4951 Arg = ConvertedArg;
4952 }
4953
Douglas Gregorda0fb532009-11-11 19:31:23 +00004954 switch (Arg.getArgument().getKind()) {
4955 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00004956 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004957
Douglas Gregorda0fb532009-11-11 19:31:23 +00004958 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004959 case TemplateArgument::TemplateExpansion:
Richard Smith5d331022018-03-08 01:07:33 +00004960 if (CheckTemplateTemplateArgument(Params, Arg))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004961 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004962
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004963 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00004964 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004965
Douglas Gregorda0fb532009-11-11 19:31:23 +00004966 case TemplateArgument::Expression:
4967 case TemplateArgument::Type:
4968 // We have a template template parameter but the template
4969 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004970 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004971 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00004972 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004973
Douglas Gregorda0fb532009-11-11 19:31:23 +00004974 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00004975 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004976 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00004977 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00004978 case TemplateArgument::NullPtr:
4979 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004980
Douglas Gregorda0fb532009-11-11 19:31:23 +00004981 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004982 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00004983 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004984
Douglas Gregorda0fb532009-11-11 19:31:23 +00004985 return false;
4986}
4987
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004988/// Check whether the template parameter is a pack expansion, and if so,
Richard Smith1fde8ec2012-09-07 02:06:42 +00004989/// determine the number of parameters produced by that expansion. For instance:
4990///
4991/// \code
4992/// template<typename ...Ts> struct A {
4993/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
4994/// };
4995/// \endcode
4996///
4997/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
4998/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00004999static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00005000 if (NonTypeTemplateParmDecl *NTTP
5001 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5002 if (NTTP->isExpandedParameterPack())
5003 return NTTP->getNumExpansionTypes();
5004 }
5005
5006 if (TemplateTemplateParmDecl *TTP
5007 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
5008 if (TTP->isExpandedParameterPack())
5009 return TTP->getNumExpansionTemplateParameters();
5010 }
5011
David Blaikie7a30dc52013-02-21 01:47:18 +00005012 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00005013}
5014
Richard Smith35c1df52015-06-17 20:16:32 +00005015/// Diagnose a missing template argument.
5016template<typename TemplateParmDecl>
5017static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
5018 TemplateDecl *TD,
5019 const TemplateParmDecl *D,
5020 TemplateArgumentListInfo &Args) {
5021 // Dig out the most recent declaration of the template parameter; there may be
5022 // declarations of the template that are more recent than TD.
5023 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
5024 ->getTemplateParameters()
5025 ->getParam(D->getIndex()));
5026
5027 // If there's a default argument that's not visible, diagnose that we're
5028 // missing a module import.
5029 llvm::SmallVector<Module*, 8> Modules;
5030 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
5031 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
5032 D->getDefaultArgumentLoc(), Modules,
5033 Sema::MissingImportKind::DefaultArgument,
Richard Smith6739a102016-05-05 00:56:12 +00005034 /*Recover*/true);
Richard Smith35c1df52015-06-17 20:16:32 +00005035 return true;
5036 }
5037
5038 // FIXME: If there's a more recent default argument that *is* visible,
5039 // diagnose that it was declared too late.
5040
Richard Smith4a8f3512018-07-19 19:00:37 +00005041 TemplateParameterList *Params = TD->getTemplateParameters();
5042
5043 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5044 << /*not enough args*/0
5045 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD))
5046 << TD;
5047 S.Diag(TD->getLocation(), diag::note_template_decl_here)
5048 << Params->getSourceRange();
5049 return true;
Richard Smith35c1df52015-06-17 20:16:32 +00005050}
5051
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005052/// Check that the given template argument list is well-formed
Douglas Gregord32e0282009-02-09 23:23:08 +00005053/// for specializing the given template.
Richard Smith11255ec2017-01-18 19:19:22 +00005054bool Sema::CheckTemplateArgumentList(
5055 TemplateDecl *Template, SourceLocation TemplateLoc,
5056 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
5057 SmallVectorImpl<TemplateArgument> &Converted,
5058 bool UpdateArgsWithConversions) {
Richard Trieu15b66532015-01-24 02:48:32 +00005059 // Make a copy of the template arguments for processing. Only make the
5060 // changes at the end when successful in matching the arguments to the
5061 // template.
5062 TemplateArgumentListInfo NewArgs = TemplateArgs;
5063
Erich Keaneaf0795b2017-10-24 01:39:56 +00005064 // Make sure we get the template parameter list from the most
5065 // recentdeclaration, since that is the only one that has is guaranteed to
5066 // have all the default template argument information.
5067 TemplateParameterList *Params =
5068 cast<TemplateDecl>(Template->getMostRecentDecl())
5069 ->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00005070
Richard Trieu15b66532015-01-24 02:48:32 +00005071 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00005072
Mike Stump11289f42009-09-09 15:08:12 +00005073 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00005074 // [...] The type and form of each template-argument specified in
5075 // a template-id shall match the type and form specified for the
5076 // corresponding parameter declared by the template in its
5077 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00005078 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005079 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00005080 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00005081 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00005082 for (TemplateParameterList::iterator Param = Params->begin(),
5083 ParamEnd = Params->end();
5084 Param != ParamEnd; /* increment in loop */) {
5085 // If we have an expanded parameter pack, make sure we don't have too
5086 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00005087 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00005088 if (*Expansions == ArgumentPack.size()) {
5089 // We're done with this parameter pack. Pack up its arguments and add
5090 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00005091 Converted.push_back(
Benjamin Kramercce63472015-08-05 09:40:22 +00005092 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00005093 ArgumentPack.clear();
5094
Richard Smith1fde8ec2012-09-07 02:06:42 +00005095 // This argument is assigned to the next parameter.
5096 ++Param;
5097 continue;
5098 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5099 // Not enough arguments for this parameter pack.
5100 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
Richard Smith4a8f3512018-07-19 19:00:37 +00005101 << /*not enough args*/0
Richard Smith0c062b42017-01-14 02:19:59 +00005102 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
Richard Smith1fde8ec2012-09-07 02:06:42 +00005103 << Template;
5104 Diag(Template->getLocation(), diag::note_template_decl_here)
5105 << Params->getSourceRange();
5106 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00005107 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00005108 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005109
Richard Smith1fde8ec2012-09-07 02:06:42 +00005110 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00005111 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00005112 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005113 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00005114 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00005115 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005116
Richard Smith96d71c32014-11-12 23:38:38 +00005117 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00005118 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00005119 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
5120 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00005121 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00005122 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00005123 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00005124 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00005125 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00005126 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00005127 Diag((*Param)->getLocation(), diag::note_template_param_here);
5128 return true;
5129 }
5130
Richard Smith1fde8ec2012-09-07 02:06:42 +00005131 // We're now done with this argument.
5132 ++ArgIdx;
5133
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005134 if ((*Param)->isTemplateParameterPack()) {
5135 // The template parameter was a template parameter pack, so take the
5136 // deduced argument and place it on the argument pack. Note that we
5137 // stay on the same template parameter so that we can deduce more
5138 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00005139 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005140 } else {
5141 // Move to the next template parameter.
5142 ++Param;
5143 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00005144
Richard Smith96d71c32014-11-12 23:38:38 +00005145 // If we just saw a pack expansion into a non-pack, then directly convert
5146 // the remaining arguments, because we don't know what parameters they'll
5147 // match up with.
5148 if (PackExpansionIntoNonPack) {
5149 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00005150 // If we were part way through filling in an expanded parameter pack,
5151 // fall back to just producing individual arguments.
5152 Converted.insert(Converted.end(),
5153 ArgumentPack.begin(), ArgumentPack.end());
5154 ArgumentPack.clear();
5155 }
5156
5157 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00005158 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00005159 ++ArgIdx;
5160 }
5161
Richard Smith1fde8ec2012-09-07 02:06:42 +00005162 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00005163 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00005164
Douglas Gregor84d49a22009-11-11 21:54:23 +00005165 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005166 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005167
Douglas Gregor2f157c92011-06-03 02:59:40 +00005168 // If we're checking a partial template argument list, we're done.
5169 if (PartialTemplateArgs) {
5170 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
Benjamin Kramercce63472015-08-05 09:40:22 +00005171 Converted.push_back(
5172 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5173
Richard Smith1fde8ec2012-09-07 02:06:42 +00005174 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00005175 }
5176
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005177 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005178 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00005179 if ((*Param)->isTemplateParameterPack()) {
5180 assert(!getExpandedPackSize(*Param) &&
5181 "Should have dealt with this already");
5182
5183 // A non-expanded parameter pack before the end of the parameter list
5184 // only occurs for an ill-formed template parameter list, unless we've
5185 // got a partial argument list for a function template, so just bail out.
5186 if (Param + 1 != ParamEnd)
5187 return true;
5188
Benjamin Kramercce63472015-08-05 09:40:22 +00005189 Converted.push_back(
5190 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00005191 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00005192
5193 ++Param;
5194 continue;
5195 }
5196
Douglas Gregor8e072612012-02-03 07:34:46 +00005197 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00005198 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005199
Douglas Gregor84d49a22009-11-11 21:54:23 +00005200 // Retrieve the default template argument from the template
5201 // parameter. For each kind of template parameter, we substitute the
5202 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005203 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00005204 // the default argument.
5205 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00005206 if (!hasVisibleDefaultArgument(TTP))
Richard Smith35c1df52015-06-17 20:16:32 +00005207 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
5208 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005209
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005210 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00005211 Template,
5212 TemplateLoc,
5213 RAngleLoc,
5214 TTP,
5215 Converted);
5216 if (!ArgType)
5217 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005218
Douglas Gregor84d49a22009-11-11 21:54:23 +00005219 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
5220 ArgType);
5221 } else if (NonTypeTemplateParmDecl *NTTP
5222 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00005223 if (!hasVisibleDefaultArgument(NTTP))
Richard Smith35c1df52015-06-17 20:16:32 +00005224 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
5225 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005226
John McCalldadc5752010-08-24 06:29:42 +00005227 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005228 TemplateLoc,
5229 RAngleLoc,
5230 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00005231 Converted);
5232 if (E.isInvalid())
5233 return true;
5234
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005235 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00005236 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
5237 } else {
5238 TemplateTemplateParmDecl *TempParm
5239 = cast<TemplateTemplateParmDecl>(*Param);
5240
Richard Smith95d83952015-06-10 20:36:34 +00005241 if (!hasVisibleDefaultArgument(TempParm))
Richard Smith35c1df52015-06-17 20:16:32 +00005242 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
5243 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005244
Douglas Gregordf846d12011-03-02 18:46:51 +00005245 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00005246 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005247 TemplateLoc,
5248 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00005249 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00005250 Converted,
5251 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005252 if (Name.isNull())
5253 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005254
Douglas Gregor9d802122011-03-02 17:09:35 +00005255 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
5256 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00005257 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005258
Douglas Gregor84d49a22009-11-11 21:54:23 +00005259 // Introduce an instantiation record that describes where we are using
Richard Smith54f18e82016-08-31 02:15:21 +00005260 // the default template argument. We're not actually instantiating a
5261 // template here, we just create this object to put a note into the
5262 // context stack.
Alp Tokerd4a72d52013-10-08 08:09:04 +00005263 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
5264 SourceRange(TemplateLoc, RAngleLoc));
5265 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00005266 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005267
Douglas Gregor84d49a22009-11-11 21:54:23 +00005268 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00005269 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00005270 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00005271 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005272
Richard Trieu15b66532015-01-24 02:48:32 +00005273 // Core issue 150 (assumed resolution): if this is a template template
5274 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00005275 // template definition.
5276 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00005277 NewArgs.addArgument(Arg);
5278
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005279 // Move to the next template parameter and argument.
5280 ++Param;
5281 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00005282 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005283
Richard Smith07f79912014-06-06 16:00:50 +00005284 // If we're performing a partial argument substitution, allow any trailing
5285 // pack expansions; they might be empty. This can happen even if
5286 // PartialTemplateArgs is false (the list of arguments is complete but
5287 // still dependent).
5288 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5289 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00005290 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
5291 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00005292 }
5293
Douglas Gregor8e072612012-02-03 07:34:46 +00005294 // If we have any leftover arguments, then there were too many arguments.
5295 // Complain and fail.
Richard Smith4a8f3512018-07-19 19:00:37 +00005296 if (ArgIdx < NumArgs) {
5297 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5298 << /*too many args*/1
5299 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5300 << Template
5301 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
5302 Diag(Template->getLocation(), diag::note_template_decl_here)
5303 << Params->getSourceRange();
5304 return true;
5305 }
Richard Trieu15b66532015-01-24 02:48:32 +00005306
5307 // No problems found with the new argument list, propagate changes back
5308 // to caller.
Richard Smith11255ec2017-01-18 19:19:22 +00005309 if (UpdateArgsWithConversions)
5310 TemplateArgs = std::move(NewArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005311
Richard Smith1fde8ec2012-09-07 02:06:42 +00005312 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00005313}
5314
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005315namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005316 class UnnamedLocalNoLinkageFinder
5317 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005318 {
5319 Sema &S;
5320 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005321
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005322 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005323
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005324 public:
5325 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5326
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005327 bool Visit(QualType T) {
Daniel Jasper5cad6852017-01-02 22:55:45 +00005328 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005329 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005330
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005331#define TYPE(Class, Parent) \
5332 bool Visit##Class##Type(const Class##Type *);
5333#define ABSTRACT_TYPE(Class, Parent) \
5334 bool Visit##Class##Type(const Class##Type *) { return false; }
5335#define NON_CANONICAL_TYPE(Class, Parent) \
5336 bool Visit##Class##Type(const Class##Type *) { return false; }
5337#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005338
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005339 bool VisitTagDecl(const TagDecl *Tag);
5340 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5341 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005342} // end anonymous namespace
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005343
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005344bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005345 return false;
5346}
5347
5348bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5349 return Visit(T->getElementType());
5350}
5351
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005352bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005353 return Visit(T->getPointeeType());
5354}
5355
5356bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005357 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005358 return Visit(T->getPointeeType());
5359}
5360
5361bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005362 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005363 return Visit(T->getPointeeType());
5364}
5365
5366bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005367 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005368 return Visit(T->getPointeeType());
5369}
5370
5371bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005372 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005373 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5374}
5375
5376bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005377 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005378 return Visit(T->getElementType());
5379}
5380
5381bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005382 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005383 return Visit(T->getElementType());
5384}
5385
5386bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005387 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005388 return Visit(T->getElementType());
5389}
5390
5391bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005392 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005393 return Visit(T->getElementType());
5394}
5395
5396bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005397 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005398 return Visit(T->getElementType());
5399}
5400
Andrew Gozillon572bbb02017-10-02 06:25:51 +00005401bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
5402 const DependentAddressSpaceType *T) {
5403 return Visit(T->getPointeeType());
5404}
5405
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005406bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5407 return Visit(T->getElementType());
5408}
5409
Erich Keanef702b022018-07-13 19:46:04 +00005410bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
5411 const DependentVectorType *T) {
5412 return Visit(T->getElementType());
5413}
5414
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005415bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5416 return Visit(T->getElementType());
5417}
5418
5419bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5420 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005421 for (const auto &A : T->param_types()) {
5422 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005423 return true;
5424 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005425
Alp Toker314cc812014-01-25 16:55:45 +00005426 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005427}
5428
5429bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5430 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00005431 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005432}
5433
5434bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5435 const UnresolvedUsingType*) {
5436 return false;
5437}
5438
5439bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5440 return false;
5441}
5442
5443bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5444 return Visit(T->getUnderlyingType());
5445}
5446
5447bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5448 return false;
5449}
5450
Alexis Hunte852b102011-05-24 22:41:36 +00005451bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5452 const UnaryTransformType*) {
5453 return false;
5454}
5455
Richard Smith30482bc2011-02-20 03:19:35 +00005456bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5457 return Visit(T->getDeducedType());
5458}
5459
Richard Smith600b5262017-01-26 20:40:47 +00005460bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5461 const DeducedTemplateSpecializationType *T) {
5462 return Visit(T->getDeducedType());
5463}
5464
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005465bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5466 return VisitTagDecl(T->getDecl());
5467}
5468
5469bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5470 return VisitTagDecl(T->getDecl());
5471}
5472
5473bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5474 const TemplateTypeParmType*) {
5475 return false;
5476}
5477
Douglas Gregorada4b792011-01-14 02:55:32 +00005478bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5479 const SubstTemplateTypeParmPackType *) {
5480 return false;
5481}
5482
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005483bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
5484 const TemplateSpecializationType*) {
5485 return false;
5486}
5487
5488bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
5489 const InjectedClassNameType* T) {
5490 return VisitTagDecl(T->getDecl());
5491}
5492
5493bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
5494 const DependentNameType* T) {
5495 return VisitNestedNameSpecifier(T->getQualifier());
5496}
5497
5498bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
5499 const DependentTemplateSpecializationType* T) {
5500 return VisitNestedNameSpecifier(T->getQualifier());
5501}
5502
Douglas Gregord2fa7662010-12-20 02:24:11 +00005503bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
5504 const PackExpansionType* T) {
5505 return Visit(T->getPattern());
5506}
5507
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005508bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5509 return false;
5510}
5511
5512bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
5513 const ObjCInterfaceType *) {
5514 return false;
5515}
5516
5517bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
5518 const ObjCObjectPointerType *) {
5519 return false;
5520}
5521
Eli Friedman0dfb8892011-10-06 23:00:33 +00005522bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
5523 return Visit(T->getValueType());
5524}
5525
Xiuli Pan9c14e282016-01-09 12:53:17 +00005526bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
5527 return false;
5528}
5529
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005530bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
5531 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005532 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005533 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00005534 diag::warn_cxx98_compat_template_arg_local_type :
5535 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005536 << S.Context.getTypeDeclType(Tag) << SR;
5537 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005538 }
5539
John McCall5ea95772013-03-09 00:54:27 +00005540 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005541 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005542 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00005543 diag::warn_cxx98_compat_template_arg_unnamed_type :
5544 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005545 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
5546 return true;
5547 }
5548
5549 return false;
5550}
5551
5552bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5553 NestedNameSpecifier *NNS) {
5554 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5555 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005556
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005557 switch (NNS->getKind()) {
5558 case NestedNameSpecifier::Identifier:
5559 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005560 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005561 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00005562 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005563 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005564
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005565 case NestedNameSpecifier::TypeSpec:
5566 case NestedNameSpecifier::TypeSpecWithTemplate:
5567 return Visit(QualType(NNS->getAsType(), 0));
5568 }
David Blaikie8a40f702012-01-17 06:56:22 +00005569 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005570}
5571
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005572/// Check a template argument against its corresponding
Douglas Gregord32e0282009-02-09 23:23:08 +00005573/// template type parameter.
5574///
5575/// This routine implements the semantics of C++ [temp.arg.type]. It
5576/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005577bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00005578 TypeSourceInfo *ArgInfo) {
5579 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00005580 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00005581 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00005582
5583 if (Arg->isVariablyModifiedType()) {
5584 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005585 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005586 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00005587 }
5588
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005589 // C++03 [temp.arg.type]p2:
5590 // A local type, a type with no linkage, an unnamed type or a type
5591 // compounded from any of these types shall not be used as a
5592 // template-argument for a template type-parameter.
5593 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00005594 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005595 // a warning.
Daniel Jasper5cad6852017-01-02 22:55:45 +00005596 if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005597 UnnamedLocalNoLinkageFinder Finder(*this, SR);
5598 (void)Finder.Visit(Context.getCanonicalType(Arg));
5599 }
5600
Douglas Gregord32e0282009-02-09 23:23:08 +00005601 return false;
5602}
5603
Douglas Gregor20fdef32012-04-10 17:08:25 +00005604enum NullPointerValueKind {
5605 NPV_NotNullPointer,
5606 NPV_NullPointer,
5607 NPV_Error
5608};
5609
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005610/// Determine whether the given template argument is a null pointer
Douglas Gregor20fdef32012-04-10 17:08:25 +00005611/// value of the appropriate type.
5612static NullPointerValueKind
5613isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
Reid Klecknercd016d82017-07-07 22:04:29 +00005614 QualType ParamType, Expr *Arg,
5615 Decl *Entity = nullptr) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00005616 if (Arg->isValueDependent() || Arg->isTypeDependent())
5617 return NPV_NotNullPointer;
David Majnemer69c3ddc2015-09-11 20:18:09 +00005618
Reid Klecknercd016d82017-07-07 22:04:29 +00005619 // dllimport'd entities aren't constant but are available inside of template
5620 // arguments.
5621 if (Entity && Entity->hasAttr<DLLImportAttr>())
5622 return NPV_NotNullPointer;
5623
Richard Smithdb0ac552015-12-18 22:40:25 +00005624 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
David Majnemerb54368c2015-09-11 20:55:29 +00005625 llvm_unreachable(
5626 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
David Majnemer69c3ddc2015-09-11 20:18:09 +00005627
David Majnemer5c734ad2014-08-14 00:49:23 +00005628 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00005629 return NPV_NotNullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005630
Douglas Gregor20fdef32012-04-10 17:08:25 +00005631 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00005632 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
5633 if (ArgRV.isInvalid())
5634 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005635 Arg = ArgRV.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005636
Douglas Gregor20fdef32012-04-10 17:08:25 +00005637 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005638 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00005639 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005640 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00005641 EvalResult.HasSideEffects) {
5642 SourceLocation DiagLoc = Arg->getExprLoc();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005643
Douglas Gregor350880c2012-04-10 19:03:30 +00005644 // If our only note is the usual "invalid subexpression" note, just point
5645 // the caret at its location rather than producing an essentially
5646 // redundant note.
5647 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5648 diag::note_invalid_subexpr_in_const_expr) {
5649 DiagLoc = Notes[0].first;
5650 Notes.clear();
5651 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005652
Douglas Gregor350880c2012-04-10 19:03:30 +00005653 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5654 << Arg->getType() << Arg->getSourceRange();
5655 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5656 S.Diag(Notes[I].first, Notes[I].second);
Simon Pilgrim6905d222016-12-30 22:55:33 +00005657
Douglas Gregor350880c2012-04-10 19:03:30 +00005658 S.Diag(Param->getLocation(), diag::note_template_param_here);
5659 return NPV_Error;
5660 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005661
Douglas Gregor20fdef32012-04-10 17:08:25 +00005662 // C++11 [temp.arg.nontype]p1:
5663 // - an address constant expression of type std::nullptr_t
5664 if (Arg->getType()->isNullPtrType())
5665 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005666
Douglas Gregor20fdef32012-04-10 17:08:25 +00005667 // - a constant expression that evaluates to a null pointer value (4.10); or
5668 // - a constant expression that evaluates to a null member pointer value
5669 // (4.11); or
5670 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
5671 (EvalResult.Val.isMemberPointer() &&
5672 !EvalResult.Val.getMemberPointerDecl())) {
5673 // If our expression has an appropriate type, we've succeeded.
5674 bool ObjCLifetimeConversion;
5675 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5676 S.IsQualificationConversion(Arg->getType(), ParamType, false,
5677 ObjCLifetimeConversion))
5678 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005679
Douglas Gregor20fdef32012-04-10 17:08:25 +00005680 // The types didn't match, but we know we got a null pointer; complain,
5681 // then recover as if the types were correct.
5682 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
5683 << Arg->getType() << ParamType << Arg->getSourceRange();
5684 S.Diag(Param->getLocation(), diag::note_template_param_here);
5685 return NPV_NullPointer;
5686 }
5687
5688 // If we don't have a null pointer value, but we do have a NULL pointer
5689 // constant, suggest a cast to the appropriate type.
5690 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
5691 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
5692 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005693 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005694 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getEndLoc()),
Alp Tokerb6cc5922014-05-03 03:45:55 +00005695 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00005696 S.Diag(Param->getLocation(), diag::note_template_param_here);
5697 return NPV_NullPointer;
5698 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005699
Douglas Gregor20fdef32012-04-10 17:08:25 +00005700 // FIXME: If we ever want to support general, address-constant expressions
5701 // as non-type template arguments, we should return the ExprResult here to
5702 // be interpreted by the caller.
5703 return NPV_NotNullPointer;
5704}
5705
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005706/// Checks whether the given template argument is compatible with its
David Majnemer61c39a12013-08-23 05:39:39 +00005707/// template parameter.
5708static bool CheckTemplateArgumentIsCompatibleWithParameter(
5709 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
5710 Expr *Arg, QualType ArgType) {
5711 bool ObjCLifetimeConversion;
5712 if (ParamType->isPointerType() &&
5713 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
5714 S.IsQualificationConversion(ArgType, ParamType, false,
5715 ObjCLifetimeConversion)) {
5716 // For pointer-to-object types, qualification conversions are
5717 // permitted.
5718 } else {
5719 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
5720 if (!ParamRef->getPointeeType()->isFunctionType()) {
5721 // C++ [temp.arg.nontype]p5b3:
5722 // For a non-type template-parameter of type reference to
5723 // object, no conversions apply. The type referred to by the
5724 // reference may be more cv-qualified than the (otherwise
5725 // identical) type of the template- argument. The
5726 // template-parameter is bound directly to the
5727 // template-argument, which shall be an lvalue.
5728
5729 // FIXME: Other qualifiers?
5730 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
5731 unsigned ArgQuals = ArgType.getCVRQualifiers();
5732
5733 if ((ParamQuals | ArgQuals) != ParamQuals) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005734 S.Diag(Arg->getBeginLoc(),
David Majnemer61c39a12013-08-23 05:39:39 +00005735 diag::err_template_arg_ref_bind_ignores_quals)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005736 << ParamType << Arg->getType() << Arg->getSourceRange();
David Majnemer61c39a12013-08-23 05:39:39 +00005737 S.Diag(Param->getLocation(), diag::note_template_param_here);
5738 return true;
5739 }
5740 }
5741 }
5742
5743 // At this point, the template argument refers to an object or
5744 // function with external linkage. We now need to check whether the
5745 // argument and parameter types are compatible.
5746 if (!S.Context.hasSameUnqualifiedType(ArgType,
5747 ParamType.getNonReferenceType())) {
5748 // We can't perform this conversion or binding.
5749 if (ParamType->isReferenceType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005750 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
5751 << ParamType << ArgIn->getType() << Arg->getSourceRange();
David Majnemer61c39a12013-08-23 05:39:39 +00005752 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005753 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
5754 << ArgIn->getType() << ParamType << Arg->getSourceRange();
David Majnemer61c39a12013-08-23 05:39:39 +00005755 S.Diag(Param->getLocation(), diag::note_template_param_here);
5756 return true;
5757 }
5758 }
5759
5760 return false;
5761}
5762
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005763/// Checks whether the given template argument is the address
Douglas Gregorccb07762009-02-11 19:52:55 +00005764/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005765static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00005766CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
5767 NonTypeTemplateParmDecl *Param,
5768 QualType ParamType,
5769 Expr *ArgIn,
5770 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005771 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005772 Expr *Arg = ArgIn;
5773 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00005774
Douglas Gregorb242683d2010-04-01 18:32:35 +00005775 bool AddressTaken = false;
5776 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00005777 if (S.getLangOpts().MicrosoftExt) {
5778 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
5779 // dereference and address-of operators.
5780 Arg = Arg->IgnoreParenCasts();
5781
5782 bool ExtWarnMSTemplateArg = false;
5783 UnaryOperatorKind FirstOpKind;
5784 SourceLocation FirstOpLoc;
5785 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5786 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
5787 if (UnOpKind == UO_Deref)
5788 ExtWarnMSTemplateArg = true;
5789 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
5790 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
5791 if (!AddrOpLoc.isValid()) {
5792 FirstOpKind = UnOpKind;
5793 FirstOpLoc = UnOp->getOperatorLoc();
5794 }
5795 } else
5796 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005797 }
David Majnemer61c39a12013-08-23 05:39:39 +00005798 if (FirstOpLoc.isValid()) {
5799 if (ExtWarnMSTemplateArg)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005800 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
5801 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00005802
David Majnemer61c39a12013-08-23 05:39:39 +00005803 if (FirstOpKind == UO_AddrOf)
5804 AddressTaken = true;
5805 else if (Arg->getType()->isPointerType()) {
5806 // We cannot let pointers get dereferenced here, that is obviously not a
5807 // constant expression.
5808 assert(FirstOpKind == UO_Deref);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005809 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
5810 << Arg->getSourceRange();
David Majnemer61c39a12013-08-23 05:39:39 +00005811 }
5812 }
5813 } else {
5814 // See through any implicit casts we added to fix the type.
5815 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00005816
David Majnemer61c39a12013-08-23 05:39:39 +00005817 // C++ [temp.arg.nontype]p1:
5818 //
5819 // A template-argument for a non-type, non-template
5820 // template-parameter shall be one of: [...]
5821 //
5822 // -- the address of an object or function with external
5823 // linkage, including function templates and function
5824 // template-ids but excluding non-static class members,
5825 // expressed as & id-expression where the & is optional if
5826 // the name refers to a function or array, or if the
5827 // corresponding template-parameter is a reference; or
5828
5829 // In C++98/03 mode, give an extension warning on any extra parentheses.
5830 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5831 bool ExtraParens = false;
5832 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5833 if (!Invalid && !ExtraParens) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005834 S.Diag(Arg->getBeginLoc(),
David Majnemer61c39a12013-08-23 05:39:39 +00005835 S.getLangOpts().CPlusPlus11
5836 ? diag::warn_cxx98_compat_template_arg_extra_parens
5837 : diag::ext_template_arg_extra_parens)
5838 << Arg->getSourceRange();
5839 ExtraParens = true;
5840 }
5841
5842 Arg = Parens->getSubExpr();
5843 }
5844
5845 while (SubstNonTypeTemplateParmExpr *subst =
5846 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5847 Arg = subst->getReplacement()->IgnoreImpCasts();
5848
5849 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5850 if (UnOp->getOpcode() == UO_AddrOf) {
5851 Arg = UnOp->getSubExpr();
5852 AddressTaken = true;
5853 AddrOpLoc = UnOp->getOperatorLoc();
5854 }
5855 }
5856
5857 while (SubstNonTypeTemplateParmExpr *subst =
5858 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5859 Arg = subst->getReplacement()->IgnoreImpCasts();
5860 }
John McCall7c454bb2011-07-15 05:09:51 +00005861
David Majnemer07910d62014-06-26 07:48:46 +00005862 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
5863 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5864
5865 // If our parameter has pointer type, check for a null template value.
5866 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
Reid Klecknercd016d82017-07-07 22:04:29 +00005867 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
5868 Entity)) {
David Majnemer07910d62014-06-26 07:48:46 +00005869 case NPV_NullPointer:
5870 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005871 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5872 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00005873 return false;
5874
5875 case NPV_Error:
5876 return true;
5877
5878 case NPV_NotNullPointer:
5879 break;
5880 }
5881 }
5882
Chandler Carruth724a8a12010-01-31 10:01:20 +00005883 // Stop checking the precise nature of the argument if it is value dependent,
5884 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00005885 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005886 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00005887 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005888 }
David Majnemer61c39a12013-08-23 05:39:39 +00005889
5890 if (isa<CXXUuidofExpr>(Arg)) {
5891 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
5892 ArgIn, Arg, ArgType))
5893 return true;
5894
5895 Converted = TemplateArgument(ArgIn);
5896 return false;
5897 }
5898
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005899 if (!DRE) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005900 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
5901 << Arg->getSourceRange();
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005902 S.Diag(Param->getLocation(), diag::note_template_param_here);
5903 return true;
5904 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00005905
Douglas Gregorccb07762009-02-11 19:52:55 +00005906 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00005907 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005908 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
5909 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005910 S.Diag(Param->getLocation(), diag::note_template_param_here);
5911 return true;
5912 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005913
5914 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00005915 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005916 if (!Method->isStatic()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005917 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
5918 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005919 S.Diag(Param->getLocation(), diag::note_template_param_here);
5920 return true;
5921 }
Richard Smith9380e0e2012-04-04 21:11:30 +00005922 }
Mike Stump11289f42009-09-09 15:08:12 +00005923
Richard Smith9380e0e2012-04-04 21:11:30 +00005924 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
5925 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00005926
Richard Smith9380e0e2012-04-04 21:11:30 +00005927 // A non-type template argument must refer to an object or function.
5928 if (!Func && !Var) {
5929 // We found something, but we don't know specifically what it is.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005930 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
5931 << Arg->getSourceRange();
Richard Smith9380e0e2012-04-04 21:11:30 +00005932 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
5933 return true;
5934 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005935
Richard Smith9380e0e2012-04-04 21:11:30 +00005936 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00005937 if (Entity->getFormalLinkage() == InternalLinkage) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005938 S.Diag(Arg->getBeginLoc(),
5939 S.getLangOpts().CPlusPlus11
5940 ? diag::warn_cxx98_compat_template_arg_object_internal
5941 : diag::ext_template_arg_object_internal)
5942 << !Func << Entity << Arg->getSourceRange();
Richard Smith9380e0e2012-04-04 21:11:30 +00005943 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5944 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00005945 } else if (!Entity->hasLinkage()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005946 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
5947 << !Func << Entity << Arg->getSourceRange();
Richard Smith9380e0e2012-04-04 21:11:30 +00005948 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5949 << !Func;
5950 return true;
5951 }
5952
5953 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005954 // If the template parameter has pointer type, the function decays.
5955 if (ParamType->isPointerType() && !AddressTaken)
5956 ArgType = S.Context.getPointerType(Func->getType());
5957 else if (AddressTaken && ParamType->isReferenceType()) {
5958 // If we originally had an address-of operator, but the
5959 // parameter has reference type, complain and (if things look
5960 // like they will work) drop the address-of operator.
5961 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
5962 ParamType.getNonReferenceType())) {
5963 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5964 << ParamType;
5965 S.Diag(Param->getLocation(), diag::note_template_param_here);
5966 return true;
5967 }
5968
5969 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5970 << ParamType
5971 << FixItHint::CreateRemoval(AddrOpLoc);
5972 S.Diag(Param->getLocation(), diag::note_template_param_here);
5973
5974 ArgType = Func->getType();
5975 }
Richard Smith9380e0e2012-04-04 21:11:30 +00005976 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005977 // A value of reference type is not an object.
5978 if (Var->getType()->isReferenceType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005979 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
5980 << Var->getType() << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005981 S.Diag(Param->getLocation(), diag::note_template_param_here);
5982 return true;
5983 }
5984
Richard Smith9380e0e2012-04-04 21:11:30 +00005985 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00005986 if (Var->getTLSKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005987 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
5988 << Arg->getSourceRange();
Richard Smith9380e0e2012-04-04 21:11:30 +00005989 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
5990 return true;
5991 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00005992
5993 // If the template parameter has pointer type, we must have taken
5994 // the address of this object.
5995 if (ParamType->isReferenceType()) {
5996 if (AddressTaken) {
5997 // If we originally had an address-of operator, but the
5998 // parameter has reference type, complain and (if things look
5999 // like they will work) drop the address-of operator.
6000 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
6001 ParamType.getNonReferenceType())) {
6002 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6003 << ParamType;
6004 S.Diag(Param->getLocation(), diag::note_template_param_here);
6005 return true;
6006 }
6007
6008 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6009 << ParamType
6010 << FixItHint::CreateRemoval(AddrOpLoc);
6011 S.Diag(Param->getLocation(), diag::note_template_param_here);
6012
6013 ArgType = Var->getType();
6014 }
6015 } else if (!AddressTaken && ParamType->isPointerType()) {
6016 if (Var->getType()->isArrayType()) {
6017 // Array-to-pointer decay.
6018 ArgType = S.Context.getArrayDecayedType(Var->getType());
6019 } else {
6020 // If the template parameter has pointer type but the address of
6021 // this object was not taken, complain and (possibly) recover by
6022 // taking the address of the entity.
6023 ArgType = S.Context.getPointerType(Var->getType());
6024 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006025 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6026 << ParamType;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006027 S.Diag(Param->getLocation(), diag::note_template_param_here);
6028 return true;
6029 }
6030
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006031 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6032 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
Douglas Gregorb242683d2010-04-01 18:32:35 +00006033
6034 S.Diag(Param->getLocation(), diag::note_template_param_here);
6035 }
6036 }
Douglas Gregorccb07762009-02-11 19:52:55 +00006037 }
Mike Stump11289f42009-09-09 15:08:12 +00006038
David Majnemer61c39a12013-08-23 05:39:39 +00006039 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6040 Arg, ArgType))
6041 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006042
6043 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00006044 Converted =
6045 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006046 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00006047 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00006048}
6049
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006050/// Checks whether the given template argument is a pointer to
Douglas Gregorccb07762009-02-11 19:52:55 +00006051/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00006052static bool CheckTemplateArgumentPointerToMember(Sema &S,
6053 NonTypeTemplateParmDecl *Param,
6054 QualType ParamType,
6055 Expr *&ResultArg,
6056 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00006057 bool Invalid = false;
6058
Douglas Gregor20fdef32012-04-10 17:08:25 +00006059 Expr *Arg = ResultArg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006060 bool ObjCLifetimeConversion;
Douglas Gregorccb07762009-02-11 19:52:55 +00006061
6062 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00006063 //
Douglas Gregorccb07762009-02-11 19:52:55 +00006064 // A template-argument for a non-type, non-template
6065 // template-parameter shall be one of: [...]
6066 //
6067 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00006068 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00006069
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00006070 // In C++98/03 mode, give an extension warning on any extra parentheses.
6071 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6072 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00006073 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00006074 if (!Invalid && !ExtraParens) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006075 S.Diag(Arg->getBeginLoc(),
6076 S.getLangOpts().CPlusPlus11
6077 ? diag::warn_cxx98_compat_template_arg_extra_parens
6078 : diag::ext_template_arg_extra_parens)
6079 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00006080 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00006081 }
6082
6083 Arg = Parens->getSubExpr();
6084 }
6085
John McCall7c454bb2011-07-15 05:09:51 +00006086 while (SubstNonTypeTemplateParmExpr *subst =
6087 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6088 Arg = subst->getReplacement()->IgnoreImpCasts();
6089
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006090 // A pointer-to-member constant written &Class::member.
6091 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00006092 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00006093 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
6094 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00006095 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00006096 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006097 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006098 // A constant of pointer-to-member type.
6099 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00006100 ValueDecl *VD = DRE->getDecl();
6101 if (VD->getType()->isMemberPointerType()) {
6102 if (isa<NonTypeTemplateParmDecl>(VD)) {
6103 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6104 Converted = TemplateArgument(Arg);
6105 } else {
6106 VD = cast<ValueDecl>(VD->getCanonicalDecl());
6107 Converted = TemplateArgument(VD, ParamType);
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006108 }
George Burgess IV00f70bd2018-03-01 05:43:23 +00006109 return Invalid;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006110 }
6111 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006112
Craig Topperc3ec1492014-05-26 06:22:03 +00006113 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006114 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006115
Reid Klecknercd016d82017-07-07 22:04:29 +00006116 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6117
6118 // Check for a null pointer value.
6119 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
6120 Entity)) {
6121 case NPV_Error:
6122 return true;
6123 case NPV_NullPointer:
6124 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6125 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
6126 /*isNullPtr*/true);
6127 return false;
6128 case NPV_NotNullPointer:
6129 break;
6130 }
6131
6132 if (S.IsQualificationConversion(ResultArg->getType(),
6133 ParamType.getNonReferenceType(), false,
6134 ObjCLifetimeConversion)) {
6135 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
6136 ResultArg->getValueKind())
6137 .get();
6138 } else if (!S.Context.hasSameUnqualifiedType(
6139 ResultArg->getType(), ParamType.getNonReferenceType())) {
6140 // We can't perform this conversion.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006141 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
Reid Klecknercd016d82017-07-07 22:04:29 +00006142 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
6143 S.Diag(Param->getLocation(), diag::note_template_param_here);
6144 return true;
6145 }
6146
Douglas Gregorccb07762009-02-11 19:52:55 +00006147 if (!DRE)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006148 return S.Diag(Arg->getBeginLoc(),
Douglas Gregor20fdef32012-04-10 17:08:25 +00006149 diag::err_template_arg_not_pointer_to_member_form)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006150 << Arg->getSourceRange();
Douglas Gregorccb07762009-02-11 19:52:55 +00006151
David Majnemer3ac84e62013-10-22 21:56:38 +00006152 if (isa<FieldDecl>(DRE->getDecl()) ||
6153 isa<IndirectFieldDecl>(DRE->getDecl()) ||
6154 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00006155 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00006156 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00006157 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
6158 "Only non-static member pointers can make it here");
6159
6160 // Okay: this is the address of a non-static member, and therefore
6161 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00006162 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00006163 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00006164 } else {
6165 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00006166 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00006167 }
Douglas Gregorccb07762009-02-11 19:52:55 +00006168 return Invalid;
6169 }
6170
6171 // We found something else, but we don't know specifically what it is.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006172 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
6173 << Arg->getSourceRange();
Douglas Gregor20fdef32012-04-10 17:08:25 +00006174 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00006175 return true;
6176}
6177
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006178/// Check a template argument against its corresponding
Douglas Gregord32e0282009-02-09 23:23:08 +00006179/// non-type template parameter.
6180///
Douglas Gregor463421d2009-03-03 04:44:36 +00006181/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00006182/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00006183/// returns the converted template argument. \p ParamType is the
6184/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00006185ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00006186 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00006187 TemplateArgument &Converted,
6188 CheckTemplateArgumentKind CTAK) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006189 SourceLocation StartLoc = Arg->getBeginLoc();
Douglas Gregorc40290e2009-03-09 23:48:35 +00006190
Richard Smith5f274382016-09-28 23:55:27 +00006191 // If the parameter type somehow involves auto, deduce the type now.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00006192 if (getLangOpts().CPlusPlus17 && ParamType->isUndeducedType()) {
Richard Smith4ae5ec82017-02-22 20:01:55 +00006193 // During template argument deduction, we allow 'decltype(auto)' to
6194 // match an arbitrary dependent argument.
6195 // FIXME: The language rules don't say what happens in this case.
6196 // FIXME: We get an opaque dependent type out of decltype(auto) if the
6197 // expression is merely instantiation-dependent; is this enough?
6198 if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
6199 auto *AT = dyn_cast<AutoType>(ParamType);
6200 if (AT && AT->isDecltypeAuto()) {
6201 Converted = TemplateArgument(Arg);
6202 return Arg;
6203 }
6204 }
6205
Richard Smith87d263e2016-12-25 08:05:23 +00006206 // When checking a deduced template argument, deduce from its type even if
6207 // the type is dependent, in order to check the types of non-type template
6208 // arguments line up properly in partial ordering.
6209 Optional<unsigned> Depth;
6210 if (CTAK != CTAK_Specified)
6211 Depth = Param->getDepth() + 1;
Richard Smith5f274382016-09-28 23:55:27 +00006212 if (DeduceAutoType(
6213 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
Richard Smith87d263e2016-12-25 08:05:23 +00006214 Arg, ParamType, Depth) == DAR_Failed) {
Richard Smith5f274382016-09-28 23:55:27 +00006215 Diag(Arg->getExprLoc(),
6216 diag::err_non_type_template_parm_type_deduction_failure)
6217 << Param->getDeclName() << Param->getType() << Arg->getType()
6218 << Arg->getSourceRange();
6219 Diag(Param->getLocation(), diag::note_template_param_here);
6220 return ExprError();
6221 }
6222 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
6223 // an error. The error message normally references the parameter
6224 // declaration, but here we'll pass the argument location because that's
6225 // where the parameter type is deduced.
6226 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
6227 if (ParamType.isNull()) {
6228 Diag(Param->getLocation(), diag::note_template_param_here);
6229 return ExprError();
6230 }
6231 }
6232
Richard Smithd663fdd2014-12-17 20:42:37 +00006233 // We should have already dropped all cv-qualifiers by now.
6234 assert(!ParamType.hasQualifiers() &&
6235 "non-type template parameter type cannot be qualified");
6236
6237 if (CTAK == CTAK_Deduced &&
Richard Smithd92eddf2016-12-27 06:14:37 +00006238 !Context.hasSameType(ParamType.getNonLValueExprType(Context),
Richard Smith0e617ec2016-12-27 07:56:27 +00006239 Arg->getType())) {
Richard Smith957fbf12017-01-17 02:14:37 +00006240 // FIXME: If either type is dependent, we skip the check. This isn't
6241 // correct, since during deduction we're supposed to have replaced each
6242 // template parameter with some unique (non-dependent) placeholder.
6243 // FIXME: If the argument type contains 'auto', we carry on and fail the
6244 // type check in order to force specific types to be more specialized than
6245 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
6246 // work.
6247 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
6248 !Arg->getType()->getContainedAutoType()) {
6249 Converted = TemplateArgument(Arg);
6250 return Arg;
6251 }
6252 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
6253 // we should actually be checking the type of the template argument in P,
6254 // not the type of the template argument deduced from A, against the
6255 // template parameter type.
Richard Smithd663fdd2014-12-17 20:42:37 +00006256 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
Richard Smith0e617ec2016-12-27 07:56:27 +00006257 << Arg->getType()
Richard Smithd663fdd2014-12-17 20:42:37 +00006258 << ParamType.getUnqualifiedType();
6259 Diag(Param->getLocation(), diag::note_template_param_here);
6260 return ExprError();
6261 }
6262
Richard Smith87d263e2016-12-25 08:05:23 +00006263 // If either the parameter has a dependent type or the argument is
6264 // type-dependent, there's nothing we can check now.
6265 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
6266 // FIXME: Produce a cloned, canonical expression?
6267 Converted = TemplateArgument(Arg);
6268 return Arg;
6269 }
6270
Richard Smithe5945872017-01-06 22:52:53 +00006271 // The initialization of the parameter from the argument is
6272 // a constant-evaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006273 EnterExpressionEvaluationContext ConstantEvaluated(
6274 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Richard Smithe5945872017-01-06 22:52:53 +00006275
Aaron Ballmanc351fba2017-12-04 20:27:34 +00006276 if (getLangOpts().CPlusPlus17) {
6277 // C++17 [temp.arg.nontype]p1:
Richard Smith410cc892014-11-26 03:26:53 +00006278 // A template-argument for a non-type template parameter shall be
6279 // a converted constant expression of the type of the template-parameter.
6280 APValue Value;
6281 ExprResult ArgResult = CheckConvertedConstantExpression(
6282 Arg, ParamType, Value, CCEK_TemplateArg);
6283 if (ArgResult.isInvalid())
6284 return ExprError();
6285
Richard Smith52e624f2016-12-21 21:42:57 +00006286 // For a value-dependent argument, CheckConvertedConstantExpression is
6287 // permitted (and expected) to be unable to determine a value.
6288 if (ArgResult.get()->isValueDependent()) {
Richard Smith01bfa682016-12-27 02:02:09 +00006289 Converted = TemplateArgument(ArgResult.get());
6290 return ArgResult;
Richard Smith52e624f2016-12-21 21:42:57 +00006291 }
6292
Richard Smithd663fdd2014-12-17 20:42:37 +00006293 QualType CanonParamType = Context.getCanonicalType(ParamType);
6294
Richard Smith410cc892014-11-26 03:26:53 +00006295 // Convert the APValue to a TemplateArgument.
6296 switch (Value.getKind()) {
6297 case APValue::Uninitialized:
6298 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00006299 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00006300 break;
6301 case APValue::Int:
6302 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00006303 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00006304 break;
6305 case APValue::MemberPointer: {
6306 assert(ParamType->isMemberPointerType());
6307
6308 // FIXME: We need TemplateArgument representation and mangling for these.
6309 if (!Value.getMemberPointerPath().empty()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006310 Diag(Arg->getBeginLoc(),
Richard Smith410cc892014-11-26 03:26:53 +00006311 diag::err_template_arg_member_ptr_base_derived_not_supported)
6312 << Value.getMemberPointerDecl() << ParamType
6313 << Arg->getSourceRange();
6314 return ExprError();
6315 }
6316
6317 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00006318 Converted = VD ? TemplateArgument(VD, CanonParamType)
6319 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00006320 break;
6321 }
6322 case APValue::LValue: {
6323 // For a non-type template-parameter of pointer or reference type,
6324 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00006325 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
6326 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00006327 // -- a temporary object
6328 // -- a string literal
6329 // -- the result of a typeid expression, or
Eric Christopher0d2c56a2017-03-31 01:45:39 +00006330 // -- a predefined __func__ variable
Richard Smith410cc892014-11-26 03:26:53 +00006331 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
6332 if (isa<CXXUuidofExpr>(E)) {
Bill Wendlingff573072019-01-27 07:24:03 +00006333 Converted = TemplateArgument(ArgResult.get()->IgnoreImpCasts());
Richard Smith410cc892014-11-26 03:26:53 +00006334 break;
6335 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006336 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6337 << Arg->getSourceRange();
Richard Smith410cc892014-11-26 03:26:53 +00006338 return ExprError();
6339 }
6340 auto *VD = const_cast<ValueDecl *>(
6341 Value.getLValueBase().dyn_cast<const ValueDecl *>());
6342 // -- a subobject
6343 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
6344 VD && VD->getType()->isArrayType() &&
6345 Value.getLValuePath()[0].ArrayIndex == 0 &&
6346 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
6347 // Per defect report (no number yet):
6348 // ... other than a pointer to the first element of a complete array
6349 // object.
6350 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
6351 Value.isLValueOnePastTheEnd()) {
6352 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
6353 << Value.getAsString(Context, ParamType);
6354 return ExprError();
6355 }
Richard Smithd663fdd2014-12-17 20:42:37 +00006356 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00006357 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00006358 assert((!VD || !ParamType->isNullPtrType()) &&
6359 "non-null value of type nullptr_t?");
6360 Converted = VD ? TemplateArgument(VD, CanonParamType)
6361 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00006362 break;
6363 }
6364 case APValue::AddrLabelDiff:
6365 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
Leonard Chan86285d22019-01-16 18:53:05 +00006366 case APValue::FixedPoint:
Richard Smith410cc892014-11-26 03:26:53 +00006367 case APValue::Float:
6368 case APValue::ComplexInt:
6369 case APValue::ComplexFloat:
6370 case APValue::Vector:
6371 case APValue::Array:
6372 case APValue::Struct:
6373 case APValue::Union:
6374 llvm_unreachable("invalid kind for template argument");
6375 }
6376
6377 return ArgResult.get();
6378 }
6379
Douglas Gregor86560402009-02-10 23:36:10 +00006380 // C++ [temp.arg.nontype]p5:
6381 // The following conversions are performed on each expression used
6382 // as a non-type template-argument. If a non-type
6383 // template-argument cannot be converted to the type of the
6384 // corresponding template-parameter then the program is
6385 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00006386 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00006387 // C++11:
6388 // -- for a non-type template-parameter of integral or
6389 // enumeration type, conversions permitted in a converted
6390 // constant expression are applied.
6391 //
6392 // C++98:
6393 // -- for a non-type template-parameter of integral or
6394 // enumeration type, integral promotions (4.5) and integral
6395 // conversions (4.7) are applied.
6396
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006397 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00006398 // C++ [temp.arg.nontype]p1:
6399 // A template-argument for a non-type, non-template template-parameter
6400 // shall be one of:
6401 //
6402 // -- for a non-type template-parameter of integral or enumeration
6403 // type, a converted constant expression of the type of the
6404 // template-parameter; or
6405 llvm::APSInt Value;
6406 ExprResult ArgResult =
6407 CheckConvertedConstantExpression(Arg, ParamType, Value,
6408 CCEK_TemplateArg);
6409 if (ArgResult.isInvalid())
6410 return ExprError();
6411
Richard Smith01bfa682016-12-27 02:02:09 +00006412 // We can't check arbitrary value-dependent arguments.
6413 if (ArgResult.get()->isValueDependent()) {
6414 Converted = TemplateArgument(ArgResult.get());
6415 return ArgResult;
6416 }
6417
Richard Smithf8379a02012-01-18 23:55:52 +00006418 // Widen the argument value to sizeof(parameter type). This is almost
6419 // always a no-op, except when the parameter type is bool. In
6420 // that case, this may extend the argument from 1 bit to 8 bits.
6421 QualType IntegerType = ParamType;
6422 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6423 IntegerType = Enum->getDecl()->getIntegerType();
6424 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
6425
Benjamin Kramer6003ad52012-06-07 15:09:51 +00006426 Converted = TemplateArgument(Context, Value,
6427 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00006428 return ArgResult;
6429 }
6430
Richard Smith08b12f12011-10-27 22:11:44 +00006431 ExprResult ArgResult = DefaultLvalueConversion(Arg);
6432 if (ArgResult.isInvalid())
6433 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006434 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00006435
6436 QualType ArgType = Arg->getType();
6437
Douglas Gregor86560402009-02-10 23:36:10 +00006438 // C++ [temp.arg.nontype]p1:
6439 // A template-argument for a non-type, non-template
6440 // template-parameter shall be one of:
6441 //
6442 // -- an integral constant-expression of integral or enumeration
6443 // type; or
6444 // -- the name of a non-type template-parameter; or
Douglas Gregor264ec4f2009-02-17 01:05:43 +00006445 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00006446 if (!ArgType->isIntegralOrEnumerationType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006447 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
6448 << ArgType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00006449 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00006450 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00006451 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00006452 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
6453 QualType T;
Simon Pilgrim6905d222016-12-30 22:55:33 +00006454
Douglas Gregore2b37442012-05-04 22:38:52 +00006455 public:
6456 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00006457
6458 void diagnoseNotICE(Sema &S, SourceLocation Loc,
6459 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00006460 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
6461 }
6462 } Diagnoser(ArgType);
6463
6464 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006465 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00006466 if (!Arg)
6467 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00006468 }
6469
Richard Smithd663fdd2014-12-17 20:42:37 +00006470 // From here on out, all we care about is the unqualified form
6471 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006472 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00006473
6474 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00006475 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00006476 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00006477 } else if (ParamType->isBooleanType()) {
6478 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006479 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00006480 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
6481 !ParamType->isEnumeralType()) {
6482 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006483 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00006484 } else {
6485 // We can't perform this conversion.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006486 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6487 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00006488 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00006489 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00006490 }
6491
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006492 // Add the value of this argument to the list of converted
6493 // arguments. We use the bitwidth and signedness of the template
6494 // parameter.
6495 if (Arg->isValueDependent()) {
6496 // The argument is value-dependent. Create a new
6497 // TemplateArgument with the converted expression.
6498 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006499 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006500 }
6501
Douglas Gregor52aba872009-03-14 00:20:21 +00006502 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00006503 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00006504 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00006505
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006506 if (ParamType->isBooleanType()) {
6507 // Value must be zero or one.
6508 Value = Value != 0;
6509 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6510 if (Value.getBitWidth() != AllowedBits)
6511 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006512 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006513 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006514 llvm::APSInt OldValue = Value;
Simon Pilgrim6905d222016-12-30 22:55:33 +00006515
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006516 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006517 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00006518 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00006519 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006520 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006521 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Simon Pilgrim6905d222016-12-30 22:55:33 +00006522
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006523 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006524 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006525 && (OldValue.isSigned() && OldValue.isNegative())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006526 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
6527 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6528 << Arg->getSourceRange();
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006529 Diag(Param->getLocation(), diag::note_template_param_here);
6530 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006531
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006532 // Complain if we overflowed the template parameter's type.
6533 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006534 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006535 RequiredBits = OldValue.getActiveBits();
6536 else if (OldValue.isUnsigned())
6537 RequiredBits = OldValue.getActiveBits() + 1;
6538 else
6539 RequiredBits = OldValue.getMinSignedBits();
6540 if (RequiredBits > AllowedBits) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006541 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
6542 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6543 << Arg->getSourceRange();
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006544 Diag(Param->getLocation(), diag::note_template_param_here);
6545 }
Douglas Gregor52aba872009-03-14 00:20:21 +00006546 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00006547
Benjamin Kramer6003ad52012-06-07 15:09:51 +00006548 Converted = TemplateArgument(Context, Value,
Simon Pilgrim6905d222016-12-30 22:55:33 +00006549 ParamType->isEnumeralType()
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00006550 ? Context.getCanonicalType(ParamType)
6551 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006552 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00006553 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006554
Richard Smith08b12f12011-10-27 22:11:44 +00006555 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00006556 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
6557
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006558 // Handle pointer-to-function, reference-to-function, and
6559 // pointer-to-member-function all in (roughly) the same way.
6560 if (// -- For a non-type template-parameter of type pointer to
6561 // function, only the function-to-pointer conversion (4.3) is
6562 // applied. If the template-argument represents a set of
6563 // overloaded functions (or a pointer to such), the matching
6564 // function is selected from the set (13.4).
6565 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006566 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006567 // -- For a non-type template-parameter of type reference to
6568 // function, no conversions apply. If the template-argument
6569 // represents a set of overloaded functions, the matching
6570 // function is selected from the set (13.4).
6571 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006572 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006573 // -- For a non-type template-parameter of type pointer to
6574 // member function, no conversions apply. If the
6575 // template-argument represents a set of overloaded member
6576 // functions, the matching member function is selected from
6577 // the set (13.4).
6578 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006579 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006580 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006581
Douglas Gregor064fdb22010-04-14 23:11:21 +00006582 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006583 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00006584 true,
6585 FoundResult)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006586 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
John Wiegley01296292011-04-08 18:41:53 +00006587 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00006588
6589 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6590 ArgType = Arg->getType();
6591 } else
John Wiegley01296292011-04-08 18:41:53 +00006592 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006593 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006594
John Wiegley01296292011-04-08 18:41:53 +00006595 if (!ParamType->isMemberPointerType()) {
6596 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6597 ParamType,
6598 Arg, Converted))
6599 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006600 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00006601 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00006602
Douglas Gregor20fdef32012-04-10 17:08:25 +00006603 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6604 Converted))
John Wiegley01296292011-04-08 18:41:53 +00006605 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006606 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006607 }
6608
Chris Lattner696197c2009-02-20 21:37:53 +00006609 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006610 // -- for a non-type template-parameter of type pointer to
6611 // object, qualification conversions (4.4) and the
6612 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00006613 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00006614 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006615 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00006616
John Wiegley01296292011-04-08 18:41:53 +00006617 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6618 ParamType,
6619 Arg, Converted))
6620 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006621 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00006622 }
Mike Stump11289f42009-09-09 15:08:12 +00006623
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006624 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006625 // -- For a non-type template-parameter of type reference to
6626 // object, no conversions apply. The type referred to by the
6627 // reference may be more cv-qualified than the (otherwise
6628 // identical) type of the template-argument. The
6629 // template-parameter is bound directly to the
6630 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00006631 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006632 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00006633
Douglas Gregor064fdb22010-04-14 23:11:21 +00006634 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006635 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
6636 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00006637 true,
6638 FoundResult)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006639 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
John Wiegley01296292011-04-08 18:41:53 +00006640 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00006641
6642 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6643 ArgType = Arg->getType();
6644 } else
John Wiegley01296292011-04-08 18:41:53 +00006645 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006646 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006647
John Wiegley01296292011-04-08 18:41:53 +00006648 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6649 ParamType,
6650 Arg, Converted))
6651 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006652 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006653 }
Douglas Gregor0e558532009-02-11 16:16:59 +00006654
Douglas Gregor20fdef32012-04-10 17:08:25 +00006655 // Deal with parameters of type std::nullptr_t.
6656 if (ParamType->isNullPtrType()) {
6657 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6658 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006659 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006660 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006661
Douglas Gregor20fdef32012-04-10 17:08:25 +00006662 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
6663 case NPV_NotNullPointer:
6664 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
6665 << Arg->getType() << ParamType;
6666 Diag(Param->getLocation(), diag::note_template_param_here);
6667 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00006668
Douglas Gregor20fdef32012-04-10 17:08:25 +00006669 case NPV_Error:
6670 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00006671
Douglas Gregor20fdef32012-04-10 17:08:25 +00006672 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00006673 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00006674 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
6675 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006676 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006677 }
6678 }
6679
Douglas Gregor0e558532009-02-11 16:16:59 +00006680 // -- For a non-type template-parameter of type pointer to data
6681 // member, qualification conversions (4.4) are applied.
6682 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
6683
Douglas Gregor20fdef32012-04-10 17:08:25 +00006684 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6685 Converted))
John Wiegley01296292011-04-08 18:41:53 +00006686 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006687 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00006688}
6689
Richard Smith26b86ea2016-12-31 21:41:23 +00006690static void DiagnoseTemplateParameterListArityMismatch(
6691 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
6692 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
6693
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006694/// Check a template argument against its corresponding
Douglas Gregord32e0282009-02-09 23:23:08 +00006695/// template template parameter.
6696///
6697/// This routine implements the semantics of C++ [temp.arg.template].
6698/// It returns true if an error occurred, and false otherwise.
Richard Smith5d331022018-03-08 01:07:33 +00006699bool Sema::CheckTemplateTemplateArgument(TemplateParameterList *Params,
6700 TemplateArgumentLoc &Arg) {
Eli Friedmanb826a002012-09-26 02:36:12 +00006701 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006702 TemplateDecl *Template = Name.getAsTemplateDecl();
6703 if (!Template) {
6704 // Any dependent template name is fine.
6705 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
6706 return false;
6707 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00006708
Richard Smith26b86ea2016-12-31 21:41:23 +00006709 if (Template->isInvalidDecl())
6710 return true;
6711
Richard Smith3f1b5d02011-05-05 21:57:07 +00006712 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00006713 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00006714 // the name of a class template or an alias template, expressed as an
6715 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00006716 // primary class templates are considered when matching the
6717 // template template argument with the corresponding parameter;
6718 // partial specializations are not considered even if their
6719 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00006720 //
6721 // Note that we also allow template template parameters here, which
6722 // will happen when we are dealing with, e.g., class template
6723 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00006724 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00006725 !isa<TemplateTemplateParmDecl>(Template) &&
David Majnemerc2406d42016-07-11 17:09:56 +00006726 !isa<TypeAliasTemplateDecl>(Template) &&
6727 !isa<BuiltinTemplateDecl>(Template)) {
6728 assert(isa<FunctionTemplateDecl>(Template) &&
6729 "Only function templates are possible here");
Faisal Valib8b04f82016-03-26 20:46:45 +00006730 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
David Majnemerc2406d42016-07-11 17:09:56 +00006731 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
6732 << Template;
Douglas Gregor85e0f662009-02-10 00:24:35 +00006733 }
6734
Richard Smith26b86ea2016-12-31 21:41:23 +00006735 // C++1z [temp.arg.template]p3: (DR 150)
6736 // A template-argument matches a template template-parameter P when P
6737 // is at least as specialized as the template-argument A.
6738 if (getLangOpts().RelaxedTemplateTemplateArgs) {
6739 // Quick check for the common case:
6740 // If P contains a parameter pack, then A [...] matches P if each of A's
6741 // template parameters matches the corresponding template parameter in
6742 // the template-parameter-list of P.
6743 if (TemplateParameterListsAreEqual(
6744 Template->getTemplateParameters(), Params, false,
6745 TPL_TemplateTemplateArgumentMatch, Arg.getLocation()))
6746 return false;
6747
6748 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
6749 Arg.getLocation()))
6750 return false;
6751 // FIXME: Produce better diagnostics for deduction failures.
6752 }
6753
Douglas Gregor85e0f662009-02-10 00:24:35 +00006754 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00006755 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006756 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006757 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006758 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00006759}
6760
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006761/// Given a non-type template argument that refers to a
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006762/// declaration and the type of its corresponding non-type template
6763/// parameter, produce an expression that properly refers to that
6764/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006765ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006766Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6767 QualType ParamType,
6768 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00006769 // C++ [temp.param]p8:
6770 //
6771 // A non-type template-parameter of type "array of T" or
6772 // "function returning T" is adjusted to be of type "pointer to
6773 // T" or "pointer to function returning T", respectively.
6774 if (ParamType->isArrayType())
6775 ParamType = Context.getArrayDecayedType(ParamType);
6776 else if (ParamType->isFunctionType())
6777 ParamType = Context.getPointerType(ParamType);
6778
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006779 // For a NULL non-type template argument, return nullptr casted to the
6780 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00006781 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006782 return ImpCastExprToType(
6783 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
6784 ParamType,
6785 ParamType->getAs<MemberPointerType>()
6786 ? CK_NullToMemberPointer
6787 : CK_NullToPointer);
6788 }
Eli Friedmanb826a002012-09-26 02:36:12 +00006789 assert(Arg.getKind() == TemplateArgument::Declaration &&
6790 "Only declaration template arguments permitted here");
6791
George Burgess IV00f70bd2018-03-01 05:43:23 +00006792 ValueDecl *VD = Arg.getAsDecl();
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006793
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006794 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00006795 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
6796 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006797 // If the value is a class member, we might have a pointer-to-member.
6798 // Determine whether the non-type template template parameter is of
6799 // pointer-to-member type. If so, we need to build an appropriate
6800 // expression for a pointer-to-member, since a "normal" DeclRefExpr
6801 // would refer to the member itself.
6802 if (ParamType->isMemberPointerType()) {
6803 QualType ClassType
6804 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
6805 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00006806 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00006807 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006808 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00006809 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00006810
6811 // The actual value-ness of this is unimportant, but for
6812 // internal consistency's sake, references to instance methods
6813 // are r-values.
6814 ExprValueKind VK = VK_LValue;
6815 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
6816 VK = VK_RValue;
6817
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006818 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00006819 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00006820 VK,
John McCall7decc9e2010-11-18 06:31:45 +00006821 Loc,
6822 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006823 if (RefExpr.isInvalid())
6824 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006825
John McCalle3027922010-08-25 11:45:40 +00006826 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006827
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006828 // We might need to perform a trailing qualification conversion, since
6829 // the element type on the parameter could be more qualified than the
6830 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00006831 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006832 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00006833 ParamType.getUnqualifiedType(), false,
6834 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006835 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006836
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006837 assert(!RefExpr.isInvalid() &&
6838 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006839 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006840 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006841 }
6842 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006843
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006844 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00006845
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006846 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006847 // When the non-type template parameter is a pointer, take the
6848 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00006849 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006850 if (RefExpr.isInvalid())
6851 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006852
Richard Smithfc6fca12017-01-28 00:38:35 +00006853 if (!Context.hasSameUnqualifiedType(ParamType->getPointeeType(), T) &&
6854 (T->isFunctionType() || T->isArrayType())) {
6855 // Decay functions and arrays unless we're forming a pointer to array.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006856 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00006857 if (RefExpr.isInvalid())
6858 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006859
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006860 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006861 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006862
Douglas Gregorb242683d2010-04-01 18:32:35 +00006863 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00006864 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006865 }
6866
John McCall7decc9e2010-11-18 06:31:45 +00006867 ExprValueKind VK = VK_RValue;
6868
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006869 // If the non-type template parameter has reference type, qualify the
6870 // resulting declaration reference with the extra qualifiers on the
6871 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00006872 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
6873 VK = VK_LValue;
6874 T = Context.getQualifiedType(T,
6875 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00006876 } else if (isa<FunctionDecl>(VD)) {
6877 // References to functions are always lvalues.
6878 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00006879 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006880
John McCall7decc9e2010-11-18 06:31:45 +00006881 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006882}
6883
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006884/// Construct a new expression that refers to the given
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006885/// integral template argument with the given source-location
6886/// information.
6887///
6888/// This routine takes care of the mapping from an integral template
6889/// argument (which may have any integral type) to the appropriate
6890/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006891ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006892Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6893 SourceLocation Loc) {
6894 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00006895 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006896 QualType OrigT = Arg.getIntegralType();
6897
6898 // If this is an enum type that we're instantiating, we need to use an integer
6899 // type the same size as the enumerator. We don't want to build an
6900 // IntegerLiteral with enum type. The integer type of an enum type can be of
6901 // any integral type with C++11 enum classes, make sure we create the right
6902 // type of literal for it.
6903 QualType T = OrigT;
6904 if (const EnumType *ET = OrigT->getAs<EnumType>())
6905 T = ET->getDecl()->getIntegerType();
6906
6907 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00006908 if (T->isAnyCharacterType()) {
6909 CharacterLiteral::CharacterKind Kind;
6910 if (T->isWideCharType())
6911 Kind = CharacterLiteral::Wide;
Richard Smith3a8244d2018-05-01 05:02:45 +00006912 else if (T->isChar8Type() && getLangOpts().Char8)
6913 Kind = CharacterLiteral::UTF8;
Douglas Gregorfb65e592011-07-27 05:40:30 +00006914 else if (T->isChar16Type())
6915 Kind = CharacterLiteral::UTF16;
6916 else if (T->isChar32Type())
6917 Kind = CharacterLiteral::UTF32;
6918 else
6919 Kind = CharacterLiteral::Ascii;
6920
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006921 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
6922 Kind, T, Loc);
6923 } else if (T->isBooleanType()) {
6924 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
6925 T, Loc);
6926 } else if (T->isNullPtrType()) {
6927 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
6928 } else {
6929 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00006930 }
6931
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006932 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00006933 // FIXME: This is a hack. We need a better way to handle substituted
6934 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00006935 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
6936 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006937 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00006938 Loc, Loc);
6939 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006940
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006941 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006942}
6943
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006944/// Match two template parameters within template parameter lists.
Douglas Gregor641040a2011-01-12 23:45:44 +00006945static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
6946 bool Complain,
6947 Sema::TemplateParameterListEqualKind Kind,
6948 SourceLocation TemplateArgLoc) {
6949 // Check the actual kind (type, non-type, template).
6950 if (Old->getKind() != New->getKind()) {
6951 if (Complain) {
6952 unsigned NextDiag = diag::err_template_param_different_kind;
6953 if (TemplateArgLoc.isValid()) {
6954 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6955 NextDiag = diag::note_template_param_different_kind;
6956 }
6957 S.Diag(New->getLocation(), NextDiag)
6958 << (Kind != Sema::TPL_TemplateMatch);
6959 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
6960 << (Kind != Sema::TPL_TemplateMatch);
6961 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006962
Douglas Gregor641040a2011-01-12 23:45:44 +00006963 return false;
6964 }
6965
Richard Smith26b86ea2016-12-31 21:41:23 +00006966 // Check that both are parameter packs or neither are parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006967 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006968 // template template parameter, the template template parameter can have
6969 // a parameter pack where the template template argument does not.
6970 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
6971 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
6972 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00006973 if (Complain) {
6974 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
6975 if (TemplateArgLoc.isValid()) {
6976 S.Diag(TemplateArgLoc,
6977 diag::err_template_arg_template_params_mismatch);
6978 NextDiag = diag::note_template_parameter_pack_non_pack;
6979 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006980
Douglas Gregor641040a2011-01-12 23:45:44 +00006981 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
6982 : isa<NonTypeTemplateParmDecl>(New)? 1
6983 : 2;
6984 S.Diag(New->getLocation(), NextDiag)
6985 << ParamKind << New->isParameterPack();
6986 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
6987 << ParamKind << Old->isParameterPack();
6988 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006989
Douglas Gregor641040a2011-01-12 23:45:44 +00006990 return false;
6991 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006992
Douglas Gregor641040a2011-01-12 23:45:44 +00006993 // For non-type template parameters, check the type of the parameter.
6994 if (NonTypeTemplateParmDecl *OldNTTP
6995 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
6996 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006997
Douglas Gregor641040a2011-01-12 23:45:44 +00006998 // If we are matching a template template argument to a template
6999 // template parameter and one of the non-type template parameter types
Richard Smith13894182017-04-13 21:37:24 +00007000 // is dependent, then we must wait until template instantiation time
7001 // to actually compare the arguments.
Douglas Gregor641040a2011-01-12 23:45:44 +00007002 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
Richard Smith13894182017-04-13 21:37:24 +00007003 (OldNTTP->getType()->isDependentType() ||
7004 NewNTTP->getType()->isDependentType()))
Douglas Gregor641040a2011-01-12 23:45:44 +00007005 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007006
Douglas Gregor641040a2011-01-12 23:45:44 +00007007 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
7008 if (Complain) {
7009 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
7010 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007011 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00007012 diag::err_template_arg_template_params_mismatch);
7013 NextDiag = diag::note_template_nontype_parm_different_type;
7014 }
7015 S.Diag(NewNTTP->getLocation(), NextDiag)
7016 << NewNTTP->getType()
7017 << (Kind != Sema::TPL_TemplateMatch);
7018 S.Diag(OldNTTP->getLocation(),
7019 diag::note_template_nontype_parm_prev_declaration)
7020 << OldNTTP->getType();
7021 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007022
Douglas Gregor641040a2011-01-12 23:45:44 +00007023 return false;
7024 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007025
Douglas Gregor641040a2011-01-12 23:45:44 +00007026 return true;
7027 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007028
Douglas Gregor641040a2011-01-12 23:45:44 +00007029 // For template template parameters, check the template parameter types.
7030 // The template parameter lists of template template
7031 // parameters must agree.
7032 if (TemplateTemplateParmDecl *OldTTP
7033 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007034 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00007035 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
7036 OldTTP->getTemplateParameters(),
7037 Complain,
7038 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007039 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00007040 : Kind),
7041 TemplateArgLoc);
7042 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007043
Douglas Gregor641040a2011-01-12 23:45:44 +00007044 return true;
7045}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00007046
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007047/// Diagnose a known arity mismatch when comparing template argument
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007048/// lists.
7049static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007050void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007051 TemplateParameterList *New,
7052 TemplateParameterList *Old,
7053 Sema::TemplateParameterListEqualKind Kind,
7054 SourceLocation TemplateArgLoc) {
7055 unsigned NextDiag = diag::err_template_param_list_different_arity;
7056 if (TemplateArgLoc.isValid()) {
7057 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7058 NextDiag = diag::note_template_param_list_different_arity;
7059 }
7060 S.Diag(New->getTemplateLoc(), NextDiag)
7061 << (New->size() > Old->size())
7062 << (Kind != Sema::TPL_TemplateMatch)
7063 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
7064 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
7065 << (Kind != Sema::TPL_TemplateMatch)
7066 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
7067}
7068
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007069/// Determine whether the given template parameter lists are
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007070/// equivalent.
7071///
Mike Stump11289f42009-09-09 15:08:12 +00007072/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007073/// source code as part of a new template declaration.
7074///
7075/// \param Old The old template parameter list, typically found via
7076/// name lookup of the template declared with this template parameter
7077/// list.
7078///
7079/// \param Complain If true, this routine will produce a diagnostic if
7080/// the template parameter lists are not equivalent.
7081///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00007082/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00007083///
7084/// \param TemplateArgLoc If this source location is valid, then we
7085/// are actually checking the template parameter list of a template
7086/// argument (New) against the template parameter list of its
7087/// corresponding template template parameter (Old). We produce
7088/// slightly different diagnostics in this scenario.
7089///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007090/// \returns True if the template parameter lists are equal, false
7091/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00007092bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007093Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
7094 TemplateParameterList *Old,
7095 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00007096 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00007097 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007098 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
7099 if (Complain)
7100 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7101 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007102
7103 return false;
7104 }
7105
Douglas Gregor641040a2011-01-12 23:45:44 +00007106 // C++0x [temp.arg.template]p3:
7107 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00007108 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00007109 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00007110 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007111 // template-parameter-list of P. [...]
7112 TemplateParameterList::iterator NewParm = New->begin();
7113 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007114 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007115 OldParmEnd = Old->end();
7116 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00007117 if (Kind != TPL_TemplateTemplateArgumentMatch ||
7118 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007119 if (NewParm == NewParmEnd) {
7120 if (Complain)
7121 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7122 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007123
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007124 return false;
7125 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007126
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007127 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
7128 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007129 return false;
7130
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007131 ++NewParm;
7132 continue;
7133 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007134
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007135 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00007136 // [...] When P's template- parameter-list contains a template parameter
7137 // pack (14.5.3), the template parameter pack will match zero or more
7138 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007139 // template-parameter-list of A with the same type and form as the
7140 // template parameter pack in P (ignoring whether those template
7141 // parameters are template parameter packs).
7142 for (; NewParm != NewParmEnd; ++NewParm) {
7143 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
7144 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007145 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007146 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007147 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007148
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007149 // Make sure we exhausted all of the arguments.
7150 if (NewParm != NewParmEnd) {
7151 if (Complain)
7152 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7153 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007154
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007155 return false;
7156 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007157
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007158 return true;
7159}
7160
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007161/// Check whether a template can be declared within this scope.
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007162///
7163/// If the template declaration is valid in this scope, returns
7164/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00007165bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007166Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00007167 if (!S)
7168 return false;
7169
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007170 // Find the nearest enclosing declaration scope.
7171 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7172 (S->getFlags() & Scope::TemplateParamScope) != 0)
7173 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00007174
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00007175 // C++ [temp]p4:
7176 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007177 DeclContext *Ctx = S->getEntity();
Alex Lorenz560ae562016-11-02 15:46:34 +00007178 if (Ctx && Ctx->isExternCContext()) {
7179 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
7180 << TemplateParams->getSourceRange();
7181 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
7182 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
7183 return true;
7184 }
Richard Smith8df390f2016-09-08 23:14:54 +00007185 Ctx = Ctx->getRedeclContext();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007186
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00007187 // C++ [temp]p2:
7188 // A template-declaration can appear only as a namespace scope or
7189 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00007190 if (Ctx) {
7191 if (Ctx->isFileContext())
7192 return false;
7193 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
7194 // C++ [temp.mem]p2:
7195 // A local class shall not have member templates.
7196 if (RD->isLocalClass())
7197 return Diag(TemplateParams->getTemplateLoc(),
7198 diag::err_template_inside_local_class)
7199 << TemplateParams->getSourceRange();
7200 else
7201 return false;
7202 }
7203 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007204
Mike Stump11289f42009-09-09 15:08:12 +00007205 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007206 diag::err_template_outside_namespace_or_class_scope)
7207 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007208}
Douglas Gregor67a65642009-02-17 23:15:12 +00007209
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007210/// Determine what kind of template specialization the given declaration
Douglas Gregor54888652009-10-07 00:13:32 +00007211/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007212static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00007213 if (!D)
7214 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007215
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007216 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
7217 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00007218 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
7219 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007220 if (VarDecl *Var = dyn_cast<VarDecl>(D))
7221 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007222
Douglas Gregor54888652009-10-07 00:13:32 +00007223 return TSK_Undeclared;
7224}
7225
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007226/// Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007227/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00007228///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007229/// This routine determines whether a template specialization can be declared
7230/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00007231///
7232/// \param S the semantic analysis object for which this check is being
7233/// performed.
7234///
7235/// \param Specialized the entity being specialized or instantiated, which
7236/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007237/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00007238/// member class).
7239///
7240/// \param PrevDecl the previous declaration of this entity, if any.
7241///
7242/// \param Loc the location of the explicit specialization or instantiation of
7243/// this entity.
7244///
7245/// \param IsPartialSpecialization whether this is a partial specialization of
7246/// a class template.
7247///
Douglas Gregor54888652009-10-07 00:13:32 +00007248/// \returns true if there was an error that we cannot recover from, false
7249/// otherwise.
7250static bool CheckTemplateSpecializationScope(Sema &S,
7251 NamedDecl *Specialized,
7252 NamedDecl *PrevDecl,
7253 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007254 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00007255 // Keep these "kind" numbers in sync with the %select statements in the
7256 // various diagnostics emitted by this routine.
7257 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00007258 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00007259 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007260 else if (isa<VarTemplateDecl>(Specialized))
7261 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00007262 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00007263 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007264 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00007265 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007266 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00007267 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007268 else if (isa<RecordDecl>(Specialized))
7269 EntityKind = 7;
7270 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
7271 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00007272 else {
Richard Smith7d137e32012-03-23 03:33:32 +00007273 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007274 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007275 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00007276 return true;
7277 }
7278
Douglas Gregorf47b9112009-02-25 22:02:03 +00007279 // C++ [temp.expl.spec]p2:
Richard Smithc660c8f2018-03-16 13:36:56 +00007280 // An explicit specialization may be declared in any scope in which
7281 // the corresponding primary template may be defined.
Sebastian Redl50c68252010-08-31 00:36:30 +00007282 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00007283 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007284 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007285 return true;
7286 }
Douglas Gregore4b05162009-10-07 17:21:34 +00007287
7288 // C++ [temp.class.spec]p6:
Richard Smithc660c8f2018-03-16 13:36:56 +00007289 // A class template partial specialization may be declared in any
7290 // scope in which the primary template may be defined.
7291 DeclContext *SpecializedContext =
7292 Specialized->getDeclContext()->getRedeclContext();
7293 DeclContext *DC = S.CurContext->getRedeclContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00007294
Richard Smithc660c8f2018-03-16 13:36:56 +00007295 // Make sure that this redeclaration (or definition) occurs in the same
7296 // scope or an enclosing namespace.
7297 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
7298 : DC->Equals(SpecializedContext))) {
Richard Smitha98f8fc2013-12-07 05:09:50 +00007299 if (isa<TranslationUnitDecl>(SpecializedContext))
7300 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
7301 << EntityKind << Specialized;
Richard Smithc660c8f2018-03-16 13:36:56 +00007302 else {
7303 auto *ND = cast<NamedDecl>(SpecializedContext);
Alexey Bataev0068cb22015-03-20 07:21:46 +00007304 int Diag = diag::err_template_spec_redecl_out_of_scope;
Richard Smithc660c8f2018-03-16 13:36:56 +00007305 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
Alexey Bataev0068cb22015-03-20 07:21:46 +00007306 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
7307 S.Diag(Loc, Diag) << EntityKind << Specialized
Richard Smithc660c8f2018-03-16 13:36:56 +00007308 << ND << isa<CXXRecordDecl>(ND);
7309 }
Richard Smitha98f8fc2013-12-07 05:09:50 +00007310
7311 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007312
Richard Smithc660c8f2018-03-16 13:36:56 +00007313 // Don't allow specializing in the wrong class during error recovery.
7314 // Otherwise, things can go horribly wrong.
7315 if (DC->isRecord())
7316 return true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007317 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007318
Douglas Gregorf47b9112009-02-25 22:02:03 +00007319 return false;
7320}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007321
Richard Smith57aae072016-12-28 02:37:25 +00007322static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
7323 if (!E->isTypeDependent())
Richard Smith6056d5e2014-02-09 00:54:43 +00007324 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00007325 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00007326 Checker.TraverseStmt(E);
Richard Smith57aae072016-12-28 02:37:25 +00007327 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00007328 return E->getSourceRange();
7329 return Checker.MatchLoc;
7330}
7331
7332static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
7333 if (!TL.getType()->isDependentType())
7334 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00007335 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00007336 Checker.TraverseTypeLoc(TL);
Richard Smith57aae072016-12-28 02:37:25 +00007337 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00007338 return TL.getSourceRange();
7339 return Checker.MatchLoc;
7340}
7341
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007342/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007343/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007344static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00007345 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
7346 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007347 for (unsigned I = 0; I != NumArgs; ++I) {
7348 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00007349 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00007350 S, TemplateNameLoc, Param, Args[I].pack_begin(),
7351 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007352 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007353
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007354 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007355 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007356
Eli Friedmanb826a002012-09-26 02:36:12 +00007357 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007358 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00007359
7360 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007361
Douglas Gregor98318c22011-01-03 21:37:45 +00007362 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007363 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
7364 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00007365
7366 // Strip off any implicit casts we added as part of type checking.
7367 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
7368 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007369
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007370 // C++ [temp.class.spec]p8:
7371 // A non-type argument is non-specialized if it is the name of a
7372 // non-type parameter. All other non-type arguments are
7373 // specialized.
7374 //
7375 // Below, we check the two conditions that only apply to
7376 // specialized non-type arguments, so skip any non-specialized
7377 // arguments.
7378 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00007379 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007380 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007381
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007382 // C++ [temp.class.spec]p9:
7383 // Within the argument list of a class template partial
7384 // specialization, the following restrictions apply:
7385 // -- A partially specialized non-type argument expression
7386 // shall not involve a template parameter of the partial
7387 // specialization except when the argument expression is a
7388 // simple identifier.
Richard Smith57aae072016-12-28 02:37:25 +00007389 // -- The type of a template parameter corresponding to a
7390 // specialized non-type argument shall not be dependent on a
7391 // parameter of the specialization.
7392 // DR1315 removes the first bullet, leaving an incoherent set of rules.
7393 // We implement a compromise between the original rules and DR1315:
7394 // -- A specialized non-type template argument shall not be
7395 // type-dependent and the corresponding template parameter
7396 // shall have a non-dependent type.
Richard Smith6056d5e2014-02-09 00:54:43 +00007397 SourceRange ParamUseRange =
Richard Smith57aae072016-12-28 02:37:25 +00007398 findTemplateParameterInType(Param->getDepth(), ArgExpr);
Richard Smith6056d5e2014-02-09 00:54:43 +00007399 if (ParamUseRange.isValid()) {
7400 if (IsDefaultArgument) {
7401 S.Diag(TemplateNameLoc,
7402 diag::err_dependent_non_type_arg_in_partial_spec);
7403 S.Diag(ParamUseRange.getBegin(),
7404 diag::note_dependent_non_type_default_arg_in_partial_spec)
7405 << ParamUseRange;
7406 } else {
7407 S.Diag(ParamUseRange.getBegin(),
7408 diag::err_dependent_non_type_arg_in_partial_spec)
7409 << ParamUseRange;
7410 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007411 return true;
7412 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007413
Richard Smith6056d5e2014-02-09 00:54:43 +00007414 ParamUseRange = findTemplateParameter(
Richard Smith57aae072016-12-28 02:37:25 +00007415 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
Richard Smith6056d5e2014-02-09 00:54:43 +00007416 if (ParamUseRange.isValid()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007417 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
Richard Smith6056d5e2014-02-09 00:54:43 +00007418 diag::err_dependent_typed_non_type_arg_in_partial_spec)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007419 << Param->getType();
Richard Smith6056d5e2014-02-09 00:54:43 +00007420 S.Diag(Param->getLocation(), diag::note_template_param_here)
Richard Smith57aae072016-12-28 02:37:25 +00007421 << (IsDefaultArgument ? ParamUseRange : SourceRange())
7422 << ParamUseRange;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007423 return true;
7424 }
7425 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007426
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007427 return false;
7428}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007429
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007430/// Check the non-type template arguments of a class template
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007431/// partial specialization according to C++ [temp.class.spec]p9.
7432///
Richard Smith6056d5e2014-02-09 00:54:43 +00007433/// \param TemplateNameLoc the location of the template name.
Simon Pilgrim6905d222016-12-30 22:55:33 +00007434/// \param PrimaryTemplate the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00007435/// template.
7436/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00007437/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00007438/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007439///
Richard Smith6056d5e2014-02-09 00:54:43 +00007440/// \returns \c true if there was an error, \c false otherwise.
Richard Smith57aae072016-12-28 02:37:25 +00007441bool Sema::CheckTemplatePartialSpecializationArgs(
7442 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
7443 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
7444 // We have to be conservative when checking a template in a dependent
7445 // context.
7446 if (PrimaryTemplate->getDeclContext()->isDependentContext())
7447 return false;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007448
Richard Smith57aae072016-12-28 02:37:25 +00007449 TemplateParameterList *TemplateParams =
7450 PrimaryTemplate->getTemplateParameters();
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007451 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7452 NonTypeTemplateParmDecl *Param
7453 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
7454 if (!Param)
7455 continue;
7456
Richard Smith57aae072016-12-28 02:37:25 +00007457 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
7458 Param, &TemplateArgs[I],
7459 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007460 return true;
7461 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007462
7463 return false;
7464}
7465
Erich Keanec480f302018-07-12 21:09:05 +00007466DeclResult Sema::ActOnClassTemplateSpecialization(
7467 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7468 SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId,
7469 const ParsedAttributesView &Attr,
7470 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00007471 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00007472
Richard Smith4b55a9c2014-04-17 03:29:33 +00007473 CXXScopeSpec &SS = TemplateId.SS;
7474
Abramo Bagnara60804e12011-03-18 15:16:37 +00007475 // NOTE: KWLoc is the location of the tag keyword. This will instead
7476 // store the location of the outermost template keyword in the declaration.
7477 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00007478 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
7479 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
7480 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
7481 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00007482
Douglas Gregor67a65642009-02-17 23:15:12 +00007483 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00007484 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00007485 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00007486 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
7487
7488 if (!ClassTemplate) {
7489 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007490 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00007491 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
7492 return true;
7493 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007494
Richard Smithf445f192017-02-09 21:04:43 +00007495 bool isMemberSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00007496 bool isPartialSpecialization = false;
7497
Douglas Gregorf47b9112009-02-25 22:02:03 +00007498 // Check the validity of the template headers that introduce this
7499 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00007500 // FIXME: We probably shouldn't complain about these headers for
7501 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007502 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00007503 TemplateParameterList *TemplateParams =
7504 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00007505 KWLoc, TemplateNameLoc, SS, &TemplateId,
Richard Smithf445f192017-02-09 21:04:43 +00007506 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
Richard Smith4b55a9c2014-04-17 03:29:33 +00007507 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007508 if (Invalid)
7509 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007510
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007511 if (TemplateParams && TemplateParams->size() > 0) {
7512 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007513
Douglas Gregorec9518b2010-12-21 08:14:57 +00007514 if (TUK == TUK_Friend) {
7515 Diag(KWLoc, diag::err_partial_specialization_friend)
7516 << SourceRange(LAngleLoc, RAngleLoc);
7517 return true;
7518 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007519
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007520 // C++ [temp.class.spec]p10:
7521 // The template parameter list of a specialization shall not
7522 // contain default template argument values.
7523 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7524 Decl *Param = TemplateParams->getParam(I);
7525 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
7526 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00007527 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007528 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00007529 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007530 }
7531 } else if (NonTypeTemplateParmDecl *NTTP
7532 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
7533 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00007534 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007535 diag::err_default_arg_in_partial_spec)
7536 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00007537 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007538 }
7539 } else {
7540 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00007541 if (TTP->hasDefaultArgument()) {
7542 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007543 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00007544 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00007545 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00007546 }
7547 }
7548 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007549 } else if (TemplateParams) {
7550 if (TUK == TUK_Friend)
7551 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00007552 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007553 SourceRange(TemplateParams->getTemplateLoc(),
7554 TemplateParams->getRAngleLoc()))
7555 << SourceRange(LAngleLoc, RAngleLoc);
Richard Smith4b55a9c2014-04-17 03:29:33 +00007556 } else {
7557 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007558 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00007559
Douglas Gregor67a65642009-02-17 23:15:12 +00007560 // Check that the specialization uses the same tag kind as the
7561 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007562 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7563 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00007564 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007565 Kind, TUK == TUK_Definition, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00007566 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007567 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00007568 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007569 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00007570 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007571 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00007572 diag::note_previous_use);
7573 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7574 }
7575
Douglas Gregorc40290e2009-03-09 23:48:35 +00007576 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00007577 TemplateArgumentListInfo TemplateArgs =
7578 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00007579
Douglas Gregor14406932011-01-03 20:35:03 +00007580 // Check for unexpanded parameter packs in any of the template arguments.
7581 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007582 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00007583 UPPC_PartialSpecialization))
7584 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007585
Douglas Gregor67a65642009-02-17 23:15:12 +00007586 // Check that the template argument list is well-formed for this
7587 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007588 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007589 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7590 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00007591 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00007592
Douglas Gregor2373c592009-05-31 09:31:02 +00007593 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00007594 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00007595 if (isPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00007596 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
7597 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007598 return true;
7599
Richard Smith57aae072016-12-28 02:37:25 +00007600 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
7601 // also do it during instantiation.
Douglas Gregor678d76c2011-07-01 01:22:09 +00007602 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007603 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00007604 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00007605 TemplateArgs.arguments(), InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00007606 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
7607 << ClassTemplate->getDeclName();
7608 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00007609 }
7610 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007611
Craig Topperc3ec1492014-05-26 06:22:03 +00007612 void *InsertPos = nullptr;
7613 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00007614
7615 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007616 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00007617 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00007618 else
Craig Topper7e0daca2014-06-26 04:58:53 +00007619 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00007620
Craig Topperc3ec1492014-05-26 06:22:03 +00007621 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00007622
Douglas Gregorf47b9112009-02-25 22:02:03 +00007623 // Check whether we can declare a class template specialization in
7624 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00007625 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007626 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
7627 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007628 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00007629 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007630
Douglas Gregor15301382009-07-30 17:40:51 +00007631 // The canonical type
7632 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00007633 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00007634 // Build the canonical type that describes the converted template
7635 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00007636 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7637 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00007638 Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007639
7640 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007641 ClassTemplate->getInjectedClassNameSpecialization())) {
7642 // C++ [temp.class.spec]p9b3:
7643 //
7644 // -- The argument list of the specialization shall not be identical
7645 // to the implicit argument list of the primary template.
Richard Smith0e617ec2016-12-27 07:56:27 +00007646 //
7647 // This rule has since been removed, because it's redundant given DR1495,
7648 // but we keep it because it produces better diagnostics and recovery.
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007649 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00007650 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00007651 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007652 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
7653 ClassTemplate->getIdentifier(),
7654 TemplateNameLoc,
7655 Attr,
7656 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00007657 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00007658 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00007659 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007660 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007661 }
Douglas Gregor15301382009-07-30 17:40:51 +00007662
Douglas Gregor2373c592009-05-31 09:31:02 +00007663 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00007664 ClassTemplatePartialSpecializationDecl *PrevPartial
7665 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007666 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00007667 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00007668 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007669 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00007670 TemplateParams,
7671 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007672 Converted,
John McCall6b51f282009-11-23 01:53:49 +00007673 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00007674 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00007675 PrevPartial);
Bruno Ricci4224c872018-12-21 14:35:24 +00007676 SetNestedNameSpecifier(*this, Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007677 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Benjamin Kramer9cc210652015-08-05 09:40:49 +00007678 Partial->setTemplateParameterListsInfo(
7679 Context, TemplateParameterLists.drop_back(1));
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007680 }
Douglas Gregor2373c592009-05-31 09:31:02 +00007681
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007682 if (!PrevPartial)
7683 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00007684 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00007685
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007686 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00007687 // template specialization, make a note of that.
7688 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
7689 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007690
Richard Smith57aae072016-12-28 02:37:25 +00007691 CheckTemplatePartialSpecialization(Partial);
Douglas Gregor67a65642009-02-17 23:15:12 +00007692 } else {
7693 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00007694 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00007695 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007696 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00007697 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007698 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007699 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007700 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00007701 PrevDecl);
Bruno Ricci4224c872018-12-21 14:35:24 +00007702 SetNestedNameSpecifier(*this, Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007703 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00007704 Specialization->setTemplateParameterListsInfo(Context,
Benjamin Kramer9cc210652015-08-05 09:40:49 +00007705 TemplateParameterLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007706 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007707
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007708 if (!PrevDecl)
7709 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00007710
David Majnemer678f50b2015-11-18 19:49:19 +00007711 if (CurContext->isDependentContext()) {
David Majnemer678f50b2015-11-18 19:49:19 +00007712 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7713 CanonType = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00007714 CanonTemplate, Converted);
David Majnemer678f50b2015-11-18 19:49:19 +00007715 } else {
7716 CanonType = Context.getTypeDeclType(Specialization);
7717 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007718 }
7719
Douglas Gregor06db9f52009-10-12 20:18:28 +00007720 // C++ [temp.expl.spec]p6:
7721 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007722 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007723 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007724 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007725 // use occurs; no diagnostic is required.
7726 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007727 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007728 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007729 // Is there any previous explicit specialization declaration?
7730 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7731 Okay = true;
7732 break;
7733 }
7734 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007735
Douglas Gregorc854c662010-02-26 06:03:23 +00007736 if (!Okay) {
7737 SourceRange Range(TemplateNameLoc, RAngleLoc);
7738 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
7739 << Context.getTypeDeclType(Specialization) << Range;
7740
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007741 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00007742 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007743 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00007744 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00007745 return true;
7746 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007747 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007748
Douglas Gregor2208a292009-09-26 20:57:03 +00007749 // If this is not a friend, note that this is an explicit specialization.
7750 if (TUK != TUK_Friend)
7751 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00007752
7753 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00007754 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00007755 RecordDecl *Def = Specialization->getDefinition();
7756 NamedDecl *Hidden = nullptr;
7757 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
7758 SkipBody->ShouldSkip = true;
Richard Smithc4577662018-09-12 02:13:47 +00007759 SkipBody->Previous = Def;
Richard Smith858e0e02017-05-11 23:11:16 +00007760 makeMergedDefinitionVisible(Hidden);
Richard Smithc7e6ff02015-05-18 20:36:47 +00007761 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00007762 SourceRange Range(TemplateNameLoc, RAngleLoc);
Richard Smith792c22d2016-12-24 04:09:05 +00007763 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00007764 Diag(Def->getLocation(), diag::note_previous_definition);
7765 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00007766 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00007767 }
7768 }
7769
Erich Keanec480f302018-07-12 21:09:05 +00007770 ProcessDeclAttributeList(S, Specialization, Attr);
John McCall659a3372010-12-18 03:30:47 +00007771
Richard Smith034b94a2012-08-17 03:20:55 +00007772 // Add alignment attributes if necessary; these attributes are checked when
7773 // the ASTContext lays out the structure.
Richard Smithc4577662018-09-12 02:13:47 +00007774 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
Richard Smith034b94a2012-08-17 03:20:55 +00007775 AddAlignmentAttributesForRecord(Specialization);
7776 AddMsStructLayoutForRecord(Specialization);
7777 }
7778
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00007779 if (ModulePrivateLoc.isValid())
7780 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
7781 << (isPartialSpecialization? 1 : 0)
7782 << FixItHint::CreateRemoval(ModulePrivateLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00007783
Douglas Gregord56a91e2009-02-26 22:19:44 +00007784 // Build the fully-sugared type for this class template
7785 // specialization as the user wrote in the specialization
7786 // itself. This means that we'll pretty-print the type retrieved
7787 // from the specialization's declaration the way that the user
7788 // actually wrote the specialization, rather than formatting the
7789 // name based on the "canonical" representation used to store the
7790 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007791 TypeSourceInfo *WrittenTy
7792 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7793 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007794 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00007795 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007796 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007797 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007798
Douglas Gregor1e249f82009-02-25 22:18:32 +00007799 // C++ [temp.expl.spec]p9:
7800 // A template explicit specialization is in the scope of the
7801 // namespace in which the template was defined.
7802 //
7803 // We actually implement this paragraph where we set the semantic
7804 // context (in the creation of the ClassTemplateSpecializationDecl),
7805 // but we also maintain the lexical context where the actual
7806 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00007807 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00007808
Douglas Gregor67a65642009-02-17 23:15:12 +00007809 // We may be starting the definition of this specialization.
Richard Smithc4577662018-09-12 02:13:47 +00007810 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
Douglas Gregor67a65642009-02-17 23:15:12 +00007811 Specialization->startDefinition();
7812
Douglas Gregor2208a292009-09-26 20:57:03 +00007813 if (TUK == TUK_Friend) {
7814 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
7815 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00007816 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00007817 /*FIXME:*/KWLoc);
7818 Friend->setAccess(AS_public);
7819 CurContext->addDecl(Friend);
7820 } else {
7821 // Add the specialization into its lexical context, so that it can
7822 // be seen when iterating through the list of declarations in that
7823 // context. However, specializations are not found by name lookup.
7824 CurContext->addDecl(Specialization);
7825 }
Richard Smithc4577662018-09-12 02:13:47 +00007826
7827 if (SkipBody && SkipBody->ShouldSkip)
7828 return SkipBody->Previous;
7829
John McCall48871652010-08-21 09:40:31 +00007830 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00007831}
Douglas Gregor333489b2009-03-27 23:10:48 +00007832
John McCall48871652010-08-21 09:40:31 +00007833Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00007834 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00007835 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007836 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00007837 ActOnDocumentableDecl(NewDecl);
7838 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00007839}
7840
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007841/// Strips various properties off an implicit instantiation
John McCall4f7ced62010-02-11 01:33:53 +00007842/// that has just been explicitly specialized.
7843static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00007844 D->dropAttr<DLLImportAttr>();
7845 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00007846
Nico Webere4974382014-12-19 23:52:45 +00007847 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00007848 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00007849}
7850
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007851/// Compute the diagnostic location for an explicit instantiation
Nico Webera8f80b32012-01-09 19:52:25 +00007852// declaration or definition.
7853static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007854 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00007855 // Explicit instantiations following a specialization have no effect and
7856 // hence no PointOfInstantiation. In that case, walk decl backwards
7857 // until a valid name loc is found.
7858 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007859 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
7860 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00007861 PrevDiagLoc = Prev->getLocation();
7862 }
7863 assert(PrevDiagLoc.isValid() &&
7864 "Explicit instantiation without point of instantiation?");
7865 return PrevDiagLoc;
7866}
7867
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007868/// Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007869/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007870/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007871/// new specialization/instantiation will have any effect.
7872///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007873/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007874/// instantiation.
7875///
7876/// \param NewTSK the kind of the new explicit specialization or instantiation.
7877///
7878/// \param PrevDecl the previous declaration of the entity.
7879///
7880/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
7881///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007882/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007883/// declaration was instantiated (either implicitly or explicitly).
7884///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007885/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007886/// specialization or instantiation has no effect and should be ignored.
7887///
7888/// \returns true if there was an error that should prevent the introduction of
7889/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00007890bool
7891Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7892 TemplateSpecializationKind NewTSK,
7893 NamedDecl *PrevDecl,
7894 TemplateSpecializationKind PrevTSK,
7895 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007896 bool &HasNoEffect) {
7897 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007898
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007899 switch (NewTSK) {
7900 case TSK_Undeclared:
7901 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00007902 assert(
7903 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
7904 "previous declaration must be implicit!");
7905 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007906
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007907 case TSK_ExplicitSpecialization:
7908 switch (PrevTSK) {
7909 case TSK_Undeclared:
7910 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007911 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007912 // explicitly specialized or has merely been mentioned without any
7913 // instantiation.
7914 return false;
7915
7916 case TSK_ImplicitInstantiation:
7917 if (PrevPointOfInstantiation.isInvalid()) {
7918 // The declaration itself has not actually been instantiated, so it is
7919 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00007920 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007921 return false;
7922 }
7923 // Fall through
Galina Kistanova3779cb32017-06-07 06:25:05 +00007924 LLVM_FALLTHROUGH;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007925
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007926 case TSK_ExplicitInstantiationDeclaration:
7927 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007928 assert((PrevTSK == TSK_ImplicitInstantiation ||
7929 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007930 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007931
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007932 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007933 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007934 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007935 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007936 // implicit instantiation to take place, in every translation unit in
7937 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007938 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007939 // Is there any previous explicit specialization declaration?
7940 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
7941 return false;
7942 }
7943
Douglas Gregor1d957a32009-10-27 18:42:08 +00007944 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007945 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007946 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007947 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007948
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007949 return true;
7950 }
Galina Kistanova1d36e832017-06-08 18:20:32 +00007951 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007952
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007953 case TSK_ExplicitInstantiationDeclaration:
7954 switch (PrevTSK) {
7955 case TSK_ExplicitInstantiationDeclaration:
7956 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00007957 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007958 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007959
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007960 case TSK_Undeclared:
7961 case TSK_ImplicitInstantiation:
7962 // We're explicitly instantiating something that may have already been
7963 // implicitly instantiated; that's fine.
7964 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007965
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007966 case TSK_ExplicitSpecialization:
7967 // C++0x [temp.explicit]p4:
7968 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007969 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007970 // specialization for that template, the explicit instantiation has no
7971 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007972 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007973 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007974
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007975 case TSK_ExplicitInstantiationDefinition:
7976 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007977 // If an entity is the subject of both an explicit instantiation
7978 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007979 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007980 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00007981 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00007982
7983 // Explicit instantiations following a specialization have no effect and
7984 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
7985 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00007986 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7987 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007988 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007989 return false;
7990 }
Bruno Riccid8c17672018-12-21 20:38:06 +00007991 llvm_unreachable("Unexpected TemplateSpecializationKind!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007992
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007993 case TSK_ExplicitInstantiationDefinition:
7994 switch (PrevTSK) {
7995 case TSK_Undeclared:
7996 case TSK_ImplicitInstantiation:
7997 // We're explicitly instantiating something that may have already been
7998 // implicitly instantiated; that's fine.
7999 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008000
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008001 case TSK_ExplicitSpecialization:
8002 // C++ DR 259, C++0x [temp.explicit]p4:
8003 // For a given set of template parameters, if an explicit
8004 // instantiation of a template appears after a declaration of
8005 // an explicit specialization for that template, the explicit
8006 // instantiation has no effect.
Richard Smithe4caa482016-08-31 23:23:25 +00008007 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
Richard Smith0bf8a4922011-10-18 20:49:44 +00008008 << PrevDecl;
8009 Diag(PrevDecl->getLocation(),
8010 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008011 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008012 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008013
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008014 case TSK_ExplicitInstantiationDeclaration:
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00008015 // We're explicitly instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008016 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00008017
8018 // C++0x [temp.explicit]p4:
8019 // For a given set of template parameters, if an explicit instantiation
8020 // of a template appears after a declaration of an explicit
8021 // specialization for that template, the explicit instantiation has no
8022 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00008023 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00008024 // Is there any previous explicit specialization declaration?
8025 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
8026 HasNoEffect = true;
8027 break;
8028 }
8029 }
8030
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008031 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008032
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008033 case TSK_ExplicitInstantiationDefinition:
8034 // C++0x [temp.spec]p5:
8035 // For a given template and a given set of template-arguments,
8036 // - an explicit instantiation definition shall appear at most once
8037 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00008038
8039 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
8040 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00008041 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00008042 : diag::err_explicit_instantiation_duplicate)
8043 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00008044 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00008045 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008046 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008047 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008048 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008049 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008050
David Blaikie83d382b2011-09-23 05:06:16 +00008051 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008052}
8053
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008054/// Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00008055/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00008056///
James Dennettf14a6e52012-06-15 22:23:43 +00008057/// The only possible way to get a dependent function template specialization
8058/// is with a friend declaration, like so:
8059///
8060/// \code
8061/// template \<class T> void foo(T);
8062/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00008063/// friend void foo<>(T);
8064/// };
James Dennettf14a6e52012-06-15 22:23:43 +00008065/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00008066///
8067/// There really isn't any useful analysis we can do here, so we
8068/// just store the information.
8069bool
8070Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
8071 const TemplateArgumentListInfo &ExplicitTemplateArgs,
8072 LookupResult &Previous) {
8073 // Remove anything from Previous that isn't a function template in
8074 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00008075 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00008076 LookupResult::Filter F = Previous.makeFilter();
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008077 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
8078 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
John McCallb9c78482010-04-08 09:05:18 +00008079 while (F.hasNext()) {
8080 NamedDecl *D = F.next()->getUnderlyingDecl();
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008081 if (!isa<FunctionTemplateDecl>(D)) {
John McCallb9c78482010-04-08 09:05:18 +00008082 F.erase();
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008083 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
8084 continue;
8085 }
8086
8087 if (!FDLookupContext->InEnclosingNamespaceSetOf(
8088 D->getDeclContext()->getRedeclContext())) {
8089 F.erase();
8090 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
8091 continue;
8092 }
John McCallb9c78482010-04-08 09:05:18 +00008093 }
8094 F.done();
8095
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008096 if (Previous.empty()) {
8097 Diag(FD->getLocation(),
8098 diag::err_dependent_function_template_spec_no_match);
8099 for (auto &P : DiscardedCandidates)
8100 Diag(P.second->getLocation(),
8101 diag::note_dependent_function_template_spec_discard_reason)
8102 << P.first;
8103 return true;
8104 }
John McCallb9c78482010-04-08 09:05:18 +00008105
8106 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
8107 ExplicitTemplateArgs);
8108 return false;
8109}
8110
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008111/// Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008112/// specialization.
8113///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008114/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008115/// explicit function template specialization. On successful completion,
8116/// the function declaration \p FD will become a function template
8117/// specialization.
8118///
8119/// \param FD the function declaration, which will be updated to become a
8120/// function template specialization.
8121///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008122/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
8123/// if any. Note that this may be valid info even when 0 arguments are
8124/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
8125/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008126///
Francois Pichet3a44e432011-07-08 06:21:47 +00008127/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008128/// this function specialization.
Richard Smith8ce732b2019-01-07 06:00:46 +00008129///
8130/// \param QualifiedFriend whether this is a lookup for a qualified friend
8131/// declaration with no explicit template argument list that might be
8132/// befriending a function template specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008133bool Sema::CheckFunctionTemplateSpecialization(
8134 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smith8ce732b2019-01-07 06:00:46 +00008135 LookupResult &Previous, bool QualifiedFriend) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008136 // The set of function template specializations that could match this
8137 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00008138 UnresolvedSet<8> Candidates;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008139 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
8140 /*ForTakingAddress=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008141
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008142 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
8143 ConvertedTemplateArgs;
8144
Sebastian Redl50c68252010-08-31 00:36:30 +00008145 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00008146 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8147 I != E; ++I) {
8148 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
8149 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008150 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008151 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00008152 if (!FDLookupContext->InEnclosingNamespaceSetOf(
8153 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008154 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008155
Richard Smith574f4f62013-01-14 05:37:29 +00008156 // When matching a constexpr member function template specialization
8157 // against the primary template, we don't yet know whether the
8158 // specialization has an implicit 'const' (because we don't know whether
8159 // it will be a static member function until we know which template it
8160 // specializes), so adjust it now assuming it specializes this template.
8161 QualType FT = FD->getType();
8162 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00008163 CXXMethodDecl *OldMD =
8164 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00008165 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00008166 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00008167 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00008168 EPI.TypeQuals.addConst();
Alp Toker314cc812014-01-25 16:55:45 +00008169 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00008170 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00008171 }
8172 }
8173
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008174 TemplateArgumentListInfo Args;
8175 if (ExplicitTemplateArgs)
8176 Args = *ExplicitTemplateArgs;
8177
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008178 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008179 // A trailing template-argument can be left unspecified in the
8180 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008181 // provided it can be deduced from the function argument type.
8182 // Perform template argument deduction to determine whether we may be
8183 // specializing this template.
8184 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00008185 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00008186 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00008187 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
8188 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
Richard Smithc2bebe92016-05-11 20:37:46 +00008189 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
8190 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008191 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008192 // that we can provide nifty diagnostics.
Richard Smithc2bebe92016-05-11 20:37:46 +00008193 FailedCandidates.addCandidate().set(
8194 I.getPair(), FunTmpl->getTemplatedDecl(),
8195 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008196 (void)TDK;
8197 continue;
8198 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008199
Artem Belevich64135c32016-12-08 19:38:13 +00008200 // Target attributes are part of the cuda function signature, so
8201 // the deduced template's cuda target must match that of the
8202 // specialization. Given that C++ template deduction does not
8203 // take target attributes into account, we reject candidates
8204 // here that have a different target.
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008205 if (LangOpts.CUDA &&
Artem Belevich64135c32016-12-08 19:38:13 +00008206 IdentifyCUDATarget(Specialization,
8207 /* IgnoreImplicitHDAttributes = */ true) !=
8208 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttributes = */ true)) {
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008209 FailedCandidates.addCandidate().set(
8210 I.getPair(), FunTmpl->getTemplatedDecl(),
8211 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
8212 continue;
8213 }
8214
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008215 // Record this candidate.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008216 if (ExplicitTemplateArgs)
8217 ConvertedTemplateArgs[Specialization] = std::move(Args);
John McCall58cc69d2010-01-27 01:50:18 +00008218 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008219 }
8220 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008221
Richard Smith8ce732b2019-01-07 06:00:46 +00008222 // For a qualified friend declaration (with no explicit marker to indicate
8223 // that a template specialization was intended), note all (template and
8224 // non-template) candidates.
8225 if (QualifiedFriend && Candidates.empty()) {
8226 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
8227 << FD->getDeclName() << FDLookupContext;
8228 // FIXME: We should form a single candidate list and diagnose all
8229 // candidates at once, to get proper sorting and limiting.
8230 for (auto *OldND : Previous) {
8231 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
8232 NoteOverloadCandidate(OldND, OldFD, FD->getType(), false);
8233 }
8234 FailedCandidates.NoteCandidates(*this, FD->getLocation());
8235 return true;
8236 }
8237
Douglas Gregor5de279c2009-09-26 03:41:46 +00008238 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008239 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith8ce732b2019-01-07 06:00:46 +00008240 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
Larisse Voufo98b20f12013-07-19 23:00:19 +00008241 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
8242 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00008243 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00008244 PDiag(diag::note_function_template_spec_matched));
8245
John McCall58cc69d2010-01-27 01:50:18 +00008246 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008247 return true;
John McCall58cc69d2010-01-27 01:50:18 +00008248
8249 // Ignore access information; it doesn't figure into redeclaration checking.
8250 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00008251
8252 FunctionTemplateSpecializationInfo *SpecInfo
8253 = Specialization->getTemplateSpecializationInfo();
8254 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00008255
8256 // Note: do not overwrite location info if previous template
8257 // specialization kind was explicit.
8258 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00008259 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00008260 Specialization->setLocation(FD->getLocation());
Richard Smith54f04402017-05-18 02:29:20 +00008261 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
Richard Smith5b8b3db2012-02-20 23:28:05 +00008262 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
8263 // function can differ from the template declaration with respect to
8264 // the constexpr specifier.
Richard Smith77e9e842017-05-09 23:02:10 +00008265 // FIXME: We need an update record for this AST mutation.
8266 // FIXME: What if there are multiple such prior declarations (for instance,
8267 // from different modules)?
Richard Smith5b8b3db2012-02-20 23:28:05 +00008268 Specialization->setConstexpr(FD->isConstexpr());
8269 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008270
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008271 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00008272 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00008273
8274 // If this is a friend declaration, then we're not really declaring
8275 // an explicit specialization.
8276 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008277
Douglas Gregor54888652009-10-07 00:13:32 +00008278 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00008279 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008280 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00008281 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008282 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00008283 false))
Douglas Gregor54888652009-10-07 00:13:32 +00008284 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00008285
8286 // C++ [temp.expl.spec]p6:
8287 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008288 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00008289 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008290 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00008291 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00008292 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00008293 if (!isFriend &&
8294 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00008295 TSK_ExplicitSpecialization,
8296 Specialization,
8297 SpecInfo->getTemplateSpecializationKind(),
8298 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008299 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00008300 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008301
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008302 // Mark the prior declaration as an explicit specialization, so that later
8303 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00008304 if (!isFriend) {
Faisal Vali81a88be2016-06-14 03:23:15 +00008305 // Since explicit specializations do not inherit '=delete' from their
8306 // primary function template - check if the 'specialization' that was
8307 // implicitly generated (during template argument deduction for partial
8308 // ordering) from the most specialized of all the function templates that
8309 // 'FD' could have been specializing, has a 'deleted' definition. If so,
8310 // first check that it was implicitly generated during template argument
8311 // deduction by making sure it wasn't referenced, and then reset the deleted
8312 // flag to not-deleted, so that we can inherit that information from 'FD'.
8313 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
8314 !Specialization->getCanonicalDecl()->isReferenced()) {
Richard Smith77e9e842017-05-09 23:02:10 +00008315 // FIXME: This assert will not hold in the presence of modules.
Faisal Vali81a88be2016-06-14 03:23:15 +00008316 assert(
8317 Specialization->getCanonicalDecl() == Specialization &&
8318 "This must be the only existing declaration of this specialization");
Richard Smith77e9e842017-05-09 23:02:10 +00008319 // FIXME: We need an update record for this AST mutation.
Faisal Vali81a88be2016-06-14 03:23:15 +00008320 Specialization->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008321 }
Richard Smith54f04402017-05-18 02:29:20 +00008322 // FIXME: We need an update record for this AST mutation.
John McCall816d75b2010-03-24 07:46:06 +00008323 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00008324 MarkUnusedFileScopedDecl(Specialization);
8325 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008326
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008327 // Turn the given function declaration into a function template
8328 // specialization, with the template arguments from the previous
8329 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008330 // Take copies of (semantic and syntactic) template argument lists.
8331 const TemplateArgumentList* TemplArgs = new (Context)
8332 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008333 FD->setFunctionTemplateSpecialization(
8334 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
8335 SpecInfo->getTemplateSpecializationKind(),
8336 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008337
Artem Belevich64135c32016-12-08 19:38:13 +00008338 // A function template specialization inherits the target attributes
8339 // of its template. (We require the attributes explicitly in the
8340 // code to match, but a template may have implicit attributes by
8341 // virtue e.g. of being constexpr, and it passes these implicit
8342 // attributes on to its specializations.)
8343 if (LangOpts.CUDA)
8344 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
8345
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008346 // The "previous declaration" for this function template specialization is
8347 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00008348 Previous.clear();
8349 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008350 return false;
8351}
8352
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008353/// Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008354/// specialization.
8355///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008356/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008357/// explicit member function specialization. On successful completion,
8358/// the function declaration \p FD will become a member function
8359/// specialization.
8360///
Douglas Gregor86d142a2009-10-08 07:24:58 +00008361/// \param Member the member declaration, which will be updated to become a
8362/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008363///
John McCall1f82f242009-11-18 22:49:29 +00008364/// \param Previous the set of declarations, one of which may be specialized
8365/// by this function specialization; the set will be modified to contain the
8366/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008367bool
John McCall1f82f242009-11-18 22:49:29 +00008368Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008369 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00008370
Douglas Gregor86d142a2009-10-08 07:24:58 +00008371 // Try to find the member we are instantiating.
Richard Smith22e7cc62016-05-24 00:01:49 +00008372 NamedDecl *FoundInstantiation = nullptr;
Craig Topperc3ec1492014-05-26 06:22:03 +00008373 NamedDecl *Instantiation = nullptr;
8374 NamedDecl *InstantiatedFrom = nullptr;
8375 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00008376
John McCall1f82f242009-11-18 22:49:29 +00008377 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008378 // Nowhere to look anyway.
8379 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008380 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8381 I != E; ++I) {
8382 NamedDecl *D = (*I)->getUnderlyingDecl();
8383 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00008384 QualType Adjusted = Function->getType();
8385 if (!hasExplicitCallingConv(Adjusted))
8386 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
Richard Smith4576a772018-09-10 06:35:32 +00008387 // This doesn't handle deduced return types, but both function
8388 // declarations should be undeduced at this point.
Rafael Espindola66747222013-12-10 00:59:31 +00008389 if (Context.hasSameType(Adjusted, Method->getType())) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008390 FoundInstantiation = *I;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008391 Instantiation = Method;
8392 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008393 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008394 break;
8395 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008396 }
8397 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00008398 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008399 VarDecl *PrevVar;
8400 if (Previous.isSingleResult() &&
8401 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00008402 if (PrevVar->isStaticDataMember()) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008403 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00008404 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008405 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008406 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008407 }
8408 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008409 CXXRecordDecl *PrevRecord;
8410 if (Previous.isSingleResult() &&
8411 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008412 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00008413 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008414 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008415 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008416 }
Richard Smith7d137e32012-03-23 03:33:32 +00008417 } else if (isa<EnumDecl>(Member)) {
8418 EnumDecl *PrevEnum;
8419 if (Previous.isSingleResult() &&
8420 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008421 FoundInstantiation = Previous.getRepresentativeDecl();
Richard Smith7d137e32012-03-23 03:33:32 +00008422 Instantiation = PrevEnum;
8423 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
8424 MSInfo = PrevEnum->getMemberSpecializationInfo();
8425 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008426 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008427
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008428 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008429 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008430 // specializations are always out-of-line, the caller will complain about
8431 // this mismatch later.
8432 return false;
8433 }
John McCalle820e5e2010-04-13 20:37:33 +00008434
Richard Smith77e9e842017-05-09 23:02:10 +00008435 // A member specialization in a friend declaration isn't really declaring
8436 // an explicit specialization, just identifying a specific (possibly implicit)
8437 // specialization. Don't change the template specialization kind.
8438 //
8439 // FIXME: Is this really valid? Other compilers reject.
John McCalle820e5e2010-04-13 20:37:33 +00008440 if (Member->getFriendObjectKind() != Decl::FOK_None) {
8441 // Preserve instantiation information.
8442 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
8443 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
8444 cast<CXXMethodDecl>(InstantiatedFrom),
8445 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
8446 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
8447 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
8448 cast<CXXRecordDecl>(InstantiatedFrom),
8449 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
8450 }
8451
8452 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00008453 Previous.addDecl(FoundInstantiation);
John McCalle820e5e2010-04-13 20:37:33 +00008454 return false;
8455 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008456
Douglas Gregor86d142a2009-10-08 07:24:58 +00008457 // Make sure that this is a specialization of a member.
8458 if (!InstantiatedFrom) {
8459 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
8460 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008461 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
8462 return true;
8463 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008464
Douglas Gregor06db9f52009-10-12 20:18:28 +00008465 // C++ [temp.expl.spec]p6:
8466 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00008467 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00008468 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008469 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00008470 // use occurs; no diagnostic is required.
8471 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00008472
Abramo Bagnara8075c852010-06-12 07:44:57 +00008473 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00008474 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
8475 TSK_ExplicitSpecialization,
8476 Instantiation,
8477 MSInfo->getTemplateSpecializationKind(),
8478 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008479 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00008480 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008481
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008482 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008483 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00008484 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008485 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00008486 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008487 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00008488
Richard Smith77e9e842017-05-09 23:02:10 +00008489 // Note that this member specialization is an "instantiation of" the
8490 // corresponding member of the original template.
8491 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008492 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
8493 if (InstantiationFunction->getTemplateSpecializationKind() ==
8494 TSK_ImplicitInstantiation) {
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008495 // Explicit specializations of member functions of class templates do not
8496 // inherit '=delete' from the member function they are specializing.
8497 if (InstantiationFunction->isDeleted()) {
Richard Smith77e9e842017-05-09 23:02:10 +00008498 // FIXME: This assert will not hold in the presence of modules.
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008499 assert(InstantiationFunction->getCanonicalDecl() ==
8500 InstantiationFunction);
Richard Smith77e9e842017-05-09 23:02:10 +00008501 // FIXME: We need an update record for this AST mutation.
Richard Smith5f274382016-09-28 23:55:27 +00008502 InstantiationFunction->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008503 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008504 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008505
Richard Smith77e9e842017-05-09 23:02:10 +00008506 MemberFunction->setInstantiationOfMemberFunction(
8507 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8508 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
8509 MemberVar->setInstantiationOfStaticDataMember(
Larisse Voufo39a1e502013-08-06 01:03:05 +00008510 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Richard Smith77e9e842017-05-09 23:02:10 +00008511 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
8512 MemberClass->setInstantiationOfMemberClass(
8513 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8514 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
8515 MemberEnum->setInstantiationOfMemberEnum(
Richard Smith7d137e32012-03-23 03:33:32 +00008516 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Richard Smith77e9e842017-05-09 23:02:10 +00008517 } else {
8518 llvm_unreachable("unknown member specialization kind");
Douglas Gregor86d142a2009-10-08 07:24:58 +00008519 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008520
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008521 // Save the caller the trouble of having to figure out which declaration
8522 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00008523 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00008524 Previous.addDecl(FoundInstantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008525 return false;
8526}
8527
Richard Smith77e9e842017-05-09 23:02:10 +00008528/// Complete the explicit specialization of a member of a class template by
8529/// updating the instantiated member to be marked as an explicit specialization.
8530///
8531/// \param OrigD The member declaration instantiated from the template.
8532/// \param Loc The location of the explicit specialization of the member.
8533template<typename DeclT>
8534static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
8535 SourceLocation Loc) {
8536 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
8537 return;
8538
8539 // FIXME: Inform AST mutation listeners of this AST mutation.
8540 // FIXME: If there are multiple in-class declarations of the member (from
8541 // multiple modules, or a declaration and later definition of a member type),
8542 // should we update all of them?
8543 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
8544 OrigD->setLocation(Loc);
8545}
8546
8547void Sema::CompleteMemberSpecialization(NamedDecl *Member,
8548 LookupResult &Previous) {
8549 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
8550 if (Instantiation == Member)
8551 return;
8552
8553 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
8554 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
8555 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
8556 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
8557 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
8558 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
8559 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
8560 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
8561 else
8562 llvm_unreachable("unknown member specialization kind");
8563}
8564
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008565/// Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008566///
8567/// \returns true if a serious error occurs, false otherwise.
8568static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00008569 SourceLocation InstLoc,
8570 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00008571 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
8572 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008573
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008574 if (CurContext->isRecord()) {
8575 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
8576 << D;
8577 return true;
8578 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008579
Richard Smith050d2612011-10-18 02:28:33 +00008580 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008581 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00008582 // template. If the name declared in the explicit instantiation is an
8583 // unqualified name, the explicit instantiation shall appear in the
8584 // namespace where its template is declared or, if that namespace is inline
8585 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008586 //
8587 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00008588 if (WasQualifiedName) {
8589 if (CurContext->Encloses(OrigContext))
8590 return false;
8591 } else {
8592 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
8593 return false;
8594 }
8595
8596 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
8597 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008598 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008599 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008600 diag::err_explicit_instantiation_out_of_scope :
8601 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008602 << D << NS;
8603 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008604 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008605 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008606 diag::err_explicit_instantiation_unqualified_wrong_namespace :
8607 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
8608 << D << NS;
8609 } else
8610 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008611 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008612 diag::err_explicit_instantiation_must_be_global :
8613 diag::warn_explicit_instantiation_must_be_global_0x)
8614 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00008615 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008616 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00008617}
8618
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008619/// Determine whether the given scope specifier has a template-id in it.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008620static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
8621 if (!SS.isSet())
8622 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008623
Richard Smith050d2612011-10-18 02:28:33 +00008624 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008625 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008626 // or a static data member of a class template specialization, the name of
8627 // the class template specialization in the qualified-id for the member
8628 // name shall be a simple-template-id.
8629 //
8630 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00008631 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
8632 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00008633 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00008634 if (isa<TemplateSpecializationType>(T))
8635 return true;
8636
8637 return false;
8638}
8639
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008640/// Make a dllexport or dllimport attr on a class template specialization take
8641/// effect.
8642static void dllExportImportClassTemplateSpecialization(
8643 Sema &S, ClassTemplateSpecializationDecl *Def) {
8644 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
8645 assert(A && "dllExportImportClassTemplateSpecialization called "
8646 "on Def without dllexport or dllimport");
8647
8648 // We reject explicit instantiations in class scope, so there should
8649 // never be any delayed exported classes to worry about.
8650 assert(S.DelayedDllExportClasses.empty() &&
8651 "delayed exports present at explicit instantiation");
8652 S.checkClassLevelDLLAttribute(Def);
8653
8654 // Propagate attribute to base class templates.
8655 for (auto &B : Def->bases()) {
8656 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
8657 B.getType()->getAsCXXRecordDecl()))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008658 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getBeginLoc());
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008659 }
8660
8661 S.referenceDLLExportedClassMethods();
8662}
8663
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008664// Explicit instantiation of a class template specialization
Erich Keanec480f302018-07-12 21:09:05 +00008665DeclResult Sema::ActOnExplicitInstantiation(
8666 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
8667 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
8668 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
8669 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
8670 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
Douglas Gregora1f49972009-05-13 00:25:59 +00008671 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00008672 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00008673 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00008674 // Check that the specialization uses the same tag kind as the
8675 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00008676 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8677 assert(Kind != TTK_Enum &&
8678 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00008679
Richard Trieu265c3442016-04-05 21:13:54 +00008680 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
8681
8682 if (!ClassTemplate) {
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00008683 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
8684 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
Richard Trieu265c3442016-04-05 21:13:54 +00008685 Diag(TD->getLocation(), diag::note_previous_use);
Richard Smith392497b2013-06-22 22:03:31 +00008686 return true;
8687 }
8688
Douglas Gregord9034f02009-05-14 16:41:31 +00008689 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00008690 Kind, /*isDefinition*/false, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00008691 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00008692 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00008693 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00008694 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00008695 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00008696 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00008697 diag::note_previous_use);
8698 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8699 }
8700
Douglas Gregore47f5a72009-10-14 23:41:34 +00008701 // C++0x [temp.explicit]p2:
8702 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008703 // definition and an explicit instantiation declaration. An explicit
8704 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00008705 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
8706 ? TSK_ExplicitInstantiationDefinition
8707 : TSK_ExplicitInstantiationDeclaration;
8708
8709 if (TSK == TSK_ExplicitInstantiationDeclaration) {
8710 // Check for dllexport class template instantiation declarations.
Erich Keanee891aa92018-07-13 15:07:47 +00008711 for (const ParsedAttr &AL : Attr) {
8712 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
Hans Wennborgfd76d912015-01-15 21:18:30 +00008713 Diag(ExternLoc,
8714 diag::warn_attribute_dllexport_explicit_instantiation_decl);
Erich Keanec480f302018-07-12 21:09:05 +00008715 Diag(AL.getLoc(), diag::note_attribute);
Hans Wennborgfd76d912015-01-15 21:18:30 +00008716 break;
8717 }
8718 }
8719
8720 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
8721 Diag(ExternLoc,
8722 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8723 Diag(A->getLocation(), diag::note_attribute);
8724 }
8725 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008726
Hans Wennborga86a83b2016-05-26 19:42:56 +00008727 // In MSVC mode, dllimported explicit instantiation definitions are treated as
8728 // instantiation declarations for most purposes.
8729 bool DLLImportExplicitInstantiationDef = false;
8730 if (TSK == TSK_ExplicitInstantiationDefinition &&
8731 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
8732 // Check for dllimport class template instantiation definitions.
8733 bool DLLImport =
8734 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
Erich Keanee891aa92018-07-13 15:07:47 +00008735 for (const ParsedAttr &AL : Attr) {
8736 if (AL.getKind() == ParsedAttr::AT_DLLImport)
Hans Wennborga86a83b2016-05-26 19:42:56 +00008737 DLLImport = true;
Erich Keanee891aa92018-07-13 15:07:47 +00008738 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
Hans Wennborga86a83b2016-05-26 19:42:56 +00008739 // dllexport trumps dllimport here.
8740 DLLImport = false;
8741 break;
8742 }
8743 }
8744 if (DLLImport) {
8745 TSK = TSK_ExplicitInstantiationDeclaration;
8746 DLLImportExplicitInstantiationDef = true;
8747 }
8748 }
8749
Douglas Gregora1f49972009-05-13 00:25:59 +00008750 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00008751 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00008752 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00008753
8754 // Check that the template argument list is well-formed for this
8755 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008756 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00008757 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
8758 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00008759 return true;
8760
Douglas Gregora1f49972009-05-13 00:25:59 +00008761 // Find the class template specialization declaration that
8762 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00008763 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00008764 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00008765 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00008766
Abramo Bagnara8075c852010-06-12 07:44:57 +00008767 TemplateSpecializationKind PrevDecl_TSK
8768 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
8769
Douglas Gregor54888652009-10-07 00:13:32 +00008770 // C++0x [temp.explicit]p2:
8771 // [...] An explicit instantiation shall appear in an enclosing
8772 // namespace of its template. [...]
8773 //
8774 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008775 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
8776 SS.isSet()))
8777 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008778
Craig Topperc3ec1492014-05-26 06:22:03 +00008779 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00008780
Abramo Bagnara8075c852010-06-12 07:44:57 +00008781 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00008782 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00008783 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00008784 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00008785 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008786 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00008787 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00008788
Abramo Bagnara8075c852010-06-12 07:44:57 +00008789 // Even though HasNoEffect == true means that this explicit instantiation
8790 // has no effect on semantics, we go on to put its syntax in the AST.
8791
8792 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
8793 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008794 // Since the only prior class template specialization with these
8795 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00008796 // declaration node as our own, updating the source location
8797 // for the template name to reflect our new declaration.
8798 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008799 Specialization = PrevDecl;
8800 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00008801 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008802 }
Hans Wennborga86a83b2016-05-26 19:42:56 +00008803
8804 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
8805 DLLImportExplicitInstantiationDef) {
8806 // The new specialization might add a dllimport attribute.
8807 HasNoEffect = false;
8808 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00008809 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00008810
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008811 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00008812 // Create a new class template specialization declaration node for
8813 // this explicit specialization.
8814 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00008815 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00008816 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00008817 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00008818 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00008819 Converted,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008820 PrevDecl);
Bruno Ricci4224c872018-12-21 14:35:24 +00008821 SetNestedNameSpecifier(*this, Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00008822
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00008823 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00008824 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00008825 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008826 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008827 }
8828
8829 // Build the fully-sugared type for this explicit instantiation as
8830 // the user wrote in the explicit instantiation itself. This means
8831 // that we'll pretty-print the type retrieved from the
8832 // specialization's declaration the way that the user actually wrote
8833 // the explicit instantiation, rather than formatting the name based
8834 // on the "canonical" representation used to store the template
8835 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00008836 TypeSourceInfo *WrittenTy
8837 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
8838 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00008839 Context.getTypeDeclType(Specialization));
8840 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00008841
Abramo Bagnara8075c852010-06-12 07:44:57 +00008842 // Set source locations for keywords.
8843 Specialization->setExternLoc(ExternLoc);
8844 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00008845 Specialization->setBraceRange(SourceRange());
Abramo Bagnara8075c852010-06-12 07:44:57 +00008846
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00008847 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
Erich Keanec480f302018-07-12 21:09:05 +00008848 ProcessDeclAttributeList(S, Specialization, Attr);
Rafael Espindola0b062072012-01-03 06:04:21 +00008849
Abramo Bagnara8075c852010-06-12 07:44:57 +00008850 // Add the explicit instantiation into its lexical context. However,
8851 // since explicit instantiations are never found by name lookup, we
8852 // just put it into the declaration context directly.
8853 Specialization->setLexicalDeclContext(CurContext);
8854 CurContext->addDecl(Specialization);
8855
8856 // Syntax is now OK, so return if it has no other effect on semantics.
8857 if (HasNoEffect) {
8858 // Set the template specialization kind.
8859 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00008860 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00008861 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008862
8863 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00008864 // A definition of a class template or class member template
8865 // shall be in scope at the point of the explicit instantiation of
8866 // the class template or class member template.
8867 //
8868 // This check comes when we actually try to perform the
8869 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00008870 ClassTemplateSpecializationDecl *Def
8871 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008872 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00008873 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00008874 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008875 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00008876 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008877 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
8878 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00008879
Douglas Gregor1d957a32009-10-27 18:42:08 +00008880 // Instantiate the members of this class template specialization.
8881 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008882 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00008883 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008884 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008885 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
8886 // TSK_ExplicitInstantiationDefinition
8887 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborga86a83b2016-05-26 19:42:56 +00008888 (TSK == TSK_ExplicitInstantiationDefinition ||
8889 DLLImportExplicitInstantiationDef)) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00008890 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00008891 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00008892
Hans Wennborgc0875502015-06-09 00:39:05 +00008893 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
Shoaib Meenaiab3f96c2016-11-09 23:52:20 +00008894 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8895 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
Hans Wennborgc0875502015-06-09 00:39:05 +00008896 // In the MS ABI, an explicit instantiation definition can add a dll
8897 // attribute to a template with a previous instantiation declaration.
8898 // MinGW doesn't allow this.
Hans Wennborg17f9b442015-05-27 00:06:45 +00008899 auto *A = cast<InheritableAttr>(
8900 getDLLAttr(Specialization)->clone(getASTContext()));
8901 A->setInherited(true);
8902 Def->addAttr(A);
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008903 dllExportImportClassTemplateSpecialization(*this, Def);
Hans Wennborg17f9b442015-05-27 00:06:45 +00008904 }
8905 }
8906
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008907 // Fix a TSK_ImplicitInstantiation followed by a
8908 // TSK_ExplicitInstantiationDefinition
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00008909 bool NewlyDLLExported =
8910 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
8911 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008912 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8913 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
8914 // In the MS ABI, an explicit instantiation definition can add a dll
8915 // attribute to a template with a previous implicit instantiation.
8916 // MinGW doesn't allow this. We limit clang to only adding dllexport, to
8917 // avoid potentially strange codegen behavior. For example, if we extend
8918 // this conditional to dllimport, and we have a source file calling a
8919 // method on an implicitly instantiated template class instance and then
8920 // declaring a dllimport explicit instantiation definition for the same
8921 // template class, the codegen for the method call will not respect the
8922 // dllimport, while it will with cl. The Def will already have the DLL
8923 // attribute, since the Def and Specialization will be the same in the
8924 // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
8925 // attribute to the Specialization; we just need to make it take effect.
8926 assert(Def == Specialization &&
8927 "Def and Specialization should match for implicit instantiation");
8928 dllExportImportClassTemplateSpecialization(*this, Def);
8929 }
8930
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00008931 // Set the template specialization kind. Make sure it is set before
8932 // instantiating the members which will trigger ASTConsumer callbacks.
8933 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregor12e49d32009-10-15 22:53:21 +00008934 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00008935 } else {
8936
8937 // Set the template specialization kind.
8938 Specialization->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00008939 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008940
John McCall48871652010-08-21 09:40:31 +00008941 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00008942}
8943
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008944// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00008945DeclResult
Erich Keanec480f302018-07-12 21:09:05 +00008946Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
8947 SourceLocation TemplateLoc, unsigned TagSpec,
8948 SourceLocation KWLoc, CXXScopeSpec &SS,
8949 IdentifierInfo *Name, SourceLocation NameLoc,
8950 const ParsedAttributesView &Attr) {
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008951
Douglas Gregord6ab8742009-05-28 23:31:59 +00008952 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00008953 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00008954 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00008955 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00008956 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00008957 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00008958 SourceLocation(), false, TypeResult(),
Akira Hatanaka12ddcee2017-06-26 18:46:12 +00008959 /*IsTypeSpecifier*/false,
8960 /*IsTemplateParamOrArg*/false);
John McCall7f41d982009-09-11 04:59:25 +00008961 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
8962
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008963 if (!TagD)
8964 return true;
8965
John McCall48871652010-08-21 09:40:31 +00008966 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00008967 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008968
Douglas Gregorb8006faf2009-05-27 17:30:49 +00008969 if (Tag->isInvalidDecl())
8970 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008971
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008972 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
8973 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
8974 if (!Pattern) {
8975 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
8976 << Context.getTypeDeclType(Record);
8977 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
8978 return true;
8979 }
8980
Douglas Gregore47f5a72009-10-14 23:41:34 +00008981 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008982 // If the explicit instantiation is for a class or member class, the
8983 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00008984 // simple-template-id.
8985 //
8986 // C++98 has the same restriction, just worded differently.
8987 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00008988 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008989 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008990
Douglas Gregore47f5a72009-10-14 23:41:34 +00008991 // C++0x [temp.explicit]p2:
8992 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008993 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00008994 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00008995 TemplateSpecializationKind TSK
8996 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8997 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008998
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008999 // C++0x [temp.explicit]p2:
9000 // [...] An explicit instantiation shall appear in an enclosing
9001 // namespace of its template. [...]
9002 //
9003 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00009004 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009005
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009006 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009007 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00009008 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009009 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00009010 PrevDecl = Record;
9011 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009012 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00009013 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009014 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009015 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009016 PrevDecl,
9017 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009018 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00009019 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009020 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00009021 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009022 return TagD;
9023 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009024
Douglas Gregor12e49d32009-10-15 22:53:21 +00009025 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009026 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00009027 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00009028 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009029 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00009030 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009031 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009032 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00009033 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00009034 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
9035 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00009036 Diag(Pattern->getLocation(), diag::note_forward_declaration)
9037 << Pattern;
9038 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00009039 } else {
9040 if (InstantiateClass(NameLoc, Record, Def,
9041 getTemplateInstantiationArgs(Record),
9042 TSK))
9043 return true;
9044
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009045 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00009046 if (!RecordDef)
9047 return true;
9048 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009049 }
9050
Douglas Gregor1d957a32009-10-27 18:42:08 +00009051 // Instantiate all of the members of the class.
9052 InstantiateClassMembers(NameLoc, RecordDef,
9053 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009054
Douglas Gregor88d292c2010-05-13 16:44:06 +00009055 if (TSK == TSK_ExplicitInstantiationDefinition)
9056 MarkVTableUsed(NameLoc, RecordDef, true);
9057
Mike Stump87c57ac2009-05-16 07:39:55 +00009058 // FIXME: We don't have any representation for explicit instantiations of
9059 // member classes. Such a representation is not needed for compilation, but it
9060 // should be available for clients that want to see all of the declarations in
9061 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009062 return TagD;
9063}
9064
John McCallfaf5fb42010-08-26 23:41:50 +00009065DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
9066 SourceLocation ExternLoc,
9067 SourceLocation TemplateLoc,
9068 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00009069 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009070 // TODO: check if/when DNInfo should replace Name.
9071 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9072 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00009073 if (!Name) {
9074 if (!D.isInvalidType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009075 Diag(D.getDeclSpec().getBeginLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00009076 diag::err_explicit_instantiation_requires_name)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009077 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009078
Douglas Gregor450f00842009-09-25 18:43:00 +00009079 return true;
9080 }
9081
9082 // The scope passed in may not be a decl scope. Zip up the scope tree until
9083 // we find one that is.
9084 while ((S->getFlags() & Scope::DeclScope) == 0 ||
9085 (S->getFlags() & Scope::TemplateParamScope) != 0)
9086 S = S->getParent();
9087
9088 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00009089 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
9090 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00009091 if (R.isNull())
9092 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009093
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009094 // C++ [dcl.stc]p1:
Simon Pilgrim6905d222016-12-30 22:55:33 +00009095 // A storage-class-specifier shall not be specified in [...] an explicit
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009096 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00009097 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00009098 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
9099 << Name;
9100 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009101 } else if (D.getDeclSpec().getStorageClassSpec()
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009102 != DeclSpec::SCS_unspecified) {
9103 // Complain about then remove the storage class specifier.
9104 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
9105 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009106
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009107 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00009108 }
9109
Douglas Gregor3c74d412009-10-14 20:14:33 +00009110 // C++0x [temp.explicit]p1:
9111 // [...] An explicit instantiation of a function template shall not use the
9112 // inline or constexpr specifiers.
9113 // Presumably, this also applies to member functions of class templates as
9114 // well.
Richard Smith83c19292011-10-18 03:44:03 +00009115 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009116 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009117 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00009118 diag::err_explicit_instantiation_inline :
9119 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00009120 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00009121 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00009122 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
9123 // not already specified.
9124 Diag(D.getDeclSpec().getConstexprSpecLoc(),
9125 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009126
Richard Smith19a311a2017-02-09 22:47:51 +00009127 // A deduction guide is not on the list of entities that can be explicitly
9128 // instantiated.
9129 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009130 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
9131 << /*explicit instantiation*/ 0;
Richard Smith19a311a2017-02-09 22:47:51 +00009132 return true;
9133 }
9134
Douglas Gregore47f5a72009-10-14 23:41:34 +00009135 // C++0x [temp.explicit]p2:
9136 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009137 // definition and an explicit instantiation declaration. An explicit
9138 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00009139 TemplateSpecializationKind TSK
9140 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
9141 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009142
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009143 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00009144 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00009145
9146 if (!R->isFunctionType()) {
9147 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009148 // A [...] static data member of a class template can be explicitly
9149 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00009150 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00009151 // C++1y [temp.explicit]p1:
9152 // A [...] variable [...] template specialization can be explicitly
9153 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00009154 if (Previous.isAmbiguous())
9155 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009156
John McCall67c00872009-12-02 08:25:40 +00009157 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00009158 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009159
Larisse Voufo39a1e502013-08-06 01:03:05 +00009160 if (!PrevTemplate) {
9161 if (!Prev || !Prev->isStaticDataMember()) {
9162 // We expect to see a data data member here.
9163 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
9164 << Name;
9165 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9166 P != PEnd; ++P)
9167 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
9168 return true;
9169 }
9170
9171 if (!Prev->getInstantiatedFromStaticDataMember()) {
9172 // FIXME: Check for explicit specialization?
9173 Diag(D.getIdentifierLoc(),
9174 diag::err_explicit_instantiation_data_member_not_instantiated)
9175 << Prev;
9176 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
9177 // FIXME: Can we provide a note showing where this was declared?
9178 return true;
9179 }
9180 } else {
9181 // Explicitly instantiate a variable template.
9182
9183 // C++1y [dcl.spec.auto]p6:
9184 // ... A program that uses auto or decltype(auto) in a context not
9185 // explicitly allowed in this section is ill-formed.
9186 //
9187 // This includes auto-typed variable template instantiations.
9188 if (R->isUndeducedType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009189 Diag(T->getTypeLoc().getBeginLoc(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00009190 diag::err_auto_not_allowed_var_inst);
9191 return true;
9192 }
9193
Faisal Vali2ab8c152017-12-30 04:15:27 +00009194 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
Richard Smithef985ac2013-09-18 02:10:12 +00009195 // C++1y [temp.explicit]p3:
9196 // If the explicit instantiation is for a variable, the unqualified-id
9197 // in the declaration shall be a template-id.
9198 Diag(D.getIdentifierLoc(),
9199 diag::err_explicit_instantiation_without_template_id)
9200 << PrevTemplate;
9201 Diag(PrevTemplate->getLocation(),
9202 diag::note_explicit_instantiation_here);
9203 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00009204 }
9205
Richard Smithef985ac2013-09-18 02:10:12 +00009206 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00009207 TemplateArgumentListInfo TemplateArgs =
9208 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00009209
Larisse Voufo39a1e502013-08-06 01:03:05 +00009210 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
9211 D.getIdentifierLoc(), TemplateArgs);
9212 if (Res.isInvalid())
9213 return true;
9214
9215 // Ignore access control bits, we don't need them for redeclaration
9216 // checking.
9217 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00009218 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009219
Douglas Gregore47f5a72009-10-14 23:41:34 +00009220 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009221 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00009222 // or a static data member of a class template specialization, the name of
9223 // the class template specialization in the qualified-id for the member
9224 // name shall be a simple-template-id.
9225 //
9226 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00009227 //
Richard Smith5977d872013-09-18 21:55:14 +00009228 // This does not apply to variable template specializations, where the
9229 // template-id is in the unqualified-id instead.
9230 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009231 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00009232 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00009233 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009234
Douglas Gregore47f5a72009-10-14 23:41:34 +00009235 // Check the scope of this explicit instantiation.
9236 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009237
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009238 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00009239 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
9240 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00009241 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00009242 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00009243 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009244 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009245
Larisse Voufo39a1e502013-08-06 01:03:05 +00009246 if (!HasNoEffect) {
9247 // Instantiate static data member or variable template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00009248 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Louis Dionnee6e81752018-10-10 15:32:29 +00009249 // Merge attributes.
9250 ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
Larisse Voufo39a1e502013-08-06 01:03:05 +00009251 if (TSK == TSK_ExplicitInstantiationDefinition)
9252 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
9253 }
9254
9255 // Check the new variable specialization against the parsed input.
9256 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009257 Diag(T->getTypeLoc().getBeginLoc(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00009258 diag::err_invalid_var_template_spec_type)
9259 << 0 << PrevTemplate << R << Prev->getType();
9260 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
9261 << 2 << PrevTemplate->getDeclName();
9262 return true;
9263 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009264
Douglas Gregor450f00842009-09-25 18:43:00 +00009265 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00009266 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009267 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009268
9269 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00009270 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00009271 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00009272 TemplateArgumentListInfo TemplateArgs;
Faisal Vali2ab8c152017-12-30 04:15:27 +00009273 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00009274 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00009275 HasExplicitTemplateArgs = true;
9276 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009277
Douglas Gregor450f00842009-09-25 18:43:00 +00009278 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009279 // A [...] function [...] can be explicitly instantiated from its template.
9280 // A member function [...] of a class template can be explicitly
9281 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00009282 // template.
John McCall27c11dd2017-06-07 23:00:05 +00009283 UnresolvedSet<8> TemplateMatches;
9284 FunctionDecl *NonTemplateMatch = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009285 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00009286 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9287 P != PEnd; ++P) {
9288 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00009289 if (!HasExplicitTemplateArgs) {
9290 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Richard Smithbaa47832016-12-01 02:11:49 +00009291 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
9292 /*AdjustExceptionSpec*/true);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00009293 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
John McCall27c11dd2017-06-07 23:00:05 +00009294 if (Method->getPrimaryTemplate()) {
9295 TemplateMatches.addDecl(Method, P.getAccess());
9296 } else {
9297 // FIXME: Can this assert ever happen? Needs a test.
9298 assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
9299 NonTemplateMatch = Method;
9300 }
Douglas Gregord90fd522009-09-25 21:45:23 +00009301 }
Douglas Gregor450f00842009-09-25 18:43:00 +00009302 }
9303 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009304
Douglas Gregor450f00842009-09-25 18:43:00 +00009305 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
9306 if (!FunTmpl)
9307 continue;
9308
Larisse Voufo98b20f12013-07-19 23:00:19 +00009309 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00009310 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009311 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009312 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00009313 (HasExplicitTemplateArgs ? &TemplateArgs
9314 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00009315 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009316 // Keep track of almost-matches.
9317 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +00009318 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +00009319 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00009320 (void)TDK;
9321 continue;
9322 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009323
Artem Belevich64135c32016-12-08 19:38:13 +00009324 // Target attributes are part of the cuda function signature, so
9325 // the cuda target of the instantiated function must match that of its
9326 // template. Given that C++ template deduction does not take
9327 // target attributes into account, we reject candidates here that
9328 // have a different target.
9329 if (LangOpts.CUDA &&
9330 IdentifyCUDATarget(Specialization,
9331 /* IgnoreImplicitHDAttributes = */ true) !=
Erich Keanec480f302018-07-12 21:09:05 +00009332 IdentifyCUDATarget(D.getDeclSpec().getAttributes())) {
Artem Belevich64135c32016-12-08 19:38:13 +00009333 FailedCandidates.addCandidate().set(
9334 P.getPair(), FunTmpl->getTemplatedDecl(),
9335 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
9336 continue;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00009337 }
9338
John McCall27c11dd2017-06-07 23:00:05 +00009339 TemplateMatches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00009340 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009341
John McCall27c11dd2017-06-07 23:00:05 +00009342 FunctionDecl *Specialization = NonTemplateMatch;
9343 if (!Specialization) {
9344 // Find the most specialized function template specialization.
9345 UnresolvedSetIterator Result = getMostSpecialized(
9346 TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
9347 D.getIdentifierLoc(),
9348 PDiag(diag::err_explicit_instantiation_not_known) << Name,
9349 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
9350 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00009351
John McCall27c11dd2017-06-07 23:00:05 +00009352 if (Result == TemplateMatches.end())
9353 return true;
John McCall58cc69d2010-01-27 01:50:18 +00009354
John McCall27c11dd2017-06-07 23:00:05 +00009355 // Ignore access control bits, we don't need them for redeclaration checking.
9356 Specialization = cast<FunctionDecl>(*Result);
9357 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009358
Alexey Bataev73983912014-11-06 10:10:50 +00009359 // C++11 [except.spec]p4
9360 // In an explicit instantiation an exception-specification may be specified,
9361 // but is not required.
9362 // If an exception-specification is specified in an explicit instantiation
9363 // directive, it shall be compatible with the exception-specifications of
9364 // other declarations of that function.
9365 if (auto *FPT = R->getAs<FunctionProtoType>())
9366 if (FPT->hasExceptionSpec()) {
9367 unsigned DiagID =
9368 diag::err_mismatched_exception_spec_explicit_instantiation;
9369 if (getLangOpts().MicrosoftExt)
9370 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
9371 bool Result = CheckEquivalentExceptionSpec(
9372 PDiag(DiagID) << Specialization->getType(),
9373 PDiag(diag::note_explicit_instantiation_here),
9374 Specialization->getType()->getAs<FunctionProtoType>(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009375 Specialization->getLocation(), FPT, D.getBeginLoc());
Alexey Bataev73983912014-11-06 10:10:50 +00009376 // In Microsoft mode, mismatching exception specifications just cause a
9377 // warning.
9378 if (!getLangOpts().MicrosoftExt && Result)
9379 return true;
9380 }
9381
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009382 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009383 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00009384 diag::err_explicit_instantiation_member_function_not_instantiated)
9385 << Specialization
9386 << (Specialization->getTemplateSpecializationKind() ==
9387 TSK_ExplicitSpecialization);
9388 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
9389 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009390 }
9391
Douglas Gregorec9fd132012-01-14 16:38:05 +00009392 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00009393 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
9394 PrevDecl = Specialization;
9395
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009396 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00009397 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00009398 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009399 PrevDecl,
9400 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009401 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00009402 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009403 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009404
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009405 // FIXME: We may still want to build some representation of this
9406 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00009407 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00009408 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009409 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00009410
Erich Keanec480f302018-07-12 21:09:05 +00009411 ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009412
Hans Wennborgb8304a62017-11-29 23:44:11 +00009413 // In MSVC mode, dllimported explicit instantiation definitions are treated as
9414 // instantiation declarations.
9415 if (TSK == TSK_ExplicitInstantiationDefinition &&
9416 Specialization->hasAttr<DLLImportAttr>() &&
9417 Context.getTargetInfo().getCXXABI().isMicrosoft())
9418 TSK = TSK_ExplicitInstantiationDeclaration;
9419
9420 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9421
Richard Smitheb36ddf2014-04-24 22:45:46 +00009422 if (Specialization->isDefined()) {
9423 // Let the ASTConsumer know that this function has been explicitly
9424 // instantiated now, and its linkage might have changed.
9425 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
9426 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00009427 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009428
Douglas Gregore47f5a72009-10-14 23:41:34 +00009429 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009430 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00009431 // or a static data member of a class template specialization, the name of
9432 // the class template specialization in the qualified-id for the member
9433 // name shall be a simple-template-id.
9434 //
9435 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009436 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Faisal Vali2ab8c152017-12-30 04:15:27 +00009437 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009438 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00009439 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009440 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00009441 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00009442 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009443
Douglas Gregore47f5a72009-10-14 23:41:34 +00009444 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009445 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregore47f5a72009-10-14 23:41:34 +00009446 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009447 D.getIdentifierLoc(),
Douglas Gregore47f5a72009-10-14 23:41:34 +00009448 D.getCXXScopeSpec().isSet());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009449
Douglas Gregor450f00842009-09-25 18:43:00 +00009450 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00009451 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009452}
9453
John McCallfaf5fb42010-08-26 23:41:50 +00009454TypeResult
Faisal Vali090da2d2018-01-01 18:23:28 +00009455Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
John McCall7f41d982009-09-11 04:59:25 +00009456 const CXXScopeSpec &SS, IdentifierInfo *Name,
9457 SourceLocation TagLoc, SourceLocation NameLoc) {
9458 // This has to hold, because SS is expected to be defined.
9459 assert(Name && "Expected a name in a dependent tag");
9460
Aaron Ballman4a979672014-01-03 13:56:08 +00009461 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00009462 if (!NNS)
9463 return true;
9464
Abramo Bagnara6150c882010-05-11 21:36:43 +00009465 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00009466
Douglas Gregorba41d012010-04-24 16:38:41 +00009467 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
9468 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00009469 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00009470 return true;
9471 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00009472
Douglas Gregore7c20652011-03-02 00:47:37 +00009473 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00009474 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00009475 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009476
Douglas Gregore7c20652011-03-02 00:47:37 +00009477 // Create type-source location information for this type.
9478 TypeLocBuilder TLB;
9479 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009480 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00009481 TL.setQualifierLoc(SS.getWithLocInContext(Context));
9482 TL.setNameLoc(NameLoc);
9483 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00009484}
9485
John McCallfaf5fb42010-08-26 23:41:50 +00009486TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009487Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
9488 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00009489 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009490 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00009491 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009492
Richard Smith0bf8a4922011-10-18 20:49:44 +00009493 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9494 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009495 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00009496 diag::warn_cxx98_compat_typename_outside_of_template :
9497 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009498 << FixItHint::CreateRemoval(TypenameLoc);
9499
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009500 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00009501 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
9502 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00009503 if (T.isNull())
9504 return true;
John McCall99b2fe52010-04-29 23:50:39 +00009505
9506 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9507 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00009508 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009509 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009510 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00009511 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00009512 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00009513 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009514 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009515 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00009516 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00009517 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009518
John McCallba7bf592010-08-24 05:47:05 +00009519 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00009520}
9521
John McCallfaf5fb42010-08-26 23:41:50 +00009522TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009523Sema::ActOnTypenameType(Scope *S,
9524 SourceLocation TypenameLoc,
9525 const CXXScopeSpec &SS,
9526 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00009527 TemplateTy TemplateIn,
Richard Smith74f02342017-01-19 21:00:13 +00009528 IdentifierInfo *TemplateII,
9529 SourceLocation TemplateIILoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00009530 SourceLocation LAngleLoc,
9531 ASTTemplateArgsPtr TemplateArgsIn,
9532 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00009533 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9534 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009535 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00009536 diag::warn_cxx98_compat_typename_outside_of_template :
9537 diag::ext_typename_outside_of_template)
9538 << FixItHint::CreateRemoval(TypenameLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009539
Richard Smith74f02342017-01-19 21:00:13 +00009540 // Strangely, non-type results are not ignored by this lookup, so the
9541 // program is ill-formed if it finds an injected-class-name.
Richard Smith62559bd2017-02-01 21:36:38 +00009542 if (TypenameLoc.isValid()) {
9543 auto *LookupRD =
9544 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
9545 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
9546 Diag(TemplateIILoc,
9547 diag::ext_out_of_line_qualified_id_type_names_constructor)
9548 << TemplateII << 0 /*injected-class-name used as template name*/
9549 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
9550 }
Richard Smith74f02342017-01-19 21:00:13 +00009551 }
9552
Douglas Gregorb09518c2011-02-27 22:46:49 +00009553 // Translate the parser's template argument list in our AST format.
9554 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9555 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009556
Douglas Gregorb09518c2011-02-27 22:46:49 +00009557 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009558 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
9559 // Construct a dependent template specialization type.
9560 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00009561 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009562 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
9563 DTN->getQualifier(),
9564 DTN->getIdentifier(),
9565 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009566
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009567 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00009568 TypeLocBuilder Builder;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009569 DependentTemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009570 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009571 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
9572 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00009573 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00009574 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009575 SpecTL.setLAngleLoc(LAngleLoc);
9576 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009577 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9578 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009579 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00009580 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009581
Richard Smith74f02342017-01-19 21:00:13 +00009582 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009583 if (T.isNull())
9584 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009585
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009586 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00009587 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009588 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009589 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009590 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00009591 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009592 SpecTL.setLAngleLoc(LAngleLoc);
9593 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009594 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9595 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009596
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009597 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
9598 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009599 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009600 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Simon Pilgrim6905d222016-12-30 22:55:33 +00009601
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009602 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
9603 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00009604}
9605
Douglas Gregorb09518c2011-02-27 22:46:49 +00009606
Richard Smith6f8d2c62012-05-09 05:17:00 +00009607/// Determine whether this failed name lookup should be treated as being
9608/// disabled by a usage of std::enable_if.
9609static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009610 SourceRange &CondRange, Expr *&Cond) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00009611 // We must be looking for a ::type...
9612 if (!II.isStr("type"))
9613 return false;
9614
9615 // ... within an explicitly-written template specialization...
9616 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
9617 return false;
9618 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00009619 TemplateSpecializationTypeLoc EnableIfTSTLoc =
9620 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
9621 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00009622 return false;
George Burgess IV00f70bd2018-03-01 05:43:23 +00009623 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009624
9625 // ... which names a complete class template declaration...
9626 const TemplateDecl *EnableIfDecl =
9627 EnableIfTST->getTemplateName().getAsTemplateDecl();
9628 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
9629 return false;
9630
9631 // ... called "enable_if".
9632 const IdentifierInfo *EnableIfII =
9633 EnableIfDecl->getDeclName().getAsIdentifierInfo();
9634 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
9635 return false;
9636
9637 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00009638 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009639
9640 // Dig out the condition.
9641 Cond = nullptr;
9642 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
9643 != TemplateArgument::Expression)
9644 return true;
9645
9646 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
9647
9648 // Ignore Boolean literals; they add no value.
9649 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
9650 Cond = nullptr;
9651
Richard Smith6f8d2c62012-05-09 05:17:00 +00009652 return true;
9653}
9654
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009655/// Build the type that describes a C++ typename specifier,
Douglas Gregor333489b2009-03-27 23:10:48 +00009656/// e.g., "typename T::type".
9657QualType
Simon Pilgrim6905d222016-12-30 22:55:33 +00009658Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009659 SourceLocation KeywordLoc,
Simon Pilgrim6905d222016-12-30 22:55:33 +00009660 NestedNameSpecifierLoc QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009661 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00009662 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00009663 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009664 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00009665
John McCall0b66eb32010-05-01 00:40:08 +00009666 DeclContext *Ctx = computeDeclContext(SS);
9667 if (!Ctx) {
9668 // If the nested-name-specifier is dependent and couldn't be
9669 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009670 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009671 return Context.getDependentNameType(Keyword,
9672 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009673 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00009674 }
Douglas Gregor333489b2009-03-27 23:10:48 +00009675
John McCall0b66eb32010-05-01 00:40:08 +00009676 // If the nested-name-specifier refers to the current instantiation,
9677 // the "typename" keyword itself is superfluous. In C++03, the
9678 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
9679 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00009680 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00009681
John McCall0b66eb32010-05-01 00:40:08 +00009682 if (RequireCompleteDeclContext(SS, Ctx))
9683 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00009684
9685 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00009686 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00009687 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00009688 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00009689 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00009690 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00009691 case LookupResult::NotFound: {
9692 // If we're looking up 'type' within a template named 'enable_if', produce
9693 // a more specific diagnostic.
9694 SourceRange CondRange;
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009695 Expr *Cond = nullptr;
9696 if (isEnableIf(QualifierLoc, II, CondRange, Cond)) {
9697 // If we have a condition, narrow it down to the specific failed
9698 // condition.
9699 if (Cond) {
9700 Expr *FailedCond;
9701 std::string FailedDescription;
9702 std::tie(FailedCond, FailedDescription) =
Clement Courbetf44c6f42018-12-11 08:39:11 +00009703 findFailedBooleanCondition(Cond);
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009704
9705 Diag(FailedCond->getExprLoc(),
9706 diag::err_typename_nested_not_found_requirement)
9707 << FailedDescription
9708 << FailedCond->getSourceRange();
9709 return QualType();
9710 }
9711
Richard Smith6f8d2c62012-05-09 05:17:00 +00009712 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009713 << Ctx << CondRange;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009714 return QualType();
9715 }
9716
Douglas Gregore40876a2009-10-13 21:16:44 +00009717 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00009718 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009719 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009720
9721 case LookupResult::FoundUnresolvedValue: {
9722 // We found a using declaration that is a value. Most likely, the using
9723 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009724 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009725 IILoc);
9726 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
9727 << Name << Ctx << FullRange;
9728 if (UnresolvedUsingValueDecl *Using
9729 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009730 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009731 Diag(Loc, diag::note_using_value_decl_missing_typename)
9732 << FixItHint::CreateInsertion(Loc, "typename ");
9733 }
9734 }
9735 // Fall through to create a dependent typename type, from which we can recover
9736 // better.
Galina Kistanova3779cb32017-06-07 06:25:05 +00009737 LLVM_FALLTHROUGH;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009738
Douglas Gregord0d2ee02010-01-15 01:44:47 +00009739 case LookupResult::NotFoundInCurrentInstantiation:
9740 // Okay, it's a member of an unknown instantiation.
Simon Pilgrim6905d222016-12-30 22:55:33 +00009741 return Context.getDependentNameType(Keyword,
9742 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009743 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00009744
9745 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009746 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Richard Smith74f02342017-01-19 21:00:13 +00009747 // C++ [class.qual]p2:
9748 // In a lookup in which function names are not ignored and the
9749 // nested-name-specifier nominates a class C, if the name specified
9750 // after the nested-name-specifier, when looked up in C, is the
9751 // injected-class-name of C [...] then the name is instead considered
9752 // to name the constructor of class C.
9753 //
9754 // Unlike in an elaborated-type-specifier, function names are not ignored
9755 // in typename-specifier lookup. However, they are ignored in all the
9756 // contexts where we form a typename type with no keyword (that is, in
9757 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
9758 //
9759 // FIXME: That's not strictly true: mem-initializer-id lookup does not
9760 // ignore functions, but that appears to be an oversight.
9761 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
9762 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
9763 if (Keyword == ETK_Typename && LookupRD && FoundRD &&
9764 FoundRD->isInjectedClassName() &&
9765 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
9766 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
9767 << &II << 1 << 0 /*'typename' keyword used*/;
9768
Abramo Bagnara6150c882010-05-11 21:36:43 +00009769 // We found a type. Build an ElaboratedType, since the
9770 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00009771 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Richard Smith74f02342017-01-19 21:00:13 +00009772 return Context.getElaboratedType(Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009773 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00009774 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00009775 }
9776
Richard Smithee579842017-01-30 20:39:26 +00009777 // C++ [dcl.type.simple]p2:
9778 // A type-specifier of the form
9779 // typename[opt] nested-name-specifier[opt] template-name
9780 // is a placeholder for a deduced class type [...].
Aaron Ballmanc351fba2017-12-04 20:27:34 +00009781 if (getLangOpts().CPlusPlus17) {
Richard Smithee579842017-01-30 20:39:26 +00009782 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
9783 return Context.getElaboratedType(
9784 Keyword, QualifierLoc.getNestedNameSpecifier(),
9785 Context.getDeducedTemplateSpecializationType(TemplateName(TD),
9786 QualType(), false));
9787 }
9788 }
Richard Smith600b5262017-01-26 20:40:47 +00009789
Douglas Gregor333489b2009-03-27 23:10:48 +00009790 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00009791 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00009792 break;
9793
9794 case LookupResult::FoundOverloaded:
9795 DiagID = diag::err_typename_nested_not_type;
9796 Referenced = *Result.begin();
9797 break;
9798
John McCall6538c932009-10-10 05:48:19 +00009799 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00009800 return QualType();
9801 }
9802
9803 // If we get here, it's because name lookup did not find a
9804 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009805 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00009806 IILoc);
9807 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00009808 if (Referenced)
9809 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
9810 << Name;
9811 return QualType();
9812}
Douglas Gregor15acfb92009-08-06 16:20:37 +00009813
9814namespace {
9815 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00009816 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00009817 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00009818 SourceLocation Loc;
9819 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00009820
Douglas Gregor15acfb92009-08-06 16:20:37 +00009821 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00009822 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009823
Mike Stump11289f42009-09-09 15:08:12 +00009824 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00009825 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00009826 DeclarationName Entity)
9827 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00009828 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00009829
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009830 /// Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00009831 /// transformed.
9832 ///
9833 /// For the purposes of type reconstruction, a type has already been
9834 /// transformed if it is NULL or if it is not dependent.
9835 bool AlreadyTransformed(QualType T) {
9836 return T.isNull() || !T->isDependentType();
9837 }
Mike Stump11289f42009-09-09 15:08:12 +00009838
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009839 /// Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00009840 /// rebuilt.
9841 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00009842
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009843 /// Returns the name of the entity whose type is being rebuilt.
Douglas Gregor15acfb92009-08-06 16:20:37 +00009844 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00009845
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009846 /// Sets the "base" location and entity when that
Douglas Gregoref6ab412009-10-27 06:26:26 +00009847 /// information is known based on another transformation.
9848 void setBase(SourceLocation Loc, DeclarationName Entity) {
9849 this->Loc = Loc;
9850 this->Entity = Entity;
9851 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009852
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00009853 ExprResult TransformLambdaExpr(LambdaExpr *E) {
9854 // Lambdas never need to be transformed.
9855 return E;
9856 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00009857 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009858} // end anonymous namespace
Douglas Gregor15acfb92009-08-06 16:20:37 +00009859
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009860/// Rebuilds a type within the context of the current instantiation.
Douglas Gregor15acfb92009-08-06 16:20:37 +00009861///
Mike Stump11289f42009-09-09 15:08:12 +00009862/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00009863/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00009864/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00009865/// partial specialization thereof). This routine will rebuild that type now
9866/// that we have entered the declarator's scope, which may produce different
9867/// canonical types, e.g.,
9868///
9869/// \code
9870/// template<typename T>
9871/// struct X {
9872/// typedef T* pointer;
9873/// pointer data();
9874/// };
9875///
9876/// template<typename T>
9877/// typename X<T>::pointer X<T>::data() { ... }
9878/// \endcode
9879///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00009880/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00009881/// since we do not know that we can look into X<T> when we parsed the type.
9882/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00009883/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00009884/// as the canonical type of T*, allowing the return types of the out-of-line
9885/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00009886TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
9887 SourceLocation Loc,
9888 DeclarationName Name) {
9889 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00009890 return T;
Mike Stump11289f42009-09-09 15:08:12 +00009891
Douglas Gregor15acfb92009-08-06 16:20:37 +00009892 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
9893 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00009894}
Douglas Gregorbe999392009-09-15 16:23:51 +00009895
John McCalldadc5752010-08-24 06:29:42 +00009896ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00009897 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
9898 DeclarationName());
9899 return Rebuilder.TransformExpr(E);
9900}
9901
John McCall99b2fe52010-04-29 23:50:39 +00009902bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00009903 if (SS.isInvalid())
Douglas Gregor10176412011-02-25 16:07:42 +00009904 return true;
John McCall2408e322010-04-27 00:57:59 +00009905
Douglas Gregor10176412011-02-25 16:07:42 +00009906 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00009907 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
9908 DeclarationName());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009909 NestedNameSpecifierLoc Rebuilt
Douglas Gregor10176412011-02-25 16:07:42 +00009910 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009911 if (!Rebuilt)
Douglas Gregor10176412011-02-25 16:07:42 +00009912 return true;
John McCall99b2fe52010-04-29 23:50:39 +00009913
Douglas Gregor10176412011-02-25 16:07:42 +00009914 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00009915 return false;
John McCall2408e322010-04-27 00:57:59 +00009916}
9917
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009918/// Rebuild the template parameters now that we know we're in a current
Douglas Gregor041b0842011-10-14 15:31:12 +00009919/// instantiation.
9920bool Sema::RebuildTemplateParamsInCurrentInstantiation(
9921 TemplateParameterList *Params) {
9922 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
9923 Decl *Param = Params->getParam(I);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009924
Douglas Gregor041b0842011-10-14 15:31:12 +00009925 // There is nothing to rebuild in a type parameter.
9926 if (isa<TemplateTypeParmDecl>(Param))
9927 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009928
Douglas Gregor041b0842011-10-14 15:31:12 +00009929 // Rebuild the template parameter list of a template template parameter.
Simon Pilgrim6905d222016-12-30 22:55:33 +00009930 if (TemplateTemplateParmDecl *TTP
Douglas Gregor041b0842011-10-14 15:31:12 +00009931 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
9932 if (RebuildTemplateParamsInCurrentInstantiation(
9933 TTP->getTemplateParameters()))
9934 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009935
Douglas Gregor041b0842011-10-14 15:31:12 +00009936 continue;
9937 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009938
Douglas Gregor041b0842011-10-14 15:31:12 +00009939 // Rebuild the type of a non-type template parameter.
9940 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009941 TypeSourceInfo *NewTSI
9942 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
9943 NTTP->getLocation(),
Douglas Gregor041b0842011-10-14 15:31:12 +00009944 NTTP->getDeclName());
9945 if (!NewTSI)
9946 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009947
Erik Pilkington9f9462a2018-08-07 22:59:02 +00009948 if (NewTSI->getType()->isUndeducedType()) {
9949 // C++17 [temp.dep.expr]p3:
9950 // An id-expression is type-dependent if it contains
9951 // - an identifier associated by name lookup with a non-type
9952 // template-parameter declared with a type that contains a
9953 // placeholder type (7.1.7.4),
9954 NewTSI = SubstAutoTypeSourceInfo(NewTSI, Context.DependentTy);
9955 }
9956
Douglas Gregor041b0842011-10-14 15:31:12 +00009957 if (NewTSI != NTTP->getTypeSourceInfo()) {
9958 NTTP->setTypeSourceInfo(NewTSI);
9959 NTTP->setType(NewTSI->getType());
9960 }
9961 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009962
Douglas Gregor041b0842011-10-14 15:31:12 +00009963 return false;
9964}
9965
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009966/// Produces a formatted string that describes the binding of
Douglas Gregorbe999392009-09-15 16:23:51 +00009967/// template parameters to template arguments.
9968std::string
9969Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9970 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009971 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00009972}
9973
9974std::string
9975Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9976 const TemplateArgument *Args,
9977 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009978 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +00009979 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +00009980
Douglas Gregore62e6a02009-11-11 19:13:48 +00009981 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00009982 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009983
Douglas Gregorbe999392009-09-15 16:23:51 +00009984 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00009985 if (I >= NumArgs)
9986 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009987
Douglas Gregorbe999392009-09-15 16:23:51 +00009988 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00009989 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +00009990 else
Douglas Gregor0192c232010-12-20 16:52:59 +00009991 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009992
Douglas Gregorbe999392009-09-15 16:23:51 +00009993 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +00009994 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +00009995 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +00009996 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +00009997 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009998
Douglas Gregor0192c232010-12-20 16:52:59 +00009999 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +000010000 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +000010001 }
Douglas Gregor0192c232010-12-20 16:52:59 +000010002
10003 Out << ']';
10004 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +000010005}
Francois Pichet1c229c02011-04-22 22:18:13 +000010006
Richard Smithe40f2ba2013-08-07 21:41:30 +000010007void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
10008 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +000010009 if (!FD)
10010 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +000010011
Justin Lebar28f09c52016-10-10 16:26:08 +000010012 auto LPT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +000010013
10014 // Take tokens to avoid allocations
10015 LPT->Toks.swap(Toks);
10016 LPT->D = FnD;
Justin Lebar28f09c52016-10-10 16:26:08 +000010017 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +000010018
10019 FD->setLateTemplateParsed(true);
10020}
10021
10022void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
10023 if (!FD)
10024 return;
10025 FD->setLateTemplateParsed(false);
10026}
Francois Pichet1c229c02011-04-22 22:18:13 +000010027
10028bool Sema::IsInsideALocalClassWithinATemplateFunction() {
10029 DeclContext *DC = CurContext;
10030
10031 while (DC) {
10032 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
10033 const FunctionDecl *FD = RD->isLocalClass();
10034 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
10035 } else if (DC->isTranslationUnit() || DC->isNamespace())
10036 return false;
10037
10038 DC = DC->getParent();
10039 }
10040 return false;
10041}
Richard Smith6739a102016-05-05 00:56:12 +000010042
Benjamin Kramera0a13c32016-08-06 11:21:04 +000010043namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010044/// Walk the path from which a declaration was instantiated, and check
Richard Smith6739a102016-05-05 00:56:12 +000010045/// that every explicit specialization along that path is visible. This enforces
10046/// C++ [temp.expl.spec]/6:
10047///
10048/// If a template, a member template or a member of a class template is
10049/// explicitly specialized then that specialization shall be declared before
10050/// the first use of that specialization that would cause an implicit
10051/// instantiation to take place, in every translation unit in which such a
10052/// use occurs; no diagnostic is required.
10053///
10054/// and also C++ [temp.class.spec]/1:
10055///
10056/// A partial specialization shall be declared before the first use of a
10057/// class template specialization that would make use of the partial
10058/// specialization as the result of an implicit or explicit instantiation
10059/// in every translation unit in which such a use occurs; no diagnostic is
10060/// required.
10061class ExplicitSpecializationVisibilityChecker {
10062 Sema &S;
10063 SourceLocation Loc;
10064 llvm::SmallVector<Module *, 8> Modules;
10065
10066public:
10067 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
10068 : S(S), Loc(Loc) {}
10069
10070 void check(NamedDecl *ND) {
10071 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10072 return checkImpl(FD);
10073 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
10074 return checkImpl(RD);
10075 if (auto *VD = dyn_cast<VarDecl>(ND))
10076 return checkImpl(VD);
10077 if (auto *ED = dyn_cast<EnumDecl>(ND))
10078 return checkImpl(ED);
10079 }
10080
10081private:
10082 void diagnose(NamedDecl *D, bool IsPartialSpec) {
10083 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
10084 : Sema::MissingImportKind::ExplicitSpecialization;
10085 const bool Recover = true;
10086
10087 // If we got a custom set of modules (because only a subset of the
10088 // declarations are interesting), use them, otherwise let
10089 // diagnoseMissingImport intelligently pick some.
10090 if (Modules.empty())
10091 S.diagnoseMissingImport(Loc, D, Kind, Recover);
10092 else
10093 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
10094 }
10095
10096 // Check a specific declaration. There are three problematic cases:
10097 //
10098 // 1) The declaration is an explicit specialization of a template
10099 // specialization.
10100 // 2) The declaration is an explicit specialization of a member of an
10101 // templated class.
10102 // 3) The declaration is an instantiation of a template, and that template
10103 // is an explicit specialization of a member of a templated class.
10104 //
10105 // We don't need to go any deeper than that, as the instantiation of the
10106 // surrounding class / etc is not triggered by whatever triggered this
10107 // instantiation, and thus should be checked elsewhere.
10108 template<typename SpecDecl>
10109 void checkImpl(SpecDecl *Spec) {
10110 bool IsHiddenExplicitSpecialization = false;
10111 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
10112 IsHiddenExplicitSpecialization =
10113 Spec->getMemberSpecializationInfo()
10114 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
Richard Smith54f04402017-05-18 02:29:20 +000010115 : !S.hasVisibleExplicitSpecialization(Spec, &Modules);
Richard Smith6739a102016-05-05 00:56:12 +000010116 } else {
10117 checkInstantiated(Spec);
10118 }
10119
10120 if (IsHiddenExplicitSpecialization)
10121 diagnose(Spec->getMostRecentDecl(), false);
10122 }
10123
10124 void checkInstantiated(FunctionDecl *FD) {
10125 if (auto *TD = FD->getPrimaryTemplate())
10126 checkTemplate(TD);
10127 }
10128
10129 void checkInstantiated(CXXRecordDecl *RD) {
10130 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
10131 if (!SD)
10132 return;
10133
10134 auto From = SD->getSpecializedTemplateOrPartial();
10135 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
10136 checkTemplate(TD);
10137 else if (auto *TD =
10138 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
10139 if (!S.hasVisibleDeclaration(TD))
10140 diagnose(TD, true);
10141 checkTemplate(TD);
10142 }
10143 }
10144
10145 void checkInstantiated(VarDecl *RD) {
10146 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
10147 if (!SD)
10148 return;
10149
10150 auto From = SD->getSpecializedTemplateOrPartial();
10151 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
10152 checkTemplate(TD);
10153 else if (auto *TD =
10154 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
10155 if (!S.hasVisibleDeclaration(TD))
10156 diagnose(TD, true);
10157 checkTemplate(TD);
10158 }
10159 }
10160
10161 void checkInstantiated(EnumDecl *FD) {}
10162
10163 template<typename TemplDecl>
10164 void checkTemplate(TemplDecl *TD) {
10165 if (TD->isMemberSpecialization()) {
10166 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
10167 diagnose(TD->getMostRecentDecl(), false);
10168 }
10169 }
10170};
Benjamin Kramera0a13c32016-08-06 11:21:04 +000010171} // end anonymous namespace
Richard Smith6739a102016-05-05 00:56:12 +000010172
10173void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
10174 if (!getLangOpts().Modules)
10175 return;
10176
10177 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
10178}
10179
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010180/// Check whether a template partial specialization that we've discovered
Richard Smith6739a102016-05-05 00:56:12 +000010181/// is hidden, and produce suitable diagnostics if so.
10182void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
10183 NamedDecl *Spec) {
10184 llvm::SmallVector<Module *, 8> Modules;
10185 if (!hasVisibleDeclaration(Spec, &Modules))
10186 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
10187 MissingImportKind::PartialSpecialization,
10188 /*Recover*/true);
10189}