blob: 699895568b77cc82639dd2d5700e80bb82b4cf99 [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"
Richard Smith26a92d52019-08-26 18:18:07 +000023#include "clang/Basic/Stack.h"
David Majnemer763584d2014-02-06 10:59:19 +000024#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Sema/DeclSpec.h"
26#include "clang/Sema/Lookup.h"
Richard Smith974c8b72019-10-19 00:04:43 +000027#include "clang/Sema/Overload.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "clang/Sema/ParsedTemplate.h"
29#include "clang/Sema/Scope.h"
30#include "clang/Sema/SemaInternal.h"
31#include "clang/Sema/Template.h"
32#include "clang/Sema/TemplateDeduction.h"
Benjamin Kramere0513cb2012-01-30 16:17:39 +000033#include "llvm/ADT/SmallBitVector.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000034#include "llvm/ADT/SmallString.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000035#include "llvm/ADT/StringExtras.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000036
Eric Fiselier6ad68552016-07-01 01:24:09 +000037#include <iterator>
Douglas Gregor5101c242008-12-05 18:15:24 +000038using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000039using namespace sema;
Douglas Gregor5101c242008-12-05 18:15:24 +000040
John McCall9b72f892010-11-10 02:40:36 +000041// Exported for use by Parser.
42SourceRange
43clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
44 unsigned N) {
45 if (!N) return SourceRange();
46 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
47}
48
Saar Raz0330fba2019-10-15 18:44:06 +000049/// \brief Determine whether the declaration found is acceptable as the name
Douglas Gregorb7bfe792009-09-02 22:59:36 +000050/// of a template and, if so, return that template declaration. Otherwise,
Richard Smithafcfb6b2019-02-15 21:53:07 +000051/// returns null.
52///
53/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
54/// is true. In all other cases it will return a TemplateDecl (or null).
55NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D,
56 bool AllowFunctionTemplates,
57 bool AllowDependent) {
58 D = D->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +000059
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000060 if (isa<TemplateDecl>(D)) {
61 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +000062 return nullptr;
63
Richard Smithafcfb6b2019-02-15 21:53:07 +000064 return D;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000065 }
Mike Stump11289f42009-09-09 15:08:12 +000066
Douglas Gregorb7bfe792009-09-02 22:59:36 +000067 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
68 // C++ [temp.local]p1:
69 // Like normal (non-template) classes, class templates have an
70 // injected-class-name (Clause 9). The injected-class-name
71 // can be used with or without a template-argument-list. When
72 // it is used without a template-argument-list, it is
73 // equivalent to the injected-class-name followed by the
74 // template-parameters of the class template enclosed in
75 // <>. When it is used with a template-argument-list, it
76 // refers to the specified class template specialization,
77 // which could be the current specialization or another
78 // specialization.
79 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000080 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000081 if (Record->getDescribedClassTemplate())
82 return Record->getDescribedClassTemplate();
83
84 if (ClassTemplateSpecializationDecl *Spec
85 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
86 return Spec->getSpecializedTemplate();
87 }
Mike Stump11289f42009-09-09 15:08:12 +000088
Craig Topperc3ec1492014-05-26 06:22:03 +000089 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +000090 }
Mike Stump11289f42009-09-09 15:08:12 +000091
Richard Smithcbebd622018-05-14 20:52:48 +000092 // 'using Dependent::foo;' can resolve to a template name.
93 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
94 // injected-class-name).
Richard Smithafcfb6b2019-02-15 21:53:07 +000095 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
Richard Smithcbebd622018-05-14 20:52:48 +000096 return D;
97
Craig Topperc3ec1492014-05-26 06:22:03 +000098 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +000099}
100
Simon Pilgrim6905d222016-12-30 22:55:33 +0000101void Sema::FilterAcceptableTemplateNames(LookupResult &R,
Richard Smithafcfb6b2019-02-15 21:53:07 +0000102 bool AllowFunctionTemplates,
103 bool AllowDependent) {
John McCalle66edc12009-11-24 19:00:30 +0000104 LookupResult::Filter filter = R.makeFilter();
105 while (filter.hasNext()) {
106 NamedDecl *Orig = filter.next();
Richard Smithafcfb6b2019-02-15 21:53:07 +0000107 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
John McCalle66edc12009-11-24 19:00:30 +0000108 filter.erase();
John McCalle66edc12009-11-24 19:00:30 +0000109 }
110 filter.done();
111}
112
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000113bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
Richard Smithafcfb6b2019-02-15 21:53:07 +0000114 bool AllowFunctionTemplates,
Richard Smithb23c5e82019-05-09 03:31:27 +0000115 bool AllowDependent,
116 bool AllowNonTemplateFunctions) {
117 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
Richard Smithafcfb6b2019-02-15 21:53:07 +0000118 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000119 return true;
Richard Smithb23c5e82019-05-09 03:31:27 +0000120 if (AllowNonTemplateFunctions &&
121 isa<FunctionDecl>((*I)->getUnderlyingDecl()))
122 return true;
123 }
Simon Pilgrim6905d222016-12-30 22:55:33 +0000124
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000125 return false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000126}
127
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000128TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000129 CXXScopeSpec &SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000130 bool hasTemplateKeyword,
Richard Smithc08b6932018-04-27 02:00:13 +0000131 const UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +0000132 ParsedType ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000133 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000134 TemplateTy &TemplateResult,
135 bool &MemberOfUnknownSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000136 assert(getLangOpts().CPlusPlus && "No template names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000137
Douglas Gregor3cf81312009-11-03 23:16:33 +0000138 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000139 MemberOfUnknownSpecialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000140
Douglas Gregor3cf81312009-11-03 23:16:33 +0000141 switch (Name.getKind()) {
Faisal Vali2ab8c152017-12-30 04:15:27 +0000142 case UnqualifiedIdKind::IK_Identifier:
Douglas Gregor3cf81312009-11-03 23:16:33 +0000143 TName = DeclarationName(Name.Identifier);
144 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000145
Faisal Vali2ab8c152017-12-30 04:15:27 +0000146 case UnqualifiedIdKind::IK_OperatorFunctionId:
Douglas Gregor3cf81312009-11-03 23:16:33 +0000147 TName = Context.DeclarationNames.getCXXOperatorName(
148 Name.OperatorFunctionId.Operator);
149 break;
150
Faisal Vali2ab8c152017-12-30 04:15:27 +0000151 case UnqualifiedIdKind::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000152 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
153 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000154
Douglas Gregor3cf81312009-11-03 23:16:33 +0000155 default:
156 return TNK_Non_template;
157 }
Mike Stump11289f42009-09-09 15:08:12 +0000158
John McCallba7bf592010-08-24 05:47:05 +0000159 QualType ObjectType = ObjectTypePtr.get();
Mike Stump11289f42009-09-09 15:08:12 +0000160
Richard Smithb23c5e82019-05-09 03:31:27 +0000161 AssumedTemplateKind AssumedTemplate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000162 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
Richard Smith79810042018-05-11 02:43:08 +0000163 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
Richard Smithb23c5e82019-05-09 03:31:27 +0000164 MemberOfUnknownSpecialization, SourceLocation(),
165 &AssumedTemplate))
Richard Smith79810042018-05-11 02:43:08 +0000166 return TNK_Non_template;
Richard Smithb23c5e82019-05-09 03:31:27 +0000167
168 if (AssumedTemplate != AssumedTemplateKind::None) {
169 TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
170 // Let the parser know whether we found nothing or found functions; if we
171 // found nothing, we want to more carefully check whether this is actually
172 // a function template name versus some other kind of undeclared identifier.
173 return AssumedTemplate == AssumedTemplateKind::FoundNothing
174 ? TNK_Undeclared_template
175 : TNK_Function_template;
176 }
177
178 if (R.empty())
179 return TNK_Non_template;
Richard Smith40bd10b2019-02-15 00:29:04 +0000180
Richard Smithafcfb6b2019-02-15 21:53:07 +0000181 NamedDecl *D = nullptr;
182 if (R.isAmbiguous()) {
183 // If we got an ambiguity involving a non-function template, treat this
184 // as a template name, and pick an arbitrary template for error recovery.
185 bool AnyFunctionTemplates = false;
186 for (NamedDecl *FoundD : R) {
187 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
188 if (isa<FunctionTemplateDecl>(FoundTemplate))
189 AnyFunctionTemplates = true;
190 else {
191 D = FoundTemplate;
192 break;
193 }
194 }
195 }
196
197 // If we didn't find any templates at all, this isn't a template name.
198 // Leave the ambiguity for a later lookup to diagnose.
199 if (!D && !AnyFunctionTemplates) {
200 R.suppressDiagnostics();
201 return TNK_Non_template;
202 }
203
204 // If the only templates were function templates, filter out the rest.
205 // We'll diagnose the ambiguity later.
206 if (!D)
207 FilterAcceptableTemplateNames(R);
John McCalldcc71402010-08-13 02:23:42 +0000208 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000209
Richard Smithafcfb6b2019-02-15 21:53:07 +0000210 // At this point, we have either picked a single template name declaration D
211 // or we have a non-empty set of results R containing either one template name
212 // declaration or a set of function templates.
213
John McCalld28ae272009-12-02 08:04:21 +0000214 TemplateName Template;
215 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000216
John McCalld28ae272009-12-02 08:04:21 +0000217 unsigned ResultCount = R.end() - R.begin();
Richard Smithafcfb6b2019-02-15 21:53:07 +0000218 if (!D && ResultCount > 1) {
John McCalld28ae272009-12-02 08:04:21 +0000219 // We assume that we'll preserve the qualifier from a function
220 // template name in other ways.
221 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
222 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000223
224 // We'll do this lookup again later.
225 R.suppressDiagnostics();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000226 } else {
Richard Smithafcfb6b2019-02-15 21:53:07 +0000227 if (!D) {
228 D = getAsTemplateNameDecl(*R.begin());
229 assert(D && "unambiguous result is not a template name");
230 }
231
232 if (isa<UnresolvedUsingValueDecl>(D)) {
233 // We don't yet know whether this is a template-name or not.
234 MemberOfUnknownSpecialization = true;
235 return TNK_Non_template;
236 }
237
238 TemplateDecl *TD = cast<TemplateDecl>(D);
John McCalld28ae272009-12-02 08:04:21 +0000239
240 if (SS.isSet() && !SS.isInvalid()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000241 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000242 Template = Context.getQualifiedTemplateName(Qualifier,
243 hasTemplateKeyword, TD);
John McCalld28ae272009-12-02 08:04:21 +0000244 } else {
245 Template = TemplateName(TD);
246 }
247
John McCalldcc71402010-08-13 02:23:42 +0000248 if (isa<FunctionTemplateDecl>(TD)) {
John McCalld28ae272009-12-02 08:04:21 +0000249 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000250
251 // We'll do this lookup again later.
252 R.suppressDiagnostics();
253 } else {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000254 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000255 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
Saar Razd7aae332019-07-10 21:25:49 +0000256 isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
Larisse Voufo39a1e502013-08-06 01:03:05 +0000257 TemplateKind =
Saar Razd7aae332019-07-10 21:25:49 +0000258 isa<VarTemplateDecl>(TD) ? TNK_Var_template :
259 isa<ConceptDecl>(TD) ? TNK_Concept_template :
260 TNK_Type_template;
John McCalld28ae272009-12-02 08:04:21 +0000261 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000262 }
Mike Stump11289f42009-09-09 15:08:12 +0000263
John McCalld28ae272009-12-02 08:04:21 +0000264 TemplateResult = TemplateTy::make(Template);
265 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000266}
267
Richard Smith278890f2017-02-10 20:39:58 +0000268bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
269 SourceLocation NameLoc,
270 ParsedTemplateTy *Template) {
271 CXXScopeSpec SS;
272 bool MemberOfUnknownSpecialization = false;
273
274 // We could use redeclaration lookup here, but we don't need to: the
275 // syntactic form of a deduction guide is enough to identify it even
276 // if we can't look up the template name at all.
277 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
Richard Smith79810042018-05-11 02:43:08 +0000278 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
279 /*EnteringContext*/ false,
280 MemberOfUnknownSpecialization))
281 return false;
Richard Smith278890f2017-02-10 20:39:58 +0000282
283 if (R.empty()) return false;
284 if (R.isAmbiguous()) {
285 // FIXME: Diagnose an ambiguity if we find at least one template.
286 R.suppressDiagnostics();
287 return false;
288 }
289
290 // We only treat template-names that name type templates as valid deduction
291 // guide names.
292 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
293 if (!TD || !getAsTypeTemplateDecl(TD))
294 return false;
295
296 if (Template)
297 *Template = TemplateTy::make(TemplateName(TD));
298 return true;
299}
300
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000301bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
Douglas Gregor18473f32010-01-12 21:28:44 +0000302 SourceLocation IILoc,
303 Scope *S,
304 const CXXScopeSpec *SS,
305 TemplateTy &SuggestedTemplate,
306 TemplateNameKind &SuggestedKind) {
307 // We can't recover unless there's a dependent scope specifier preceding the
308 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000309 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000310 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
311 computeDeclContext(*SS))
312 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000313
Douglas Gregor18473f32010-01-12 21:28:44 +0000314 // The code is missing a 'template' keyword prior to the dependent template
315 // name.
316 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
317 Diag(IILoc, diag::err_template_kw_missing)
318 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000319 << FixItHint::CreateInsertion(IILoc, "template ");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000320 SuggestedTemplate
Douglas Gregor18473f32010-01-12 21:28:44 +0000321 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
322 SuggestedKind = TNK_Dependent_template_name;
323 return true;
324}
325
Richard Smith79810042018-05-11 02:43:08 +0000326bool Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000327 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000328 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000329 bool EnteringContext,
Richard Smith79810042018-05-11 02:43:08 +0000330 bool &MemberOfUnknownSpecialization,
Richard Smithb23c5e82019-05-09 03:31:27 +0000331 SourceLocation TemplateKWLoc,
332 AssumedTemplateKind *ATK) {
333 if (ATK)
334 *ATK = AssumedTemplateKind::None;
335
Richard Smithafcfb6b2019-02-15 21:53:07 +0000336 Found.setTemplateNameLookup(true);
337
John McCalle66edc12009-11-24 19:00:30 +0000338 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000339 MemberOfUnknownSpecialization = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000340 DeclContext *LookupCtx = nullptr;
Richard Smith79810042018-05-11 02:43:08 +0000341 bool IsDependent = false;
John McCalle66edc12009-11-24 19:00:30 +0000342 if (!ObjectType.isNull()) {
343 // This nested-name-specifier occurs in a member access expression, e.g.,
344 // x->B::f, and we are looking into the type of the object.
345 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
346 LookupCtx = computeDeclContext(ObjectType);
Richard Smith9e77f522019-08-14 22:57:50 +0000347 IsDependent = !LookupCtx && ObjectType->isDependentType();
Richard Smith79810042018-05-11 02:43:08 +0000348 assert((IsDependent || !ObjectType->isIncompleteType() ||
Richard Smith5ed79562013-06-07 20:03:01 +0000349 ObjectType->castAs<TagType>()->isBeingDefined()) &&
John McCalle66edc12009-11-24 19:00:30 +0000350 "Caller should have completed object type");
Simon Pilgrim6905d222016-12-30 22:55:33 +0000351
Richard Smith9e77f522019-08-14 22:57:50 +0000352 // Template names cannot appear inside an Objective-C class or object type
353 // or a vector type.
354 //
355 // FIXME: This is wrong. For example:
356 //
357 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
358 // Vec<int> vi;
359 // vi.Vec<int>::~Vec<int>();
360 //
361 // ... should be accepted but we will not treat 'Vec' as a template name
362 // here. The right thing to do would be to check if the name is a valid
363 // vector component name, and look up a template name if not. And similarly
364 // for lookups into Objective-C class and object types, where the same
365 // problem can arise.
366 if (ObjectType->isObjCObjectOrInterfaceType() ||
367 ObjectType->isVectorType()) {
Douglas Gregorbf3a8262012-01-12 16:11:24 +0000368 Found.clear();
Richard Smith79810042018-05-11 02:43:08 +0000369 return false;
Douglas Gregorbf3a8262012-01-12 16:11:24 +0000370 }
John McCalle66edc12009-11-24 19:00:30 +0000371 } else if (SS.isSet()) {
372 // This nested-name-specifier occurs after another nested-name-specifier,
373 // so long into the context associated with the prior nested-name-specifier.
374 LookupCtx = computeDeclContext(SS, EnteringContext);
Richard Smith79810042018-05-11 02:43:08 +0000375 IsDependent = !LookupCtx;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000376
John McCalle66edc12009-11-24 19:00:30 +0000377 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000378 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
Richard Smith79810042018-05-11 02:43:08 +0000379 return true;
John McCalle66edc12009-11-24 19:00:30 +0000380 }
381
382 bool ObjectTypeSearchedInScope = false;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000383 bool AllowFunctionTemplatesInLookup = true;
John McCalle66edc12009-11-24 19:00:30 +0000384 if (LookupCtx) {
385 // Perform "qualified" name lookup into the declaration context we
386 // computed, which is either the type of the base of a member access
387 // expression or the declaration context associated with a prior
388 // nested-name-specifier.
389 LookupQualifiedName(Found, LookupCtx);
Simon Pilgrim6905d222016-12-30 22:55:33 +0000390
Richard Smith79810042018-05-11 02:43:08 +0000391 // FIXME: The C++ standard does not clearly specify what happens in the
392 // case where the object type is dependent, and implementations vary. In
393 // Clang, we treat a name after a . or -> as a template-name if lookup
394 // finds a non-dependent member or member of the current instantiation that
395 // is a type template, or finds no such members and lookup in the context
396 // of the postfix-expression finds a type template. In the latter case, the
397 // name is nonetheless dependent, and we may resolve it to a member of an
398 // unknown specialization when we come to instantiate the template.
399 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
John McCalle66edc12009-11-24 19:00:30 +0000400 }
401
Richard Smith79810042018-05-11 02:43:08 +0000402 if (!SS.isSet() && (ObjectType.isNull() || Found.empty())) {
403 // C++ [basic.lookup.classref]p1:
404 // In a class member access expression (5.2.5), if the . or -> token is
405 // immediately followed by an identifier followed by a <, the
406 // identifier must be looked up to determine whether the < is the
407 // beginning of a template argument list (14.2) or a less-than operator.
408 // The identifier is first looked up in the class of the object
409 // expression. If the identifier is not found, it is then looked up in
410 // the context of the entire postfix-expression and shall name a class
411 // template.
412 if (S)
413 LookupName(Found, S);
414
415 if (!ObjectType.isNull()) {
416 // FIXME: We should filter out all non-type templates here, particularly
417 // variable templates and concepts. But the exclusion of alias templates
418 // and template template parameters is a wording defect.
419 AllowFunctionTemplatesInLookup = false;
420 ObjectTypeSearchedInScope = true;
421 }
422
423 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
424 }
425
Richard Smithafcfb6b2019-02-15 21:53:07 +0000426 if (Found.isAmbiguous())
427 return false;
428
Richard Smithb23c5e82019-05-09 03:31:27 +0000429 if (ATK && !SS.isSet() && ObjectType.isNull() && TemplateKWLoc.isInvalid()) {
430 // C++2a [temp.names]p2:
431 // A name is also considered to refer to a template if it is an
432 // unqualified-id followed by a < and name lookup finds either one or more
433 // functions or finds nothing.
434 //
435 // To keep our behavior consistent, we apply the "finds nothing" part in
436 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
437 // successfully form a call to an undeclared template-id.
438 bool AllFunctions =
439 getLangOpts().CPlusPlus2a &&
440 std::all_of(Found.begin(), Found.end(), [](NamedDecl *ND) {
441 return isa<FunctionDecl>(ND->getUnderlyingDecl());
442 });
443 if (AllFunctions || (Found.empty() && !IsDependent)) {
444 // If lookup found any functions, or if this is a name that can only be
445 // used for a function, then strongly assume this is a function
446 // template-id.
447 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
448 ? AssumedTemplateKind::FoundNothing
449 : AssumedTemplateKind::FoundFunctions;
450 Found.clear();
451 return false;
452 }
453 }
454
Richard Smith79810042018-05-11 02:43:08 +0000455 if (Found.empty() && !IsDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000456 // If we did not find any names, attempt to correct any typos.
457 DeclarationName Name = Found.getLookupName();
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000458 Found.clear();
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000459 // Simple filter callback that, for keywords, only accepts the C++ *_cast
Bruno Ricci70ad3962019-03-25 17:08:51 +0000460 DefaultFilterCCC FilterCCC{};
461 FilterCCC.WantTypeSpecifiers = false;
462 FilterCCC.WantExpressionKeywords = false;
463 FilterCCC.WantRemainingKeywords = false;
464 FilterCCC.WantCXXNamedCasts = true;
465 if (TypoCorrection Corrected =
466 CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S,
467 &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) {
Richard Smithde6d6c42015-12-29 19:43:10 +0000468 if (auto *ND = Corrected.getFoundDecl())
469 Found.addDecl(ND);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000470 FilterAcceptableTemplateNames(Found);
Richard Smithafcfb6b2019-02-15 21:53:07 +0000471 if (Found.isAmbiguous()) {
472 Found.clear();
473 } else if (!Found.empty()) {
Richard Smithb23c5e82019-05-09 03:31:27 +0000474 Found.setLookupName(Corrected.getCorrection());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000475 if (LookupCtx) {
Richard Smithf9b15102013-08-17 00:46:16 +0000476 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
477 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000478 Name.getAsString() == CorrectedStr;
Richard Smithf9b15102013-08-17 00:46:16 +0000479 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
480 << Name << LookupCtx << DroppedSpecifier
481 << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000482 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000483 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000484 }
John McCalle9cccd82010-06-16 08:42:20 +0000485 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000486 }
487 }
488
Richard Smith79810042018-05-11 02:43:08 +0000489 NamedDecl *ExampleLookupResult =
490 Found.empty() ? nullptr : Found.getRepresentativeDecl();
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000491 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000492 if (Found.empty()) {
Richard Smith79810042018-05-11 02:43:08 +0000493 if (IsDependent) {
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000494 MemberOfUnknownSpecialization = true;
Richard Smith79810042018-05-11 02:43:08 +0000495 return false;
496 }
497
498 // If a 'template' keyword was used, a lookup that finds only non-template
499 // names is an error.
500 if (ExampleLookupResult && TemplateKWLoc.isValid()) {
501 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
502 << Found.getLookupName() << SS.getRange();
Richard Smithcbebd622018-05-14 20:52:48 +0000503 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
Richard Smith79810042018-05-11 02:43:08 +0000504 diag::note_template_kw_refers_to_non_template)
505 << Found.getLookupName();
506 return true;
507 }
508
509 return false;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000510 }
John McCalle66edc12009-11-24 19:00:30 +0000511
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000512 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
Richard Smithe7d67f22013-09-03 21:22:41 +0000513 !getLangOpts().CPlusPlus11) {
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000514 // C++03 [basic.lookup.classref]p1:
John McCalle66edc12009-11-24 19:00:30 +0000515 // [...] If the lookup in the class of the object expression finds a
516 // template, the name is also looked up in the context of the entire
517 // postfix-expression and [...]
518 //
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000519 // Note: C++11 does not perform this second lookup.
John McCalle66edc12009-11-24 19:00:30 +0000520 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
521 LookupOrdinaryName);
Richard Smithafcfb6b2019-02-15 21:53:07 +0000522 FoundOuter.setTemplateNameLookup(true);
John McCalle66edc12009-11-24 19:00:30 +0000523 LookupName(FoundOuter, S);
Richard Smithafcfb6b2019-02-15 21:53:07 +0000524 // FIXME: We silently accept an ambiguous lookup here, in violation of
525 // [basic.lookup]/1.
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000526 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000527
Richard Smithafcfb6b2019-02-15 21:53:07 +0000528 NamedDecl *OuterTemplate;
John McCalle66edc12009-11-24 19:00:30 +0000529 if (FoundOuter.empty()) {
530 // - if the name is not found, the name found in the class of the
531 // object expression is used, otherwise
Richard Smithafcfb6b2019-02-15 21:53:07 +0000532 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
533 !(OuterTemplate =
534 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
John McCalle66edc12009-11-24 19:00:30 +0000535 // - if the name is found in the context of the entire
536 // postfix-expression and does not name a class template, the name
537 // found in the class of the object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000538 FoundOuter.clear();
John McCalle9cccd82010-06-16 08:42:20 +0000539 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000540 // - if the name found is a class template, it must refer to the same
541 // entity as the one found in the class of the object expression,
542 // otherwise the program is ill-formed.
543 if (!Found.isSingleResult() ||
Richard Smithafcfb6b2019-02-15 21:53:07 +0000544 getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
545 OuterTemplate->getCanonicalDecl()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000546 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000547 diag::ext_nested_name_member_ref_lookup_ambiguous)
548 << Found.getLookupName()
549 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000550 Diag(Found.getRepresentativeDecl()->getLocation(),
551 diag::note_ambig_member_ref_object_type)
552 << ObjectType;
553 Diag(FoundOuter.getFoundDecl()->getLocation(),
554 diag::note_ambig_member_ref_scope);
555
556 // Recover by taking the template that we found in the object
557 // expression's type.
558 }
559 }
560 }
Richard Smith79810042018-05-11 02:43:08 +0000561
562 return false;
John McCalle66edc12009-11-24 19:00:30 +0000563}
564
Richard Smith42bc73a2017-05-10 02:30:28 +0000565void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
566 SourceLocation Less,
567 SourceLocation Greater) {
568 if (TemplateName.isInvalid())
569 return;
570
571 DeclarationNameInfo NameInfo;
572 CXXScopeSpec SS;
573 LookupNameKind LookupKind;
574
575 DeclContext *LookupCtx = nullptr;
576 NamedDecl *Found = nullptr;
Richard Smithbf5bcf22018-06-26 23:20:26 +0000577 bool MissingTemplateKeyword = false;
Richard Smith42bc73a2017-05-10 02:30:28 +0000578
579 // Figure out what name we looked up.
Richard Smithbf5bcf22018-06-26 23:20:26 +0000580 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
581 NameInfo = DRE->getNameInfo();
582 SS.Adopt(DRE->getQualifierLoc());
583 LookupKind = LookupOrdinaryName;
584 Found = DRE->getFoundDecl();
585 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
Richard Smith42bc73a2017-05-10 02:30:28 +0000586 NameInfo = ME->getMemberNameInfo();
587 SS.Adopt(ME->getQualifierLoc());
588 LookupKind = LookupMemberName;
589 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
590 Found = ME->getMemberDecl();
Richard Smithbf5bcf22018-06-26 23:20:26 +0000591 } else if (auto *DSDRE =
592 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
593 NameInfo = DSDRE->getNameInfo();
594 SS.Adopt(DSDRE->getQualifierLoc());
595 MissingTemplateKeyword = true;
596 } else if (auto *DSME =
597 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
598 NameInfo = DSME->getMemberNameInfo();
599 SS.Adopt(DSME->getQualifierLoc());
600 MissingTemplateKeyword = true;
Richard Smith42bc73a2017-05-10 02:30:28 +0000601 } else {
Richard Smithbf5bcf22018-06-26 23:20:26 +0000602 llvm_unreachable("unexpected kind of potential template name");
603 }
604
605 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
606 // was missing.
607 if (MissingTemplateKeyword) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000608 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
609 << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
Richard Smithbf5bcf22018-06-26 23:20:26 +0000610 return;
Richard Smith42bc73a2017-05-10 02:30:28 +0000611 }
612
613 // Try to correct the name by looking for templates and C++ named casts.
614 struct TemplateCandidateFilter : CorrectionCandidateCallback {
Richard Smithafcfb6b2019-02-15 21:53:07 +0000615 Sema &S;
616 TemplateCandidateFilter(Sema &S) : S(S) {
Richard Smith42bc73a2017-05-10 02:30:28 +0000617 WantTypeSpecifiers = false;
618 WantExpressionKeywords = false;
619 WantRemainingKeywords = false;
620 WantCXXNamedCasts = true;
621 };
622 bool ValidateCandidate(const TypoCorrection &Candidate) override {
623 if (auto *ND = Candidate.getCorrectionDecl())
Richard Smithafcfb6b2019-02-15 21:53:07 +0000624 return S.getAsTemplateNameDecl(ND);
Richard Smith42bc73a2017-05-10 02:30:28 +0000625 return Candidate.isKeyword();
626 }
Bruno Ricci70ad3962019-03-25 17:08:51 +0000627
628 std::unique_ptr<CorrectionCandidateCallback> clone() override {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000629 return std::make_unique<TemplateCandidateFilter>(*this);
Bruno Ricci70ad3962019-03-25 17:08:51 +0000630 }
Richard Smith42bc73a2017-05-10 02:30:28 +0000631 };
632
633 DeclarationName Name = NameInfo.getName();
Bruno Ricci70ad3962019-03-25 17:08:51 +0000634 TemplateCandidateFilter CCC(*this);
635 if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
636 CTK_ErrorRecovery, LookupCtx)) {
Richard Smith42bc73a2017-05-10 02:30:28 +0000637 auto *ND = Corrected.getFoundDecl();
638 if (ND)
Richard Smithafcfb6b2019-02-15 21:53:07 +0000639 ND = getAsTemplateNameDecl(ND);
Richard Smith42bc73a2017-05-10 02:30:28 +0000640 if (ND || Corrected.isKeyword()) {
641 if (LookupCtx) {
642 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
643 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
644 Name.getAsString() == CorrectedStr;
645 diagnoseTypo(Corrected,
646 PDiag(diag::err_non_template_in_member_template_id_suggest)
647 << Name << LookupCtx << DroppedSpecifier
Richard Smith52f8d192017-05-10 21:32:16 +0000648 << SS.getRange(), false);
Richard Smith42bc73a2017-05-10 02:30:28 +0000649 } else {
650 diagnoseTypo(Corrected,
651 PDiag(diag::err_non_template_in_template_id_suggest)
Richard Smith52f8d192017-05-10 21:32:16 +0000652 << Name, false);
Richard Smith42bc73a2017-05-10 02:30:28 +0000653 }
654 if (Found)
655 Diag(Found->getLocation(),
656 diag::note_non_template_in_template_id_found);
657 return;
658 }
659 }
660
661 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
662 << Name << SourceRange(Less, Greater);
663 if (Found)
664 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
665}
666
John McCallcd4b4772009-12-02 03:53:29 +0000667/// ActOnDependentIdExpression - Handle a dependent id-expression that
668/// was just parsed. This is only possible with an explicit scope
669/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000670ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000671Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000672 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000673 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000674 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000675 const TemplateArgumentListInfo *TemplateArgs) {
John McCall87fe5d52010-05-20 01:18:31 +0000676 DeclContext *DC = getFunctionLevelDeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000677
Reid Kleckner1af391df2016-03-11 18:59:12 +0000678 // C++11 [expr.prim.general]p12:
679 // An id-expression that denotes a non-static data member or non-static
680 // member function of a class can only be used:
681 // (...)
682 // - if that id-expression denotes a non-static data member and it
683 // appears in an unevaluated operand.
684 //
685 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
686 // CXXDependentScopeMemberExpr. The former can instantiate to either
687 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
688 // always a MemberExpr.
689 bool MightBeCxx11UnevalField =
690 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
691
Akira Hatanakad644e022016-12-16 03:19:41 +0000692 // Check if the nested name specifier is an enum type.
693 bool IsEnum = false;
694 if (NestedNameSpecifier *NNS = SS.getScopeRep())
695 IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
696
697 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
Reid Kleckner1af391df2016-03-11 18:59:12 +0000698 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
Brian Gesiak5488ab42019-01-11 01:54:53 +0000699 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000700
John McCalle66edc12009-11-24 19:00:30 +0000701 // Since the 'this' expression is synthesized, we don't need to
702 // perform the double-lookup check.
Craig Topperc3ec1492014-05-26 06:22:03 +0000703 NamedDecl *FirstQualifierInScope = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000704
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000705 return CXXDependentScopeMemberExpr::Create(
706 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
707 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
708 FirstQualifierInScope, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000709 }
710
Abramo Bagnara7945c982012-01-27 09:46:47 +0000711 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000712}
713
John McCalldadc5752010-08-24 06:29:42 +0000714ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000715Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000716 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000717 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000718 const TemplateArgumentListInfo *TemplateArgs) {
Aaron Ballmanc4450432019-09-07 20:14:09 +0000719 // DependentScopeDeclRefExpr::Create requires a valid QualifierLoc
720 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
721 if (!QualifierLoc)
722 return ExprError();
723
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000724 return DependentScopeDeclRefExpr::Create(
Aaron Ballmanc4450432019-09-07 20:14:09 +0000725 Context, QualifierLoc, TemplateKWLoc, NameInfo, TemplateArgs);
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000726}
727
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000728
729/// Determine whether we would be unable to instantiate this template (because
730/// it either has no definition, or is in the process of being instantiated).
731bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
732 NamedDecl *Instantiation,
733 bool InstantiatedFromMember,
734 const NamedDecl *Pattern,
735 const NamedDecl *PatternDef,
736 TemplateSpecializationKind TSK,
737 bool Complain /*= true*/) {
Richard Smithedbc6e92016-10-14 21:41:24 +0000738 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
739 isa<VarDecl>(Instantiation));
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000740
Richard Smithedbc6e92016-10-14 21:41:24 +0000741 bool IsEntityBeingDefined = false;
742 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
743 IsEntityBeingDefined = TD->isBeingDefined();
744
745 if (PatternDef && !IsEntityBeingDefined) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000746 NamedDecl *SuggestedDef = nullptr;
747 if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
748 /*OnlyNeedComplete*/false)) {
749 // If we're allowed to diagnose this and recover, do so.
750 bool Recover = Complain && !isSFINAEContext();
751 if (Complain)
752 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
753 Sema::MissingImportKind::Definition, Recover);
754 return !Recover;
755 }
756 return false;
757 }
758
Richard Smith6f4e2e02016-08-23 19:41:39 +0000759 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
760 return true;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000761
Richard Smithedbc6e92016-10-14 21:41:24 +0000762 llvm::Optional<unsigned> Note;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000763 QualType InstantiationTy;
764 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
765 InstantiationTy = Context.getTypeDeclType(TD);
Richard Smith6f4e2e02016-08-23 19:41:39 +0000766 if (PatternDef) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000767 Diag(PointOfInstantiation,
768 diag::err_template_instantiate_within_definition)
Richard Smithedbc6e92016-10-14 21:41:24 +0000769 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000770 << InstantiationTy;
771 // Not much point in noting the template declaration here, since
772 // we're lexically inside it.
773 Instantiation->setInvalidDecl();
774 } else if (InstantiatedFromMember) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000775 if (isa<FunctionDecl>(Instantiation)) {
776 Diag(PointOfInstantiation,
777 diag::err_explicit_instantiation_undefined_member)
Richard Smithedbc6e92016-10-14 21:41:24 +0000778 << /*member function*/ 1 << Instantiation->getDeclName()
779 << Instantiation->getDeclContext();
780 Note = diag::note_explicit_instantiation_here;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000781 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000782 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
Richard Smith6f4e2e02016-08-23 19:41:39 +0000783 Diag(PointOfInstantiation,
784 diag::err_implicit_instantiate_member_undefined)
785 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000786 Note = diag::note_member_declared_at;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000787 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000788 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000789 if (isa<FunctionDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000790 Diag(PointOfInstantiation,
791 diag::err_explicit_instantiation_undefined_func_template)
792 << Pattern;
Richard Smithedbc6e92016-10-14 21:41:24 +0000793 Note = diag::note_explicit_instantiation_here;
794 } else if (isa<TagDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000795 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
796 << (TSK != TSK_ImplicitInstantiation)
797 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000798 Note = diag::note_template_decl_here;
799 } else {
800 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
801 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
802 Diag(PointOfInstantiation,
803 diag::err_explicit_instantiation_undefined_var_template)
804 << Instantiation;
805 Instantiation->setInvalidDecl();
806 } else
807 Diag(PointOfInstantiation,
808 diag::err_explicit_instantiation_undefined_member)
809 << /*static data member*/ 2 << Instantiation->getDeclName()
810 << Instantiation->getDeclContext();
811 Note = diag::note_explicit_instantiation_here;
812 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000813 }
Richard Smithedbc6e92016-10-14 21:41:24 +0000814 if (Note) // Diagnostics were emitted.
815 Diag(Pattern->getLocation(), Note.getValue());
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000816
817 // In general, Instantiation isn't marked invalid to get more than one
818 // error for multiple undefined instantiations. But the code that does
819 // explicit declaration -> explicit definition conversion can't handle
820 // invalid declarations, so mark as invalid in that case.
821 if (TSK == TSK_ExplicitInstantiationDeclaration)
822 Instantiation->setInvalidDecl();
823 return true;
824}
825
Douglas Gregor5101c242008-12-05 18:15:24 +0000826/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
827/// that the template parameter 'PrevDecl' is being shadowed by a new
828/// declaration at location Loc. Returns true to indicate that this is
829/// an error, and false otherwise.
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000830void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000831 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000832
Douglas Gregor5101c242008-12-05 18:15:24 +0000833 // C++ [temp.local]p4:
834 // A template-parameter shall not be redeclared within its
835 // scope (including nested scopes).
Reid Klecknerb6a81522019-09-12 18:26:34 +0000836 //
837 // Make this a warning when MSVC compatibility is requested.
838 unsigned DiagId = getLangOpts().MSVCCompat ? diag::ext_template_param_shadow
839 : diag::err_template_param_shadow;
840 Diag(Loc, DiagId) << cast<NamedDecl>(PrevDecl)->getDeclName();
Douglas Gregor5101c242008-12-05 18:15:24 +0000841 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregor5101c242008-12-05 18:15:24 +0000842}
843
Douglas Gregor463421d2009-03-03 04:44:36 +0000844/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000845/// the parameter D to reference the templated declaration and return a pointer
846/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000847TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
848 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
849 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000850 return Temp;
851 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000852 return nullptr;
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000853}
854
Douglas Gregoreb29d182011-01-05 17:40:24 +0000855ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
856 SourceLocation EllipsisLoc) const {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000857 assert(Kind == Template &&
Douglas Gregoreb29d182011-01-05 17:40:24 +0000858 "Only template template arguments can be pack expansions here");
859 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
860 "Template template argument pack expansion without packs");
861 ParsedTemplateArgument Result(*this);
862 Result.EllipsisLoc = EllipsisLoc;
863 return Result;
864}
865
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000866static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
867 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000868
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000869 switch (Arg.getKind()) {
870 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000871 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000872 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000873 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000874 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000875 return TemplateArgumentLoc(TemplateArgument(T), DI);
876 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000877
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000878 case ParsedTemplateArgument::NonType: {
879 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
880 return TemplateArgumentLoc(TemplateArgument(E), E);
881 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000882
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000883 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000884 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregore1d60df2011-01-14 23:41:42 +0000885 TemplateArgument TArg;
886 if (Arg.getEllipsisLoc().isValid())
David Blaikie05785d12013-02-20 22:23:23 +0000887 TArg = TemplateArgument(Template, Optional<unsigned int>());
Douglas Gregore1d60df2011-01-14 23:41:42 +0000888 else
889 TArg = Template;
890 return TemplateArgumentLoc(TArg,
Douglas Gregor9d802122011-03-02 17:09:35 +0000891 Arg.getScopeSpec().getWithLocInContext(
892 SemaRef.Context),
Douglas Gregoreb29d182011-01-05 17:40:24 +0000893 Arg.getLocation(),
894 Arg.getEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000895 }
896 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000897
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000898 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000899}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000900
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000901/// Translates template arguments as provided by the parser
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000902/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000903void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
904 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000905 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000906 TemplateArgs.addArgument(translateTemplateArgument(*this,
907 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000908}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000909
Richard Smithb80d5402013-06-25 22:21:36 +0000910static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
911 SourceLocation Loc,
912 IdentifierInfo *Name) {
913 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
Richard Smithbecb92d2017-10-10 22:33:17 +0000914 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
Richard Smithb80d5402013-06-25 22:21:36 +0000915 if (PrevDecl && PrevDecl->isTemplateParameter())
916 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
917}
918
Richard Smith77a9c602018-02-28 03:02:23 +0000919/// Convert a parsed type into a parsed template argument. This is mostly
920/// trivial, except that we may have parsed a C++17 deduced class template
921/// specialization type, in which case we should form a template template
922/// argument instead of a type template argument.
923ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
924 TypeSourceInfo *TInfo;
925 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
926 if (T.isNull())
927 return ParsedTemplateArgument();
928 assert(TInfo && "template argument with no location");
929
930 // If we might have formed a deduced template specialization type, convert
931 // it to a template template argument.
932 if (getLangOpts().CPlusPlus17) {
933 TypeLoc TL = TInfo->getTypeLoc();
934 SourceLocation EllipsisLoc;
935 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
936 EllipsisLoc = PET.getEllipsisLoc();
937 TL = PET.getPatternLoc();
938 }
939
940 CXXScopeSpec SS;
941 if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
942 SS.Adopt(ET.getQualifierLoc());
943 TL = ET.getNamedTypeLoc();
944 }
945
946 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
947 TemplateName Name = DTST.getTypePtr()->getTemplateName();
948 if (SS.isSet())
949 Name = Context.getQualifiedTemplateName(SS.getScopeRep(),
950 /*HasTemplateKeyword*/ false,
951 Name.getAsTemplateDecl());
952 ParsedTemplateArgument Result(SS, TemplateTy::make(Name),
953 DTST.getTemplateNameLoc());
954 if (EllipsisLoc.isValid())
955 Result = Result.getTemplatePackExpansion(EllipsisLoc);
956 return Result;
957 }
958 }
959
960 // This is a normal type template argument. Note, if the type template
961 // argument is an injected-class-name for a template, it has a dual nature
Fangrui Song6907ce22018-07-30 19:24:48 +0000962 // and can be used as either a type or a template. We handle that in
Richard Smith77a9c602018-02-28 03:02:23 +0000963 // convertTypeTemplateArgumentToTemplate.
964 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
965 ParsedType.get().getAsOpaquePtr(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000966 TInfo->getTypeLoc().getBeginLoc());
Richard Smith77a9c602018-02-28 03:02:23 +0000967}
968
Douglas Gregor5101c242008-12-05 18:15:24 +0000969/// ActOnTypeParameter - Called when a C++ template type parameter
970/// (e.g., "typename T") has been parsed. Typename specifies whether
971/// the keyword "typename" was used to declare the type parameter
972/// (otherwise, "class" was used), and KeyLoc is the location of the
973/// "class" or "typename" keyword. ParamName is the name of the
974/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth08836322011-05-01 00:51:33 +0000975/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000976/// If the type parameter has a default argument, it will be added
977/// later via ActOnTypeParameterDefault.
Faisal Valibe294032017-12-23 18:56:34 +0000978NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
John McCall48871652010-08-21 09:40:31 +0000979 SourceLocation EllipsisLoc,
980 SourceLocation KeyLoc,
981 IdentifierInfo *ParamName,
982 SourceLocation ParamNameLoc,
983 unsigned Depth, unsigned Position,
984 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000985 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000986 assert(S->isTemplateParamScope() &&
987 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000988
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000989 bool IsParameterPack = EllipsisLoc.isValid();
Kadir Cetinkayafd019ed2019-10-01 14:08:51 +0000990 TemplateTypeParmDecl *Param = TemplateTypeParmDecl::Create(
991 Context, Context.getTranslationUnitDecl(), KeyLoc, ParamNameLoc, Depth,
992 Position, ParamName, Typename, IsParameterPack);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000993 Param->setAccess(AS_public);
Douglas Gregor5101c242008-12-05 18:15:24 +0000994
Richard Smithb26bc342019-08-26 22:51:28 +0000995 if (Param->isParameterPack())
996 if (auto *LSI = getEnclosingLambda())
997 LSI->LocalPacks.push_back(Param);
998
Douglas Gregor5101c242008-12-05 18:15:24 +0000999 if (ParamName) {
Richard Smithb80d5402013-06-25 22:21:36 +00001000 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1001
Douglas Gregor5101c242008-12-05 18:15:24 +00001002 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +00001003 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +00001004 IdResolver.AddDecl(Param);
1005 }
1006
Douglas Gregorf5500772011-01-05 15:48:55 +00001007 // C++0x [temp.param]p9:
1008 // A default template-argument may be specified for any kind of
1009 // template-parameter that is not a template parameter pack.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +00001010 if (DefaultArg && IsParameterPack) {
Douglas Gregorf5500772011-01-05 15:48:55 +00001011 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
David Blaikieefdccaa2016-01-15 23:43:34 +00001012 DefaultArg = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +00001013 }
1014
Douglas Gregordc13ded2010-07-01 00:00:45 +00001015 // Handle the default argument, if provided.
1016 if (DefaultArg) {
1017 TypeSourceInfo *DefaultTInfo;
1018 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001019
Douglas Gregordc13ded2010-07-01 00:00:45 +00001020 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001021
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001022 // Check for unexpanded parameter packs.
Kadir Cetinkayafd019ed2019-10-01 14:08:51 +00001023 if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001024 UPPC_DefaultArgument))
1025 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001026
Douglas Gregordc13ded2010-07-01 00:00:45 +00001027 // Check the template argument itself.
1028 if (CheckTemplateArgument(Param, DefaultTInfo)) {
1029 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +00001030 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +00001031 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001032
Richard Smith1469b912015-06-10 00:29:03 +00001033 Param->setDefaultArgument(DefaultTInfo);
Douglas Gregordc13ded2010-07-01 00:00:45 +00001034 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001035
John McCall48871652010-08-21 09:40:31 +00001036 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +00001037}
1038
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001039/// Check that the type of a non-type template parameter is
Douglas Gregor463421d2009-03-03 04:44:36 +00001040/// well-formed.
1041///
1042/// \returns the (possibly-promoted) parameter type if valid;
1043/// otherwise, produces a diagnostic and returns a NULL type.
Richard Smith15361a22016-12-28 06:27:18 +00001044QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
1045 SourceLocation Loc) {
1046 if (TSI->getType()->isUndeducedType()) {
Erik Pilkington9f9462a2018-08-07 22:59:02 +00001047 // C++17 [temp.dep.expr]p3:
Richard Smith15361a22016-12-28 06:27:18 +00001048 // An id-expression is type-dependent if it contains
1049 // - an identifier associated by name lookup with a non-type
1050 // template-parameter declared with a type that contains a
1051 // placeholder type (7.1.7.4),
1052 TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
1053 }
1054
1055 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1056}
1057
1058QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
1059 SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +00001060 // We don't allow variably-modified types as the type of non-type template
1061 // parameters.
1062 if (T->isVariablyModifiedType()) {
1063 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1064 << T;
1065 return QualType();
1066 }
1067
Douglas Gregor463421d2009-03-03 04:44:36 +00001068 // C++ [temp.param]p4:
1069 //
1070 // A non-type template-parameter shall have one of the following
1071 // (optionally cv-qualified) types:
1072 //
1073 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +00001074 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +00001075 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +00001076 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +00001077 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +00001078 T->isReferenceType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +00001079 // -- pointer to member,
Douglas Gregor463421d2009-03-03 04:44:36 +00001080 T->isMemberPointerType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +00001081 // -- std::nullptr_t.
1082 T->isNullPtrType() ||
Richard Smith5f274382016-09-28 23:55:27 +00001083 // Allow use of auto in template parameter declarations.
1084 T->isUndeducedType()) {
Richard Smithd0e1c952012-03-13 07:21:50 +00001085 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1086 // are ignored when determining its type.
1087 return T.getUnqualifiedType();
1088 }
1089
Douglas Gregor463421d2009-03-03 04:44:36 +00001090 // C++ [temp.param]p8:
1091 //
1092 // A non-type template-parameter of type "array of T" or
1093 // "function returning T" is adjusted to be of type "pointer to
1094 // T" or "pointer to function returning T", respectively.
Richard Smith9d1eba12019-10-11 01:29:53 +00001095 if (T->isArrayType() || T->isFunctionType())
Richard Smithd663fdd2014-12-17 20:42:37 +00001096 return Context.getDecayedType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001097
Richard Smith9d1eba12019-10-11 01:29:53 +00001098 // If T is a dependent type, we can't do the check now, so we
1099 // assume that it is well-formed. Note that stripping off the
1100 // qualifiers here is not really correct if T turns out to be
1101 // an array type, but we'll recompute the type everywhere it's
1102 // used during instantiation, so that should be OK. (Using the
1103 // qualified type is equally wrong.)
1104 if (T->isDependentType())
1105 return T.getUnqualifiedType();
1106
Douglas Gregor463421d2009-03-03 04:44:36 +00001107 Diag(Loc, diag::err_template_nontype_parm_bad_type)
1108 << T;
1109
1110 return QualType();
1111}
1112
Faisal Valibe294032017-12-23 18:56:34 +00001113NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
John McCall48871652010-08-21 09:40:31 +00001114 unsigned Depth,
1115 unsigned Position,
1116 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +00001117 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +00001118 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Richard Smith15361a22016-12-28 06:27:18 +00001119
Faisal Valia223d1c2017-12-22 03:50:55 +00001120 // Check that we have valid decl-specifiers specified.
1121 auto CheckValidDeclSpecifiers = [this, &D] {
1122 // C++ [temp.param]
Fangrui Song6907ce22018-07-30 19:24:48 +00001123 // p1
Malcolm Parsonsfab36802018-04-16 08:31:08 +00001124 // template-parameter:
1125 // ...
1126 // parameter-declaration
Fangrui Song6907ce22018-07-30 19:24:48 +00001127 // p2
Faisal Valia223d1c2017-12-22 03:50:55 +00001128 // ... A storage class shall not be specified in a template-parameter
1129 // declaration.
Fangrui Song6907ce22018-07-30 19:24:48 +00001130 // [dcl.typedef]p1:
Faisal Valia223d1c2017-12-22 03:50:55 +00001131 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1132 // of a parameter-declaration
1133 const DeclSpec &DS = D.getDeclSpec();
1134 auto EmitDiag = [this](SourceLocation Loc) {
1135 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1136 << FixItHint::CreateRemoval(Loc);
1137 };
1138 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1139 EmitDiag(DS.getStorageClassSpecLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00001140
Sam McCall1371cba2017-12-22 07:09:51 +00001141 if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
Faisal Valia223d1c2017-12-22 03:50:55 +00001142 EmitDiag(DS.getThreadStorageClassSpecLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00001143
1144 // [dcl.inline]p1:
1145 // The inline specifier can be applied only to the declaration or
Faisal Valia223d1c2017-12-22 03:50:55 +00001146 // definition of a variable or function.
Fangrui Song6907ce22018-07-30 19:24:48 +00001147
Faisal Valia223d1c2017-12-22 03:50:55 +00001148 if (DS.isInlineSpecified())
1149 EmitDiag(DS.getInlineSpecLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00001150
Faisal Valia223d1c2017-12-22 03:50:55 +00001151 // [dcl.constexpr]p1:
Fangrui Song6907ce22018-07-30 19:24:48 +00001152 // The constexpr specifier shall be applied only to the definition of a
1153 // variable or variable template or the declaration of a function or
Faisal Valia223d1c2017-12-22 03:50:55 +00001154 // function template.
Fangrui Song6907ce22018-07-30 19:24:48 +00001155
Gauthier Harnisch796ed032019-06-14 08:56:20 +00001156 if (DS.hasConstexprSpecifier())
Faisal Valia223d1c2017-12-22 03:50:55 +00001157 EmitDiag(DS.getConstexprSpecLoc());
1158
1159 // [dcl.fct.spec]p1:
1160 // Function-specifiers can be used only in function declarations.
1161
1162 if (DS.isVirtualSpecified())
1163 EmitDiag(DS.getVirtualSpecLoc());
1164
Richard Smith76b90272019-05-09 03:59:21 +00001165 if (DS.hasExplicitSpecifier())
Faisal Valia223d1c2017-12-22 03:50:55 +00001166 EmitDiag(DS.getExplicitSpecLoc());
1167
1168 if (DS.isNoreturnSpecified())
1169 EmitDiag(DS.getNoreturnSpecLoc());
1170 };
1171
1172 CheckValidDeclSpecifiers();
Fangrui Song6907ce22018-07-30 19:24:48 +00001173
Richard Smith15361a22016-12-28 06:27:18 +00001174 if (TInfo->getType()->isUndeducedType()) {
1175 Diag(D.getIdentifierLoc(),
1176 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1177 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1178 }
Douglas Gregor5101c242008-12-05 18:15:24 +00001179
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001180 assert(S->isTemplateParamScope() &&
1181 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +00001182 bool Invalid = false;
1183
Richard Smith15361a22016-12-28 06:27:18 +00001184 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001185 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001186 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +00001187 Invalid = true;
1188 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001189
Richard Smithda70fc02019-06-14 20:01:54 +00001190 CheckFunctionOrTemplateParamDeclarator(S, D);
1191
Richard Smithb80d5402013-06-25 22:21:36 +00001192 IdentifierInfo *ParamName = D.getIdentifier();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +00001193 bool IsParameterPack = D.hasEllipsis();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001194 NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
1195 Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1196 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1197 TInfo);
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001198 Param->setAccess(AS_public);
Richard Smithb80d5402013-06-25 22:21:36 +00001199
Douglas Gregor5101c242008-12-05 18:15:24 +00001200 if (Invalid)
1201 Param->setInvalidDecl();
1202
Richard Smithb26bc342019-08-26 22:51:28 +00001203 if (Param->isParameterPack())
1204 if (auto *LSI = getEnclosingLambda())
1205 LSI->LocalPacks.push_back(Param);
1206
Richard Smithb80d5402013-06-25 22:21:36 +00001207 if (ParamName) {
1208 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1209 ParamName);
1210
Douglas Gregor5101c242008-12-05 18:15:24 +00001211 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +00001212 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +00001213 IdResolver.AddDecl(Param);
1214 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001215
Douglas Gregorf5500772011-01-05 15:48:55 +00001216 // C++0x [temp.param]p9:
1217 // A default template-argument may be specified for any kind of
1218 // template-parameter that is not a template parameter pack.
1219 if (Default && IsParameterPack) {
1220 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
Craig Topperc3ec1492014-05-26 06:22:03 +00001221 Default = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +00001222 }
1223
Douglas Gregordc13ded2010-07-01 00:00:45 +00001224 // Check the well-formedness of the default template argument, if provided.
Douglas Gregorda3cc0d2010-12-23 23:51:58 +00001225 if (Default) {
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001226 // Check for unexpanded parameter packs.
1227 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
1228 return Param;
1229
Douglas Gregordc13ded2010-07-01 00:00:45 +00001230 TemplateArgument Converted;
Richard Smithd663fdd2014-12-17 20:42:37 +00001231 ExprResult DefaultRes =
1232 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
John Wiegley01296292011-04-08 18:41:53 +00001233 if (DefaultRes.isInvalid()) {
Douglas Gregordc13ded2010-07-01 00:00:45 +00001234 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +00001235 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +00001236 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001237 Default = DefaultRes.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001238
Richard Smith1469b912015-06-10 00:29:03 +00001239 Param->setDefaultArgument(Default);
Douglas Gregordc13ded2010-07-01 00:00:45 +00001240 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001241
John McCall48871652010-08-21 09:40:31 +00001242 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +00001243}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001244
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001245/// ActOnTemplateTemplateParameter - Called when a C++ template template
James Dennett2a4d13c2012-06-15 07:13:21 +00001246/// parameter (e.g. T in template <template \<typename> class T> class array)
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001247/// has been parsed. S is the current scope.
Faisal Valibe294032017-12-23 18:56:34 +00001248NamedDecl *Sema::ActOnTemplateTemplateParameter(Scope* S,
John McCall48871652010-08-21 09:40:31 +00001249 SourceLocation TmpLoc,
Richard Trieu9becef62011-09-09 03:18:59 +00001250 TemplateParameterList *Params,
Douglas Gregorf5500772011-01-05 15:48:55 +00001251 SourceLocation EllipsisLoc,
John McCall48871652010-08-21 09:40:31 +00001252 IdentifierInfo *Name,
1253 SourceLocation NameLoc,
1254 unsigned Depth,
1255 unsigned Position,
1256 SourceLocation EqualLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +00001257 ParsedTemplateArgument Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001258 assert(S->isTemplateParamScope() &&
1259 "Template template parameter not in template parameter scope!");
1260
1261 // Construct the parameter object.
Douglas Gregorf5500772011-01-05 15:48:55 +00001262 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001263 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +00001264 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001265 NameLoc.isInvalid()? TmpLoc : NameLoc,
1266 Depth, Position, IsParameterPack,
Douglas Gregorf5500772011-01-05 15:48:55 +00001267 Name, Params);
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001268 Param->setAccess(AS_public);
Simon Pilgrim6905d222016-12-30 22:55:33 +00001269
Richard Smithb26bc342019-08-26 22:51:28 +00001270 if (Param->isParameterPack())
1271 if (auto *LSI = getEnclosingLambda())
1272 LSI->LocalPacks.push_back(Param);
1273
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001274 // If the template template parameter has a name, then link the identifier
Douglas Gregordc13ded2010-07-01 00:00:45 +00001275 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001276 if (Name) {
Richard Smithb80d5402013-06-25 22:21:36 +00001277 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1278
John McCall48871652010-08-21 09:40:31 +00001279 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001280 IdResolver.AddDecl(Param);
1281 }
1282
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001283 if (Params->size() == 0) {
1284 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1285 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1286 Param->setInvalidDecl();
1287 }
1288
Douglas Gregorf5500772011-01-05 15:48:55 +00001289 // C++0x [temp.param]p9:
1290 // A default template-argument may be specified for any kind of
1291 // template-parameter that is not a template parameter pack.
1292 if (IsParameterPack && !Default.isInvalid()) {
1293 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1294 Default = ParsedTemplateArgument();
1295 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001296
Douglas Gregordc13ded2010-07-01 00:00:45 +00001297 if (!Default.isInvalid()) {
1298 // Check only that we have a template template argument. We don't want to
1299 // try to check well-formedness now, because our template template parameter
1300 // might have dependent types in its template parameters, which we wouldn't
1301 // be able to match now.
1302 //
1303 // If none of the template template parameter's template arguments mention
1304 // other template parameters, we could actually perform more checking here.
1305 // However, it isn't worth doing.
1306 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1307 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
Faisal Valib8b04f82016-03-26 20:46:45 +00001308 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
Douglas Gregordc13ded2010-07-01 00:00:45 +00001309 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00001310 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +00001311 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001312
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001313 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001314 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001315 DefaultArg.getArgument().getAsTemplate(),
1316 UPPC_DefaultArgument))
1317 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001318
Richard Smith1469b912015-06-10 00:29:03 +00001319 Param->setDefaultArgument(Context, DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +00001320 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001321
John McCall48871652010-08-21 09:40:31 +00001322 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +00001323}
1324
Hubert Tongf608c052016-04-29 18:05:37 +00001325/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1326/// constrained by RequiresClause, that contains the template parameters in
1327/// Params.
Richard Trieu9becef62011-09-09 03:18:59 +00001328TemplateParameterList *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001329Sema::ActOnTemplateParameterList(unsigned Depth,
1330 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001331 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001332 SourceLocation LAngleLoc,
Faisal Valif241b0d2017-08-25 18:24:20 +00001333 ArrayRef<NamedDecl *> Params,
Hubert Tongf608c052016-04-29 18:05:37 +00001334 SourceLocation RAngleLoc,
1335 Expr *RequiresClause) {
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001336 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001337 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001338
David Majnemer902f8c62015-12-27 07:16:27 +00001339 return TemplateParameterList::Create(
1340 Context, TemplateLoc, LAngleLoc,
Faisal Valif241b0d2017-08-25 18:24:20 +00001341 llvm::makeArrayRef(Params.data(), Params.size()),
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00001342 RAngleLoc, RequiresClause);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001343}
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001344
Bruno Ricci4224c872018-12-21 14:35:24 +00001345static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
1346 const CXXScopeSpec &SS) {
John McCall3e11ebe2010-03-15 10:12:16 +00001347 if (SS.isSet())
Bruno Ricci4224c872018-12-21 14:35:24 +00001348 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
John McCall3e11ebe2010-03-15 10:12:16 +00001349}
1350
Erich Keanec480f302018-07-12 21:09:05 +00001351DeclResult Sema::CheckClassTemplate(
1352 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1353 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1354 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1355 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1356 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1357 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
Mike Stump11289f42009-09-09 15:08:12 +00001358 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001359 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +00001360 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +00001361 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001362
1363 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001364 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001365 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001366
Abramo Bagnara6150c882010-05-11 21:36:43 +00001367 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1368 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001369
1370 // There is no such thing as an unnamed class template.
1371 if (!Name) {
1372 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001373 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001374 }
1375
Richard Smith6483d222012-04-21 01:27:54 +00001376 // Find any previous declaration with this name. For a friend with no
1377 // scope explicitly specified, we only look for tag declarations (per
1378 // C++11 [basic.lookup.elab]p2).
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001379 DeclContext *SemanticContext;
Richard Smith6483d222012-04-21 01:27:54 +00001380 LookupResult Previous(*this, Name, NameLoc,
1381 (SS.isEmpty() && TUK == TUK_Friend)
1382 ? LookupTagName : LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00001383 forRedeclarationInCurContext());
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001384 if (SS.isNotEmpty() && !SS.isInvalid()) {
1385 SemanticContext = computeDeclContext(SS, true);
1386 if (!SemanticContext) {
Douglas Gregor67daacb2012-03-30 16:20:47 +00001387 // FIXME: Horrible, horrible hack! We can't currently represent this
1388 // in the AST, and historically we have just ignored such friend
1389 // class templates, so don't complain here.
Richard Smithcd556eb2013-11-08 18:59:56 +00001390 Diag(NameLoc, TUK == TUK_Friend
1391 ? diag::warn_template_qualified_friend_ignored
1392 : diag::err_template_qualified_declarator_no_match)
Douglas Gregor67daacb2012-03-30 16:20:47 +00001393 << SS.getScopeRep() << SS.getRange();
Richard Smithcd556eb2013-11-08 18:59:56 +00001394 return TUK != TUK_Friend;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001395 }
Mike Stump11289f42009-09-09 15:08:12 +00001396
John McCall0b66eb32010-05-01 00:40:08 +00001397 if (RequireCompleteDeclContext(SS, SemanticContext))
1398 return true;
1399
Simon Pilgrim6905d222016-12-30 22:55:33 +00001400 // If we're adding a template to a dependent context, we may need to
1401 // rebuilding some of the types used within the template parameter list,
Douglas Gregor041b0842011-10-14 15:31:12 +00001402 // now that we know what the current instantiation is.
1403 if (SemanticContext->isDependentContext()) {
1404 ContextRAII SavedContext(*this, SemanticContext);
1405 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1406 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00001407 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
Richard Smithc660c8f2018-03-16 13:36:56 +00001408 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc, false);
Richard Smith6483d222012-04-21 01:27:54 +00001409
John McCall27b18f82009-11-17 02:14:36 +00001410 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001411 } else {
1412 SemanticContext = CurContext;
Richard Smith88fe69c2015-07-06 01:45:27 +00001413
1414 // C++14 [class.mem]p14:
1415 // If T is the name of a class, then each of the following shall have a
1416 // name different from T:
1417 // -- every member template of class T
1418 if (TUK != TUK_Friend &&
1419 DiagnoseClassNameShadow(SemanticContext,
1420 DeclarationNameInfo(Name, NameLoc)))
1421 return true;
1422
John McCall27b18f82009-11-17 02:14:36 +00001423 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001424 }
Mike Stump11289f42009-09-09 15:08:12 +00001425
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001426 if (Previous.isAmbiguous())
1427 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001428
Craig Topperc3ec1492014-05-26 06:22:03 +00001429 NamedDecl *PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001430 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001431 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001432
Serge Pavlove50bf752016-06-10 04:39:07 +00001433 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1434 // Maybe we will complain about the shadowed template parameter.
1435 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1436 // Just pretend that we didn't see the previous declaration.
1437 PrevDecl = nullptr;
1438 }
1439
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001440 // If there is a previous declaration with the same name, check
1441 // whether this is a valid redeclaration.
Richard Smithbecb92d2017-10-10 22:33:17 +00001442 ClassTemplateDecl *PrevClassTemplate =
1443 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001444
1445 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001446 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001447 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001448 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001449 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1450 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001451 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001452 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1453 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1454 PrevClassTemplate
1455 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1456 ->getSpecializedTemplate();
1457 }
1458 }
1459
John McCalld43784f2009-12-18 11:25:59 +00001460 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +00001461 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001462 // [...] When looking for a prior declaration of a class or a function
1463 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +00001464 // function is neither a qualified name nor a template-id, scopes outside
1465 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +00001466 if (!SS.isSet()) {
1467 DeclContext *OutermostContext = CurContext;
1468 while (!OutermostContext->isFileContext())
1469 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +00001470
Richard Smith61e582f2012-04-20 07:12:26 +00001471 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +00001472 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1473 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1474 SemanticContext = PrevDecl->getDeclContext();
1475 } else {
1476 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001477 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +00001478 // declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00001479 PrevDecl = PrevClassTemplate = nullptr;
Douglas Gregorb74b1032010-04-18 17:37:40 +00001480 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +00001481
1482 // Check that the chosen semantic context doesn't already contain a
1483 // declaration of this name as a non-tag type.
Richard Smithfc805ca2015-07-06 04:43:58 +00001484 Previous.clear(LookupOrdinaryName);
Richard Smith6483d222012-04-21 01:27:54 +00001485 DeclContext *LookupContext = SemanticContext;
1486 while (LookupContext->isTransparentContext())
1487 LookupContext = LookupContext->getLookupParent();
1488 LookupQualifiedName(Previous, LookupContext);
1489
1490 if (Previous.isAmbiguous())
1491 return true;
1492
1493 if (Previous.begin() != Previous.end())
1494 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +00001495 }
John McCall90d3bb92009-12-17 23:21:11 +00001496 }
Richard Smith72bcaec2013-12-05 04:30:04 +00001497 } else if (PrevDecl &&
Richard Smithfc805ca2015-07-06 04:43:58 +00001498 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1499 S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +00001500 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001501
Richard Smithfc805ca2015-07-06 04:43:58 +00001502 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1503 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1504 if (SS.isEmpty() &&
1505 !(PrevClassTemplate &&
1506 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1507 SemanticContext->getRedeclContext()))) {
1508 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1509 Diag(Shadow->getTargetDecl()->getLocation(),
1510 diag::note_using_decl_target);
1511 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1512 // Recover by ignoring the old declaration.
1513 PrevDecl = PrevClassTemplate = nullptr;
1514 }
1515 }
1516
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001517 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +00001518 // Ensure that the template parameter lists are compatible. Skip this check
1519 // for a friend in a dependent context: the template parameter list itself
1520 // could be dependent.
1521 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1522 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001523 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001524 /*Complain=*/true,
1525 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001526 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001527
1528 // C++ [temp.class]p4:
1529 // In a redeclaration, partial specialization, explicit
1530 // specialization or explicit instantiation of a class template,
1531 // the class-key shall agree in kind with the original class
1532 // template declaration (7.1.5.3).
1533 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +00001534 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001535 TUK == TUK_Definition, KWLoc, Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00001536 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00001537 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00001538 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001539 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00001540 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001541 }
1542
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001543 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +00001544 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001545 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001546 // If we have a prior definition that is not visible, treat this as
1547 // simply making that previous definition visible.
1548 NamedDecl *Hidden = nullptr;
1549 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
Richard Smithd9ba2242015-05-07 03:54:19 +00001550 SkipBody->ShouldSkip = true;
Richard Smithc4577662018-09-12 02:13:47 +00001551 SkipBody->Previous = Def;
Richard Smithbe3980b2015-03-27 00:41:57 +00001552 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1553 assert(Tmpl && "original definition of a class template is not a "
1554 "class template?");
Richard Smith858e0e02017-05-11 23:11:16 +00001555 makeMergedDefinitionVisible(Hidden);
1556 makeMergedDefinitionVisible(Tmpl);
Richard Smithc4577662018-09-12 02:13:47 +00001557 } else {
1558 Diag(NameLoc, diag::err_redefinition) << Name;
1559 Diag(Def->getLocation(), diag::note_previous_definition);
1560 // FIXME: Would it make sense to try to "forget" the previous
1561 // definition, as part of error recovery?
1562 return true;
Richard Smithbe3980b2015-03-27 00:41:57 +00001563 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001564 }
Serge Pavlove50bf752016-06-10 04:39:07 +00001565 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001566 } else if (PrevDecl) {
1567 // C++ [temp]p5:
1568 // A class template shall not have the same name as any other
1569 // template, class, function, object, enumeration, enumerator,
1570 // namespace, or type in the same scope (3.3), except as specified
1571 // in (14.5.4).
1572 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1573 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001574 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001575 }
1576
Douglas Gregordba32632009-02-10 19:49:53 +00001577 // Check the template parameter list of this declaration, possibly
1578 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001579 // template declaration. Skip this check for a friend in a dependent
1580 // context, because the template parameter list might be dependent.
1581 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001582 CheckTemplateParameterList(
1583 TemplateParams,
Richard Smithc4577662018-09-12 02:13:47 +00001584 PrevClassTemplate
1585 ? PrevClassTemplate->getMostRecentDecl()->getTemplateParameters()
1586 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001587 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1588 SemanticContext->isDependentContext())
1589 ? TPC_ClassTemplateMember
Richard Smithc4577662018-09-12 02:13:47 +00001590 : TUK == TUK_Friend ? TPC_FriendClassTemplate : TPC_ClassTemplate,
1591 SkipBody))
Douglas Gregordba32632009-02-10 19:49:53 +00001592 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001593
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001594 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001595 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001596 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001597 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1598 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001599 : diag::err_member_decl_does_not_match)
1600 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001601 Invalid = true;
1602 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001603 }
1604
Vassil Vassilev352e4412017-01-12 09:16:26 +00001605 // If this is a templated friend in a dependent context we should not put it
1606 // on the redecl chain. In some cases, the templated friend can be the most
1607 // recent declaration tricking the template instantiator to make substitutions
1608 // there.
1609 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1610 bool ShouldAddRedecl
1611 = !(TUK == TUK_Friend && CurContext->isDependentContext());
1612
Mike Stump11289f42009-09-09 15:08:12 +00001613 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001614 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Vassil Vassilev352e4412017-01-12 09:16:26 +00001615 PrevClassTemplate && ShouldAddRedecl ?
Craig Topperc3ec1492014-05-26 06:22:03 +00001616 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001617 /*DelayTypeCreation=*/true);
Bruno Ricci4224c872018-12-21 14:35:24 +00001618 SetNestedNameSpecifier(*this, NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001619 if (NumOuterTemplateParamLists > 0)
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001620 NewClass->setTemplateParameterListsInfo(
1621 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1622 NumOuterTemplateParamLists));
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001623
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001624 // Add alignment attributes if necessary; these attributes are checked when
1625 // the ASTContext lays out the structure.
Richard Smithc4577662018-09-12 02:13:47 +00001626 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
Eli Friedman0415f3e12012-08-08 21:08:34 +00001627 AddAlignmentAttributesForRecord(NewClass);
1628 AddMsStructLayoutForRecord(NewClass);
1629 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001630
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001631 ClassTemplateDecl *NewTemplate
1632 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1633 DeclarationName(Name), TemplateParams,
Saar Raz0330fba2019-10-15 18:44:06 +00001634 NewClass);
Vassil Vassilev352e4412017-01-12 09:16:26 +00001635
1636 if (ShouldAddRedecl)
1637 NewTemplate->setPreviousDecl(PrevClassTemplate);
1638
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001639 NewClass->setDescribedClassTemplate(NewTemplate);
Simon Pilgrim6905d222016-12-30 22:55:33 +00001640
Douglas Gregor21823bf2011-12-20 18:11:52 +00001641 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001642 NewTemplate->setModulePrivate();
Simon Pilgrim6905d222016-12-30 22:55:33 +00001643
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001644 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001645 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001646 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001647 assert(T->isDependentType() && "Class template type is not dependent?");
1648 (void)T;
1649
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001650 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001651 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001652 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001653 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1654 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001655
Anders Carlsson137108d2009-03-26 01:24:28 +00001656 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001657 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001658 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001659
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001660 // Set the lexical context of these templates
1661 NewClass->setLexicalDeclContext(CurContext);
1662 NewTemplate->setLexicalDeclContext(CurContext);
1663
Richard Smithc4577662018-09-12 02:13:47 +00001664 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001665 NewClass->startDefinition();
1666
Erich Keanec480f302018-07-12 21:09:05 +00001667 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001668
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001669 if (PrevClassTemplate)
1670 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1671
Rafael Espindola385c0422012-07-13 18:04:45 +00001672 AddPushedVisibilityAttribute(NewClass);
Matthias Gehre23092ca2019-08-07 10:45:36 +00001673 inferGslOwnerPointerAttribute(NewClass);
Rafael Espindola385c0422012-07-13 18:04:45 +00001674
Richard Smith234ff472014-08-23 00:49:01 +00001675 if (TUK != TUK_Friend) {
1676 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1677 Scope *Outer = S;
1678 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1679 Outer = Outer->getParent();
1680 PushOnScopeChains(NewTemplate, Outer);
1681 } else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001682 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001683 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001684 NewClass->setAccess(PrevClassTemplate->getAccess());
1685 }
John McCall27b5c252009-09-14 21:59:20 +00001686
Richard Smith64017682013-07-17 23:53:16 +00001687 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001688
John McCall27b5c252009-09-14 21:59:20 +00001689 // Friend templates are visible in fairly strange ways.
1690 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001691 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001692 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001693 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1694 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001695 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001696 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001697
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001698 FriendDecl *Friend = FriendDecl::Create(
1699 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
Douglas Gregor3dad8422009-09-26 06:47:28 +00001700 Friend->setAccess(AS_public);
1701 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001702 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001703
Richard Smithbecb92d2017-10-10 22:33:17 +00001704 if (PrevClassTemplate)
1705 CheckRedeclarationModuleOwnership(NewTemplate, PrevClassTemplate);
1706
Douglas Gregordba32632009-02-10 19:49:53 +00001707 if (Invalid) {
1708 NewTemplate->setInvalidDecl();
1709 NewClass->setInvalidDecl();
1710 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001711
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001712 ActOnDocumentableDecl(NewTemplate);
1713
Richard Smithc4577662018-09-12 02:13:47 +00001714 if (SkipBody && SkipBody->ShouldSkip)
1715 return SkipBody->Previous;
1716
John McCall48871652010-08-21 09:40:31 +00001717 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001718}
1719
Richard Smith32918772017-02-14 00:25:28 +00001720namespace {
Erik Pilkington69770d32018-07-27 21:23:48 +00001721/// Tree transform to "extract" a transformed type from a class template's
1722/// constructor to a deduction guide.
1723class ExtractTypeForDeductionGuide
1724 : public TreeTransform<ExtractTypeForDeductionGuide> {
1725public:
1726 typedef TreeTransform<ExtractTypeForDeductionGuide> Base;
1727 ExtractTypeForDeductionGuide(Sema &SemaRef) : Base(SemaRef) {}
1728
1729 TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); }
1730
1731 QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) {
1732 return TransformType(
1733 TLB,
1734 TL.getTypedefNameDecl()->getTypeSourceInfo()->getTypeLoc());
1735 }
1736};
1737
Richard Smith32918772017-02-14 00:25:28 +00001738/// Transform to convert portions of a constructor declaration into the
1739/// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
1740struct ConvertConstructorToDeductionGuideTransform {
1741 ConvertConstructorToDeductionGuideTransform(Sema &S,
1742 ClassTemplateDecl *Template)
1743 : SemaRef(S), Template(Template) {}
1744
1745 Sema &SemaRef;
1746 ClassTemplateDecl *Template;
1747
1748 DeclContext *DC = Template->getDeclContext();
1749 CXXRecordDecl *Primary = Template->getTemplatedDecl();
1750 DeclarationName DeductionGuideName =
1751 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
1752
1753 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
1754
1755 // Index adjustment to apply to convert depth-1 template parameters into
1756 // depth-0 template parameters.
1757 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
1758
1759 /// Transform a constructor declaration into a deduction guide.
Richard Smithbc491202017-02-17 20:05:37 +00001760 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
1761 CXXConstructorDecl *CD) {
Richard Smith32918772017-02-14 00:25:28 +00001762 SmallVector<TemplateArgument, 16> SubstArgs;
1763
Richard Smithb4f96252017-02-21 06:30:38 +00001764 LocalInstantiationScope Scope(SemaRef);
1765
Richard Smith32918772017-02-14 00:25:28 +00001766 // C++ [over.match.class.deduct]p1:
1767 // -- For each constructor of the class template designated by the
1768 // template-name, a function template with the following properties:
1769
1770 // -- The template parameters are the template parameters of the class
1771 // template followed by the template parameters (including default
1772 // template arguments) of the constructor, if any.
1773 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
1774 if (FTD) {
1775 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
1776 SmallVector<NamedDecl *, 16> AllParams;
1777 AllParams.reserve(TemplateParams->size() + InnerParams->size());
1778 AllParams.insert(AllParams.begin(),
1779 TemplateParams->begin(), TemplateParams->end());
1780 SubstArgs.reserve(InnerParams->size());
1781
1782 // Later template parameters could refer to earlier ones, so build up
1783 // a list of substituted template arguments as we go.
1784 for (NamedDecl *Param : *InnerParams) {
1785 MultiLevelTemplateArgumentList Args;
1786 Args.addOuterTemplateArguments(SubstArgs);
Richard Smithb4f96252017-02-21 06:30:38 +00001787 Args.addOuterRetainedLevel();
Richard Smith32918772017-02-14 00:25:28 +00001788 NamedDecl *NewParam = transformTemplateParameter(Param, Args);
1789 if (!NewParam)
1790 return nullptr;
1791 AllParams.push_back(NewParam);
1792 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
1793 SemaRef.Context.getInjectedTemplateArg(NewParam)));
1794 }
1795 TemplateParams = TemplateParameterList::Create(
1796 SemaRef.Context, InnerParams->getTemplateLoc(),
1797 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
1798 /*FIXME: RequiresClause*/ nullptr);
1799 }
1800
1801 // If we built a new template-parameter-list, track that we need to
1802 // substitute references to the old parameters into references to the
1803 // new ones.
1804 MultiLevelTemplateArgumentList Args;
1805 if (FTD) {
1806 Args.addOuterTemplateArguments(SubstArgs);
Richard Smithb4f96252017-02-21 06:30:38 +00001807 Args.addOuterRetainedLevel();
Richard Smith32918772017-02-14 00:25:28 +00001808 }
1809
Richard Smithbc491202017-02-17 20:05:37 +00001810 FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
Richard Smith32918772017-02-14 00:25:28 +00001811 .getAsAdjusted<FunctionProtoTypeLoc>();
1812 assert(FPTL && "no prototype for constructor declaration");
1813
1814 // Transform the type of the function, adjusting the return type and
1815 // replacing references to the old parameters with references to the
1816 // new ones.
1817 TypeLocBuilder TLB;
1818 SmallVector<ParmVarDecl*, 8> Params;
1819 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args);
1820 if (NewType.isNull())
1821 return nullptr;
1822 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
1823
Richard Smith76b90272019-05-09 03:59:21 +00001824 return buildDeductionGuide(TemplateParams, CD->getExplicitSpecifier(),
1825 NewTInfo, CD->getBeginLoc(), CD->getLocation(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001826 CD->getEndLoc());
Richard Smith32918772017-02-14 00:25:28 +00001827 }
1828
1829 /// Build a deduction guide with the specified parameter types.
1830 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
1831 SourceLocation Loc = Template->getLocation();
1832
1833 // Build the requested type.
1834 FunctionProtoType::ExtProtoInfo EPI;
1835 EPI.HasTrailingReturn = true;
1836 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
1837 DeductionGuideName, EPI);
1838 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
1839
1840 FunctionProtoTypeLoc FPTL =
1841 TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
1842
1843 // Build the parameters, needed during deduction / substitution.
1844 SmallVector<ParmVarDecl*, 4> Params;
1845 for (auto T : ParamTypes) {
1846 ParmVarDecl *NewParam = ParmVarDecl::Create(
1847 SemaRef.Context, DC, Loc, Loc, nullptr, T,
1848 SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
1849 NewParam->setScopeInfo(0, Params.size());
1850 FPTL.setParam(Params.size(), NewParam);
1851 Params.push_back(NewParam);
1852 }
1853
Richard Smith76b90272019-05-09 03:59:21 +00001854 return buildDeductionGuide(Template->getTemplateParameters(),
1855 ExplicitSpecifier(), TSI, Loc, Loc, Loc);
Richard Smith32918772017-02-14 00:25:28 +00001856 }
1857
1858private:
1859 /// Transform a constructor template parameter into a deduction guide template
1860 /// parameter, rebuilding any internal references to earlier parameters and
1861 /// renumbering as we go.
1862 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
1863 MultiLevelTemplateArgumentList &Args) {
1864 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
1865 // TemplateTypeParmDecl's index cannot be changed after creation, so
1866 // substitute it directly.
1867 auto *NewTTP = TemplateTypeParmDecl::Create(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001868 SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(),
1869 /*Depth*/ 0, Depth1IndexAdjustment + TTP->getIndex(),
Richard Smith32918772017-02-14 00:25:28 +00001870 TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
1871 TTP->isParameterPack());
1872 if (TTP->hasDefaultArgument()) {
1873 TypeSourceInfo *InstantiatedDefaultArg =
1874 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
1875 TTP->getDefaultArgumentLoc(), TTP->getDeclName());
1876 if (InstantiatedDefaultArg)
1877 NewTTP->setDefaultArgument(InstantiatedDefaultArg);
1878 }
Richard Smithb4f96252017-02-21 06:30:38 +00001879 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
1880 NewTTP);
Richard Smith32918772017-02-14 00:25:28 +00001881 return NewTTP;
1882 }
1883
1884 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
1885 return transformTemplateParameterImpl(TTP, Args);
1886
1887 return transformTemplateParameterImpl(
1888 cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
1889 }
1890 template<typename TemplateParmDecl>
1891 TemplateParmDecl *
1892 transformTemplateParameterImpl(TemplateParmDecl *OldParam,
1893 MultiLevelTemplateArgumentList &Args) {
1894 // Ask the template instantiator to do the heavy lifting for us, then adjust
1895 // the index of the parameter once it's done.
1896 auto *NewParam =
1897 cast_or_null<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
1898 assert(NewParam->getDepth() == 0 && "unexpected template param depth");
1899 NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
1900 return NewParam;
1901 }
1902
1903 QualType transformFunctionProtoType(TypeLocBuilder &TLB,
1904 FunctionProtoTypeLoc TL,
1905 SmallVectorImpl<ParmVarDecl*> &Params,
1906 MultiLevelTemplateArgumentList &Args) {
1907 SmallVector<QualType, 4> ParamTypes;
1908 const FunctionProtoType *T = TL.getTypePtr();
1909
1910 // -- The types of the function parameters are those of the constructor.
1911 for (auto *OldParam : TL.getParams()) {
Richard Smithc27b3d72017-02-14 01:49:59 +00001912 ParmVarDecl *NewParam = transformFunctionTypeParam(OldParam, Args);
Richard Smith32918772017-02-14 00:25:28 +00001913 if (!NewParam)
1914 return QualType();
1915 ParamTypes.push_back(NewParam->getType());
1916 Params.push_back(NewParam);
1917 }
1918
1919 // -- The return type is the class template specialization designated by
1920 // the template-name and template arguments corresponding to the
1921 // template parameters obtained from the class template.
1922 //
1923 // We use the injected-class-name type of the primary template instead.
1924 // This has the convenient property that it is different from any type that
1925 // the user can write in a deduction-guide (because they cannot enter the
1926 // context of the template), so implicit deduction guides can never collide
1927 // with explicit ones.
1928 QualType ReturnType = DeducedType;
1929 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
1930
1931 // Resolving a wording defect, we also inherit the variadicness of the
1932 // constructor.
1933 FunctionProtoType::ExtProtoInfo EPI;
1934 EPI.Variadic = T->isVariadic();
1935 EPI.HasTrailingReturn = true;
1936
1937 QualType Result = SemaRef.BuildFunctionType(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001938 ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI);
Richard Smith32918772017-02-14 00:25:28 +00001939 if (Result.isNull())
1940 return QualType();
1941
1942 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
1943 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
1944 NewTL.setLParenLoc(TL.getLParenLoc());
1945 NewTL.setRParenLoc(TL.getRParenLoc());
1946 NewTL.setExceptionSpecRange(SourceRange());
1947 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
1948 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
1949 NewTL.setParam(I, Params[I]);
1950
1951 return Result;
1952 }
1953
1954 ParmVarDecl *
1955 transformFunctionTypeParam(ParmVarDecl *OldParam,
1956 MultiLevelTemplateArgumentList &Args) {
1957 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
Richard Smith479ba8e2017-04-20 01:15:31 +00001958 TypeSourceInfo *NewDI;
Erik Pilkington69770d32018-07-27 21:23:48 +00001959 if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
Richard Smith479ba8e2017-04-20 01:15:31 +00001960 // Expand out the one and only element in each inner pack.
1961 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
1962 NewDI =
1963 SemaRef.SubstType(PackTL.getPatternLoc(), Args,
1964 OldParam->getLocation(), OldParam->getDeclName());
1965 if (!NewDI) return nullptr;
1966 NewDI =
1967 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
1968 PackTL.getTypePtr()->getNumExpansions());
1969 } else
1970 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
1971 OldParam->getDeclName());
Richard Smith32918772017-02-14 00:25:28 +00001972 if (!NewDI)
1973 return nullptr;
1974
Erik Pilkington69770d32018-07-27 21:23:48 +00001975 // Extract the type. This (for instance) replaces references to typedef
1976 // members of the current instantiations with the definitions of those
1977 // typedefs, avoiding triggering instantiation of the deduced type during
1978 // deduction.
1979 NewDI = ExtractTypeForDeductionGuide(SemaRef).transform(NewDI);
Richard Smithc27b3d72017-02-14 01:49:59 +00001980
Richard Smith32918772017-02-14 00:25:28 +00001981 // Resolving a wording defect, we also inherit default arguments from the
1982 // constructor.
1983 ExprResult NewDefArg;
1984 if (OldParam->hasDefaultArg()) {
Erik Pilkington69770d32018-07-27 21:23:48 +00001985 NewDefArg = SemaRef.SubstExpr(OldParam->getDefaultArg(), Args);
Richard Smith32918772017-02-14 00:25:28 +00001986 if (NewDefArg.isInvalid())
1987 return nullptr;
1988 }
1989
1990 ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
1991 OldParam->getInnerLocStart(),
1992 OldParam->getLocation(),
1993 OldParam->getIdentifier(),
1994 NewDI->getType(),
1995 NewDI,
1996 OldParam->getStorageClass(),
1997 NewDefArg.get());
1998 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
1999 OldParam->getFunctionScopeIndex());
Erik Pilkington69770d32018-07-27 21:23:48 +00002000 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);
Richard Smith32918772017-02-14 00:25:28 +00002001 return NewParam;
2002 }
2003
2004 NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams,
Richard Smith76b90272019-05-09 03:59:21 +00002005 ExplicitSpecifier ES, TypeSourceInfo *TInfo,
Richard Smith32918772017-02-14 00:25:28 +00002006 SourceLocation LocStart, SourceLocation Loc,
2007 SourceLocation LocEnd) {
Richard Smithbc491202017-02-17 20:05:37 +00002008 DeclarationNameInfo Name(DeductionGuideName, Loc);
Richard Smithefa919a2017-02-16 21:29:21 +00002009 ArrayRef<ParmVarDecl *> Params =
2010 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
2011
Richard Smith32918772017-02-14 00:25:28 +00002012 // Build the implicit deduction guide template.
Richard Smithbc491202017-02-17 20:05:37 +00002013 auto *Guide =
Richard Smith76b90272019-05-09 03:59:21 +00002014 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, ES, Name,
2015 TInfo->getType(), TInfo, LocEnd);
Richard Smith32918772017-02-14 00:25:28 +00002016 Guide->setImplicit();
Richard Smithefa919a2017-02-16 21:29:21 +00002017 Guide->setParams(Params);
2018
2019 for (auto *Param : Params)
2020 Param->setDeclContext(Guide);
Richard Smith32918772017-02-14 00:25:28 +00002021
2022 auto *GuideTemplate = FunctionTemplateDecl::Create(
2023 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
2024 GuideTemplate->setImplicit();
2025 Guide->setDescribedFunctionTemplate(GuideTemplate);
2026
2027 if (isa<CXXRecordDecl>(DC)) {
2028 Guide->setAccess(AS_public);
2029 GuideTemplate->setAccess(AS_public);
2030 }
2031
2032 DC->addDecl(GuideTemplate);
2033 return GuideTemplate;
2034 }
2035};
2036}
2037
2038void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
2039 SourceLocation Loc) {
Gauthier Harnischb63e5772019-06-14 08:40:04 +00002040 if (CXXRecordDecl *DefRecord =
2041 cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
2042 TemplateDecl *DescribedTemplate = DefRecord->getDescribedClassTemplate();
2043 Template = DescribedTemplate ? DescribedTemplate : Template;
2044 }
2045
Richard Smith32918772017-02-14 00:25:28 +00002046 DeclContext *DC = Template->getDeclContext();
2047 if (DC->isDependentContext())
2048 return;
2049
2050 ConvertConstructorToDeductionGuideTransform Transform(
2051 *this, cast<ClassTemplateDecl>(Template));
2052 if (!isCompleteType(Loc, Transform.DeducedType))
2053 return;
2054
2055 // Check whether we've already declared deduction guides for this template.
2056 // FIXME: Consider storing a flag on the template to indicate this.
2057 auto Existing = DC->lookup(Transform.DeductionGuideName);
2058 for (auto *D : Existing)
2059 if (D->isImplicit())
2060 return;
2061
2062 // In case we were expanding a pack when we attempted to declare deduction
2063 // guides, turn off pack expansion for everything we're about to do.
2064 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2065 // Create a template instantiation record to track the "instantiation" of
2066 // constructors into deduction guides.
2067 // FIXME: Add a kind for this to give more meaningful diagnostics. But can
2068 // this substitution process actually fail?
2069 InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
Volodymyr Sapsai2f649f32018-05-14 22:49:44 +00002070 if (BuildingDeductionGuides.isInvalid())
2071 return;
Richard Smith32918772017-02-14 00:25:28 +00002072
2073 // Convert declared constructors into deduction guide templates.
2074 // FIXME: Skip constructors for which deduction must necessarily fail (those
2075 // for which some class template parameter without a default argument never
2076 // appears in a deduced context).
2077 bool AddedAny = false;
Richard Smith32918772017-02-14 00:25:28 +00002078 for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
2079 D = D->getUnderlyingDecl();
2080 if (D->isInvalidDecl() || D->isImplicit())
2081 continue;
2082 D = cast<NamedDecl>(D->getCanonicalDecl());
2083
2084 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
Richard Smithbc491202017-02-17 20:05:37 +00002085 auto *CD =
2086 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
Richard Smith32918772017-02-14 00:25:28 +00002087 // Class-scope explicit specializations (MS extension) do not result in
2088 // deduction guides.
Richard Smithbc491202017-02-17 20:05:37 +00002089 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
Richard Smith32918772017-02-14 00:25:28 +00002090 continue;
2091
Richard Smithbc491202017-02-17 20:05:37 +00002092 Transform.transformConstructor(FTD, CD);
Richard Smith32918772017-02-14 00:25:28 +00002093 AddedAny = true;
Richard Smith32918772017-02-14 00:25:28 +00002094 }
2095
Faisal Vali81b756e2017-10-22 14:45:08 +00002096 // C++17 [over.match.class.deduct]
2097 // -- If C is not defined or does not declare any constructors, an
2098 // additional function template derived as above from a hypothetical
2099 // constructor C().
Richard Smith32918772017-02-14 00:25:28 +00002100 if (!AddedAny)
2101 Transform.buildSimpleDeductionGuide(None);
2102
Faisal Vali81b756e2017-10-22 14:45:08 +00002103 // -- An additional function template derived as above from a hypothetical
2104 // constructor C(C), called the copy deduction candidate.
2105 cast<CXXDeductionGuideDecl>(
2106 cast<FunctionTemplateDecl>(
2107 Transform.buildSimpleDeductionGuide(Transform.DeducedType))
2108 ->getTemplatedDecl())
2109 ->setIsCopyDeductionCandidate();
Richard Smith32918772017-02-14 00:25:28 +00002110}
2111
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002112/// Diagnose the presence of a default template argument on a
Douglas Gregored5731f2009-11-25 17:50:39 +00002113/// template parameter, which is ill-formed in certain contexts.
2114///
2115/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002116static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00002117 Sema::TemplateParamListContext TPC,
2118 SourceLocation ParamLoc,
2119 SourceRange DefArgRange) {
2120 switch (TPC) {
2121 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00002122 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00002123 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00002124 return false;
2125
2126 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00002127 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002128 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00002129 // A default template-argument shall not be specified in a
2130 // function template declaration or a function template
2131 // definition [...]
Simon Pilgrim6905d222016-12-30 22:55:33 +00002132 // If a friend function template declaration specifies a default
Douglas Gregora99fb4c2011-02-04 04:20:44 +00002133 // template-argument, that declaration shall be a definition and shall be
2134 // the only declaration of the function template in the translation unit.
2135 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002136 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002137 diag::warn_cxx98_compat_template_parameter_default_in_function_template
2138 : diag::ext_template_parameter_default_in_function_template)
2139 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00002140 return false;
2141
2142 case Sema::TPC_ClassTemplateMember:
2143 // C++0x [temp.param]p9:
2144 // A default template-argument shall not be specified in the
2145 // template-parameter-lists of the definition of a member of a
2146 // class template that appears outside of the member's class.
2147 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2148 << DefArgRange;
2149 return true;
2150
David Majnemerba8f17a2013-06-25 22:08:55 +00002151 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00002152 case Sema::TPC_FriendFunctionTemplate:
2153 // C++ [temp.param]p9:
2154 // A default template-argument shall not be specified in a
2155 // friend template declaration.
2156 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2157 << DefArgRange;
2158 return true;
2159
2160 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2161 // for friend function templates if there is only a single
2162 // declaration (and it is a definition). Strange!
2163 }
2164
David Blaikie8a40f702012-01-17 06:56:22 +00002165 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00002166}
2167
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002168/// Check for unexpanded parameter packs within the template parameters
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002169/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00002170static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2171 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00002172 // A template template parameter which is a parameter pack is also a pack
2173 // expansion.
2174 if (TTP->isParameterPack())
2175 return false;
2176
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002177 TemplateParameterList *Params = TTP->getTemplateParameters();
2178 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2179 NamedDecl *P = Params->getParam(I);
2180 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00002181 if (!NTTP->isParameterPack() &&
2182 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002183 NTTP->getTypeSourceInfo(),
2184 Sema::UPPC_NonTypeTemplateParameterType))
2185 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002186
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002187 continue;
2188 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002189
2190 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002191 = dyn_cast<TemplateTemplateParmDecl>(P))
2192 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2193 return true;
2194 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002195
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002196 return false;
2197}
2198
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002199/// Checks the validity of a template parameter list, possibly
Douglas Gregordba32632009-02-10 19:49:53 +00002200/// considering the template parameter list from a previous
2201/// declaration.
2202///
2203/// If an "old" template parameter list is provided, it must be
2204/// equivalent (per TemplateParameterListsAreEqual) to the "new"
2205/// template parameter list.
2206///
2207/// \param NewParams Template parameter list for a new template
2208/// declaration. This template parameter list will be updated with any
2209/// default arguments that are carried through from the previous
2210/// template parameter list.
2211///
2212/// \param OldParams If provided, template parameter list from a
2213/// previous declaration of the same template. Default template
2214/// arguments will be merged from the old template parameter list to
2215/// the new template parameter list.
2216///
Douglas Gregored5731f2009-11-25 17:50:39 +00002217/// \param TPC Describes the context in which we are checking the given
2218/// template parameter list.
2219///
Richard Smithc4577662018-09-12 02:13:47 +00002220/// \param SkipBody If we might have already made a prior merged definition
2221/// of this template visible, the corresponding body-skipping information.
2222/// Default argument redefinition is not an error when skipping such a body,
2223/// because (under the ODR) we can assume the default arguments are the same
2224/// as the prior merged definition.
2225///
Douglas Gregordba32632009-02-10 19:49:53 +00002226/// \returns true if an error occurred, false otherwise.
2227bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00002228 TemplateParameterList *OldParams,
Richard Smithc4577662018-09-12 02:13:47 +00002229 TemplateParamListContext TPC,
2230 SkipBodyInfo *SkipBody) {
Douglas Gregordba32632009-02-10 19:49:53 +00002231 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00002232
Douglas Gregordba32632009-02-10 19:49:53 +00002233 // C++ [temp.param]p10:
2234 // The set of default template-arguments available for use with a
2235 // template declaration or definition is obtained by merging the
2236 // default arguments from the definition (if in scope) and all
2237 // declarations in scope in the same way default function
2238 // arguments are (8.3.6).
2239 bool SawDefaultArgument = false;
2240 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00002241
Mike Stumpc89c8e32009-02-11 23:03:27 +00002242 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00002243 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00002244 if (OldParams)
2245 OldParam = OldParams->begin();
2246
Douglas Gregor0693def2011-01-27 01:40:17 +00002247 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00002248 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2249 NewParamEnd = NewParams->end();
2250 NewParam != NewParamEnd; ++NewParam) {
2251 // Variables used to diagnose redundant default arguments
2252 bool RedundantDefaultArg = false;
2253 SourceLocation OldDefaultLoc;
2254 SourceLocation NewDefaultLoc;
2255
David Blaikie651c73c2011-10-19 05:19:50 +00002256 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00002257 bool MissingDefaultArg = false;
2258
David Blaikie651c73c2011-10-19 05:19:50 +00002259 // Variable used to diagnose non-final parameter packs
2260 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00002261
Douglas Gregordba32632009-02-10 19:49:53 +00002262 if (TemplateTypeParmDecl *NewTypeParm
2263 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00002264 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002265 if (NewTypeParm->hasDefaultArgument() &&
2266 DiagnoseDefaultTemplateArgument(*this, TPC,
2267 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002268 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002269 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00002270 NewTypeParm->removeDefaultArgument();
2271
2272 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00002273 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002274 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Anders Carlsson327865d2009-06-12 23:20:15 +00002275 if (NewTypeParm->isParameterPack()) {
2276 assert(!NewTypeParm->hasDefaultArgument() &&
2277 "Parameter packs can't have a default argument!");
2278 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002279 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
Richard Smithc4577662018-09-12 02:13:47 +00002280 NewTypeParm->hasDefaultArgument() &&
2281 (!SkipBody || !SkipBody->ShouldSkip)) {
Douglas Gregordba32632009-02-10 19:49:53 +00002282 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2283 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2284 SawDefaultArgument = true;
2285 RedundantDefaultArg = true;
2286 PreviousDefaultArgLoc = NewDefaultLoc;
2287 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2288 // Merge the default argument from the old declaration to the
2289 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002290 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00002291 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2292 } else if (NewTypeParm->hasDefaultArgument()) {
2293 SawDefaultArgument = true;
2294 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2295 } else if (SawDefaultArgument)
2296 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00002297 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00002298 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002299 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002300 if (!NewNonTypeParm->isParameterPack() &&
2301 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002302 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002303 UPPC_NonTypeTemplateParameterType)) {
2304 Invalid = true;
2305 continue;
2306 }
2307
Douglas Gregored5731f2009-11-25 17:50:39 +00002308 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002309 if (NewNonTypeParm->hasDefaultArgument() &&
2310 DiagnoseDefaultTemplateArgument(*this, TPC,
2311 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002312 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00002313 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00002314 }
2315
Mike Stump12b8ce12009-08-04 21:02:39 +00002316 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00002317 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002318 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00002319 if (NewNonTypeParm->isParameterPack()) {
2320 assert(!NewNonTypeParm->hasDefaultArgument() &&
2321 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00002322 if (!NewNonTypeParm->isPackExpansion())
2323 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002324 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
Richard Smithc4577662018-09-12 02:13:47 +00002325 NewNonTypeParm->hasDefaultArgument() &&
2326 (!SkipBody || !SkipBody->ShouldSkip)) {
Douglas Gregordba32632009-02-10 19:49:53 +00002327 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2328 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2329 SawDefaultArgument = true;
2330 RedundantDefaultArg = true;
2331 PreviousDefaultArgLoc = NewDefaultLoc;
2332 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2333 // Merge the default argument from the old declaration to the
2334 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002335 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00002336 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2337 } else if (NewNonTypeParm->hasDefaultArgument()) {
2338 SawDefaultArgument = true;
2339 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2340 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002341 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00002342 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00002343 TemplateTemplateParmDecl *NewTemplateParm
2344 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002345
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002346 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00002347 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002348 Invalid = true;
2349 continue;
2350 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002351
David Blaikie651c73c2011-10-19 05:19:50 +00002352 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002353 if (NewTemplateParm->hasDefaultArgument() &&
2354 DiagnoseDefaultTemplateArgument(*this, TPC,
2355 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002356 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00002357 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00002358
2359 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00002360 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002361 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00002362 if (NewTemplateParm->isParameterPack()) {
2363 assert(!NewTemplateParm->hasDefaultArgument() &&
2364 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00002365 if (!NewTemplateParm->isPackExpansion())
2366 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002367 } else if (OldTemplateParm &&
2368 hasVisibleDefaultArgument(OldTemplateParm) &&
Richard Smithc4577662018-09-12 02:13:47 +00002369 NewTemplateParm->hasDefaultArgument() &&
2370 (!SkipBody || !SkipBody->ShouldSkip)) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002371 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2372 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002373 SawDefaultArgument = true;
2374 RedundantDefaultArg = true;
2375 PreviousDefaultArgLoc = NewDefaultLoc;
2376 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2377 // Merge the default argument from the old declaration to the
2378 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002379 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002380 PreviousDefaultArgLoc
2381 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002382 } else if (NewTemplateParm->hasDefaultArgument()) {
2383 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002384 PreviousDefaultArgLoc
2385 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002386 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002387 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00002388 }
2389
Richard Smith1fde8ec2012-09-07 02:06:42 +00002390 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00002391 // If a template parameter of a primary class template or alias template
2392 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002393 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00002394 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2395 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00002396 Diag((*NewParam)->getLocation(),
2397 diag::err_template_param_pack_must_be_last_template_parameter);
2398 Invalid = true;
2399 }
2400
Douglas Gregordba32632009-02-10 19:49:53 +00002401 if (RedundantDefaultArg) {
2402 // C++ [temp.param]p12:
2403 // A template-parameter shall not be given default arguments
2404 // by two different declarations in the same scope.
2405 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2406 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2407 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00002408 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00002409 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002410 // If a template-parameter of a class template has a default
2411 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00002412 // have a default template-argument supplied or be a template parameter
2413 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00002414 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00002415 diag::err_template_param_default_arg_missing);
2416 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2417 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00002418 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00002419 }
2420
2421 // If we have an old template parameter list that we're merging
2422 // in, move on to the next parameter.
2423 if (OldParams)
2424 ++OldParam;
2425 }
2426
Douglas Gregor0693def2011-01-27 01:40:17 +00002427 // We were missing some default arguments at the end of the list, so remove
2428 // all of the default arguments.
2429 if (RemoveDefaultArguments) {
2430 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2431 NewParamEnd = NewParams->end();
2432 NewParam != NewParamEnd; ++NewParam) {
2433 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2434 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002435 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00002436 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2437 NTTP->removeDefaultArgument();
2438 else
2439 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2440 }
2441 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002442
Douglas Gregordba32632009-02-10 19:49:53 +00002443 return Invalid;
2444}
Douglas Gregord32e0282009-02-09 23:23:08 +00002445
John McCalla020a012010-10-20 05:44:58 +00002446namespace {
2447
2448/// A class which looks for a use of a certain level of template
2449/// parameter.
2450struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2451 typedef RecursiveASTVisitor<DependencyChecker> super;
2452
2453 unsigned Depth;
Richard Smith57aae072016-12-28 02:37:25 +00002454
2455 // Whether we're looking for a use of a template parameter that makes the
2456 // overall construct type-dependent / a dependent type. This is strictly
2457 // best-effort for now; we may fail to match at all for a dependent type
2458 // in some cases if this is set.
2459 bool IgnoreNonTypeDependent;
2460
John McCalla020a012010-10-20 05:44:58 +00002461 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00002462 SourceLocation MatchLoc;
2463
Richard Smith13894182017-04-13 21:37:24 +00002464 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2465 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2466 Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00002467
Richard Smith57aae072016-12-28 02:37:25 +00002468 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
Richard Smith13894182017-04-13 21:37:24 +00002469 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2470 NamedDecl *ND = Params->getParam(0);
2471 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2472 Depth = PD->getDepth();
2473 } else if (NonTypeTemplateParmDecl *PD =
2474 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2475 Depth = PD->getDepth();
2476 } else {
2477 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2478 }
2479 }
John McCalla020a012010-10-20 05:44:58 +00002480
Richard Smith6056d5e2014-02-09 00:54:43 +00002481 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
Richard Smith13894182017-04-13 21:37:24 +00002482 if (ParmDepth >= Depth) {
John McCalla020a012010-10-20 05:44:58 +00002483 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00002484 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00002485 return true;
2486 }
2487 return false;
2488 }
2489
Richard Smith57aae072016-12-28 02:37:25 +00002490 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2491 // Prune out non-type-dependent expressions if requested. This can
2492 // sometimes result in us failing to find a template parameter reference
2493 // (if a value-dependent expression creates a dependent type), but this
2494 // mode is best-effort only.
2495 if (auto *E = dyn_cast_or_null<Expr>(S))
2496 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2497 return true;
2498 return super::TraverseStmt(S, Q);
2499 }
2500
2501 bool TraverseTypeLoc(TypeLoc TL) {
2502 if (IgnoreNonTypeDependent && !TL.isNull() &&
2503 !TL.getType()->isDependentType())
2504 return true;
2505 return super::TraverseTypeLoc(TL);
2506 }
2507
Richard Smith6056d5e2014-02-09 00:54:43 +00002508 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2509 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2510 }
2511
John McCalla020a012010-10-20 05:44:58 +00002512 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
Richard Smith57aae072016-12-28 02:37:25 +00002513 // For a best-effort search, keep looking until we find a location.
2514 return IgnoreNonTypeDependent || !Matches(T->getDepth());
John McCalla020a012010-10-20 05:44:58 +00002515 }
2516
2517 bool TraverseTemplateName(TemplateName N) {
2518 if (TemplateTemplateParmDecl *PD =
2519 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00002520 if (Matches(PD->getDepth()))
2521 return false;
John McCalla020a012010-10-20 05:44:58 +00002522 return super::TraverseTemplateName(N);
2523 }
2524
2525 bool VisitDeclRefExpr(DeclRefExpr *E) {
2526 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00002527 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2528 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00002529 return false;
John McCalla020a012010-10-20 05:44:58 +00002530 return super::VisitDeclRefExpr(E);
2531 }
Richard Smith6056d5e2014-02-09 00:54:43 +00002532
2533 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2534 return TraverseType(T->getReplacementType());
2535 }
2536
2537 bool
2538 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2539 return TraverseTemplateArgument(T->getArgumentPack());
2540 }
2541
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00002542 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2543 return TraverseType(T->getInjectedSpecializationType());
2544 }
John McCalla020a012010-10-20 05:44:58 +00002545};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002546} // end anonymous namespace
John McCalla020a012010-10-20 05:44:58 +00002547
Douglas Gregor972fe532011-05-10 18:27:06 +00002548/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00002549/// list.
2550static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00002551DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
Mark de Wever74346102019-11-05 20:39:55 +01002552 if (!Params->size())
2553 return false;
2554
Richard Smith57aae072016-12-28 02:37:25 +00002555 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
Douglas Gregor972fe532011-05-10 18:27:06 +00002556 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00002557 return Checker.Match;
2558}
2559
Douglas Gregor972fe532011-05-10 18:27:06 +00002560// Find the source range corresponding to the named type in the given
2561// nested-name-specifier, if any.
2562static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2563 QualType T,
2564 const CXXScopeSpec &SS) {
2565 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2566 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2567 if (const Type *CurType = NNS->getAsType()) {
2568 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2569 return NNSLoc.getTypeLoc().getSourceRange();
2570 } else
2571 break;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002572
Douglas Gregor972fe532011-05-10 18:27:06 +00002573 NNSLoc = NNSLoc.getPrefix();
2574 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002575
Douglas Gregor972fe532011-05-10 18:27:06 +00002576 return SourceRange();
2577}
2578
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002579/// Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00002580/// specifier, returning the template parameter list that applies to the
2581/// name.
2582///
2583/// \param DeclStartLoc the start of the declaration that has a scope
2584/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00002585///
Douglas Gregor972fe532011-05-10 18:27:06 +00002586/// \param DeclLoc The location of the declaration itself.
2587///
Douglas Gregord8d297c2009-07-21 23:53:31 +00002588/// \param SS the scope specifier that will be matched to the given template
2589/// parameter lists. This scope specifier precedes a qualified name that is
2590/// being declared.
2591///
Richard Smith4b55a9c2014-04-17 03:29:33 +00002592/// \param TemplateId The template-id following the scope specifier, if there
2593/// is one. Used to check for a missing 'template<>'.
2594///
Douglas Gregord8d297c2009-07-21 23:53:31 +00002595/// \param ParamLists the template parameter lists, from the outermost to the
2596/// innermost template parameter lists.
2597///
John McCalle820e5e2010-04-13 20:37:33 +00002598/// \param IsFriend Whether to apply the slightly different rules for
2599/// matching template parameters to scope specifiers in friend
2600/// declarations.
2601///
Richard Smithf445f192017-02-09 21:04:43 +00002602/// \param IsMemberSpecialization will be set true if the scope specifier
2603/// denotes a fully-specialized type, and therefore this is a declaration of
2604/// a member specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002605///
Mike Stump11289f42009-09-09 15:08:12 +00002606/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00002607/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00002608/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00002609/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00002610/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00002611/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002612TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2613 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00002614 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002615 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
Richard Smithf445f192017-02-09 21:04:43 +00002616 bool &IsMemberSpecialization, bool &Invalid) {
2617 IsMemberSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00002618 Invalid = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002619
Douglas Gregor972fe532011-05-10 18:27:06 +00002620 // The sequence of nested types to which we will match up the template
2621 // parameter lists. We first build this list by starting with the type named
2622 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002623 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00002624 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00002625 if (SS.getScopeRep()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002626 if (CXXRecordDecl *Record
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00002627 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2628 T = Context.getTypeDeclType(Record);
2629 else
2630 T = QualType(SS.getScopeRep()->getAsType(), 0);
2631 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002632
Douglas Gregor972fe532011-05-10 18:27:06 +00002633 // If we found an explicit specialization that prevents us from needing
2634 // 'template<>' headers, this will be set to the location of that
2635 // explicit specialization.
2636 SourceLocation ExplicitSpecLoc;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002637
Douglas Gregor972fe532011-05-10 18:27:06 +00002638 while (!T.isNull()) {
2639 NestedTypes.push_back(T);
Simon Pilgrim6905d222016-12-30 22:55:33 +00002640
Douglas Gregor972fe532011-05-10 18:27:06 +00002641 // Retrieve the parent of a record type.
2642 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2643 // If this type is an explicit specialization, we're done.
2644 if (ClassTemplateSpecializationDecl *Spec
2645 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002646 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002647 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2648 ExplicitSpecLoc = Spec->getLocation();
2649 break;
Douglas Gregor65911492009-11-23 12:11:45 +00002650 }
Douglas Gregor972fe532011-05-10 18:27:06 +00002651 } else if (Record->getTemplateSpecializationKind()
2652 == TSK_ExplicitSpecialization) {
2653 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00002654 break;
2655 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002656
Douglas Gregor972fe532011-05-10 18:27:06 +00002657 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2658 T = Context.getTypeDeclType(Parent);
2659 else
2660 T = QualType();
2661 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002662 }
2663
Douglas Gregor972fe532011-05-10 18:27:06 +00002664 if (const TemplateSpecializationType *TST
2665 = T->getAs<TemplateSpecializationType>()) {
2666 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2667 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2668 T = Context.getTypeDeclType(Parent);
2669 else
2670 T = QualType();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002671 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002672 }
Douglas Gregor972fe532011-05-10 18:27:06 +00002673 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002674
Douglas Gregor972fe532011-05-10 18:27:06 +00002675 // Look one step prior in a dependent template specialization type.
2676 if (const DependentTemplateSpecializationType *DependentTST
2677 = T->getAs<DependentTemplateSpecializationType>()) {
2678 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2679 T = QualType(NNS->getAsType(), 0);
2680 else
2681 T = QualType();
2682 continue;
2683 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002684
Douglas Gregor972fe532011-05-10 18:27:06 +00002685 // Look one step prior in a dependent name type.
2686 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2687 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2688 T = QualType(NNS->getAsType(), 0);
2689 else
2690 T = QualType();
2691 continue;
2692 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002693
Douglas Gregor972fe532011-05-10 18:27:06 +00002694 // Retrieve the parent of an enumeration type.
2695 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2696 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2697 // check here.
2698 EnumDecl *Enum = EnumT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002699
Douglas Gregor972fe532011-05-10 18:27:06 +00002700 // Get to the parent type.
2701 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2702 T = Context.getTypeDeclType(Parent);
2703 else
Simon Pilgrim6905d222016-12-30 22:55:33 +00002704 T = QualType();
Douglas Gregor972fe532011-05-10 18:27:06 +00002705 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002706 }
Mike Stump11289f42009-09-09 15:08:12 +00002707
Douglas Gregor972fe532011-05-10 18:27:06 +00002708 T = QualType();
2709 }
2710 // Reverse the nested types list, since we want to traverse from the outermost
2711 // to the innermost while checking template-parameter-lists.
2712 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00002713
Douglas Gregor972fe532011-05-10 18:27:06 +00002714 // C++0x [temp.expl.spec]p17:
2715 // A member or a member template may be nested within many
2716 // enclosing class templates. In an explicit specialization for
2717 // such a member, the member declaration shall be preceded by a
2718 // template<> for each enclosing class template that is
2719 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002720 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00002721
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002722 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00002723 if (SawNonEmptyTemplateParameterList) {
2724 Diag(DeclLoc, diag::err_specialize_member_of_template)
2725 << !Recovery << Range;
2726 Invalid = true;
Richard Smithf445f192017-02-09 21:04:43 +00002727 IsMemberSpecialization = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00002728 return true;
2729 }
2730
2731 return false;
2732 };
2733
2734 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2735 // Check that we can have an explicit specialization here.
2736 if (CheckExplicitSpecialization(Range, true))
2737 return true;
2738
2739 // We don't have a template header, but we should.
2740 SourceLocation ExpectedTemplateLoc;
2741 if (!ParamLists.empty())
2742 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2743 else
2744 ExpectedTemplateLoc = DeclStartLoc;
2745
2746 Diag(DeclLoc, diag::err_template_spec_needs_header)
2747 << Range
2748 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2749 return false;
2750 };
2751
Douglas Gregor972fe532011-05-10 18:27:06 +00002752 unsigned ParamIdx = 0;
2753 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2754 ++TypeIdx) {
2755 T = NestedTypes[TypeIdx];
Simon Pilgrim6905d222016-12-30 22:55:33 +00002756
Douglas Gregor972fe532011-05-10 18:27:06 +00002757 // Whether we expect a 'template<>' header.
2758 bool NeedEmptyTemplateHeader = false;
2759
2760 // Whether we expect a template header with parameters.
2761 bool NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002762
Douglas Gregor972fe532011-05-10 18:27:06 +00002763 // For a dependent type, the set of template parameters that we
2764 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00002765 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002766
Douglas Gregor373af9b2011-05-11 23:26:17 +00002767 // C++0x [temp.expl.spec]p15:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002768 // A member or a member template may be nested within many enclosing
2769 // class templates. In an explicit specialization for such a member, the
2770 // member declaration shall be preceded by a template<> for each
Douglas Gregor373af9b2011-05-11 23:26:17 +00002771 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00002772 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2773 if (ClassTemplatePartialSpecializationDecl *Partial
2774 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2775 ExpectedTemplateParams = Partial->getTemplateParameters();
2776 NeedNonemptyTemplateHeader = true;
2777 } else if (Record->isDependentType()) {
2778 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00002779 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00002780 ->getTemplateParameters();
2781 NeedNonemptyTemplateHeader = true;
2782 }
2783 } else if (ClassTemplateSpecializationDecl *Spec
2784 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2785 // C++0x [temp.expl.spec]p4:
2786 // Members of an explicitly specialized class template are defined
Simon Pilgrim6905d222016-12-30 22:55:33 +00002787 // in the same manner as members of normal classes, and not using
2788 // the template<> syntax.
Douglas Gregor972fe532011-05-10 18:27:06 +00002789 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2790 NeedEmptyTemplateHeader = true;
2791 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00002792 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002793 } else if (Record->getTemplateSpecializationKind()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002794 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00002795 != TSK_ExplicitSpecialization &&
2796 TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002797 IsMemberSpecialization = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002798
Douglas Gregor373af9b2011-05-11 23:26:17 +00002799 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002800 }
2801 } else if (const TemplateSpecializationType *TST
2802 = T->getAs<TemplateSpecializationType>()) {
Nico Weber28900612015-01-30 02:35:21 +00002803 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002804 ExpectedTemplateParams = Template->getTemplateParameters();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002805 NeedNonemptyTemplateHeader = true;
Douglas Gregor972fe532011-05-10 18:27:06 +00002806 }
2807 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2808 // FIXME: We actually could/should check the template arguments here
2809 // against the corresponding template parameter list.
2810 NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002811 }
2812
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002813 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002814 // In an explicit specialization declaration for a member of a class
2815 // template or a member template that ap- pears in namespace scope, the
2816 // member template and some of its enclosing class templates may remain
2817 // unspecialized, except that the declaration shall not explicitly
2818 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002819 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002820 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002821 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002822 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2823 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002824 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002825 } else
2826 SawNonEmptyTemplateParameterList = true;
2827 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002828
Douglas Gregor972fe532011-05-10 18:27:06 +00002829 if (NeedEmptyTemplateHeader) {
2830 // If we're on the last of the types, and we need a 'template<>' header
Richard Smithf445f192017-02-09 21:04:43 +00002831 // here, then it's a member specialization.
Douglas Gregor972fe532011-05-10 18:27:06 +00002832 if (TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002833 IsMemberSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002834
2835 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002836 if (ParamLists[ParamIdx]->size() > 0) {
2837 // The header has template parameters when it shouldn't. Complain.
Simon Pilgrim6905d222016-12-30 22:55:33 +00002838 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregor972fe532011-05-10 18:27:06 +00002839 diag::err_template_param_list_matches_nontemplate)
2840 << T
2841 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2842 ParamLists[ParamIdx]->getRAngleLoc())
2843 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2844 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002845 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002846 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002847
Douglas Gregor972fe532011-05-10 18:27:06 +00002848 // Consume this template header.
2849 ++ParamIdx;
2850 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002851 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002852
2853 if (!IsFriend)
2854 if (DiagnoseMissingExplicitSpecialization(
2855 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00002856 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002857
Douglas Gregor972fe532011-05-10 18:27:06 +00002858 continue;
2859 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002860
Douglas Gregor972fe532011-05-10 18:27:06 +00002861 if (NeedNonemptyTemplateHeader) {
2862 // In friend declarations we can have template-ids which don't
2863 // depend on the corresponding template parameter lists. But
2864 // assume that empty parameter lists are supposed to match this
2865 // template-id.
2866 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002867 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002868 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00002869 ExpectedTemplateParams = nullptr;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002870 else
Douglas Gregor972fe532011-05-10 18:27:06 +00002871 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002872 }
Douglas Gregored5731f2009-11-25 17:50:39 +00002873
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002874 if (ParamIdx < ParamLists.size()) {
2875 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00002876 if (ExpectedTemplateParams &&
2877 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2878 ExpectedTemplateParams,
2879 true, TPL_TemplateMatch))
2880 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002881
Douglas Gregor972fe532011-05-10 18:27:06 +00002882 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00002883 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00002884 TPC_ClassTemplateMember))
2885 Invalid = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002886
Douglas Gregor972fe532011-05-10 18:27:06 +00002887 ++ParamIdx;
2888 continue;
2889 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002890
Douglas Gregor972fe532011-05-10 18:27:06 +00002891 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2892 << T
2893 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2894 Invalid = true;
2895 continue;
2896 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00002897 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00002898
Douglas Gregord8d297c2009-07-21 23:53:31 +00002899 // If there were at least as many template-ids as there were template
2900 // parameter lists, then there are no template parameter lists remaining for
2901 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00002902 if (ParamIdx >= ParamLists.size()) {
2903 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00002904 // We don't have a template header for the declaration itself, but we
2905 // should.
Richard Smith11a80dc2014-04-17 03:52:20 +00002906 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2907 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00002908
2909 // Fabricate an empty template parameter list for the invented header.
2910 return TemplateParameterList::Create(Context, SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +00002911 SourceLocation(), None,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00002912 SourceLocation(), nullptr);
Richard Smith4b55a9c2014-04-17 03:29:33 +00002913 }
2914
Craig Topperc3ec1492014-05-26 06:22:03 +00002915 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002916 }
Mike Stump11289f42009-09-09 15:08:12 +00002917
Douglas Gregord8d297c2009-07-21 23:53:31 +00002918 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002919 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002920 bool HasAnyExplicitSpecHeader = false;
2921 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002922 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002923 if (ParamLists[I]->size() == 0)
2924 HasAnyExplicitSpecHeader = true;
2925 else
2926 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002927 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002928
Douglas Gregor972fe532011-05-10 18:27:06 +00002929 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002930 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2931 : diag::err_template_spec_extra_headers)
2932 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2933 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00002934
2935 // If there was a specialization somewhere, such that 'template<>' is
2936 // not required, and there were any 'template<>' headers, note where the
2937 // specialization occurred.
2938 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
Simon Pilgrim6905d222016-12-30 22:55:33 +00002939 Diag(ExplicitSpecLoc,
Douglas Gregor972fe532011-05-10 18:27:06 +00002940 diag::note_explicit_template_spec_does_not_need_header)
2941 << NestedTypes.back();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002942
Douglas Gregor972fe532011-05-10 18:27:06 +00002943 // We have a template parameter list with no corresponding scope, which
2944 // means that the resulting template declaration can't be instantiated
2945 // properly (we'll end up with dependent nodes when we shouldn't).
2946 if (!AllExplicitSpecHeaders)
2947 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002948 }
Mike Stump11289f42009-09-09 15:08:12 +00002949
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002950 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002951 // In an explicit specialization declaration for a member of a class
2952 // template or a member template that ap- pears in namespace scope, the
2953 // member template and some of its enclosing class templates may remain
2954 // unspecialized, except that the declaration shall not explicitly
2955 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002956 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00002957 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002958 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2959 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002960 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002961
Douglas Gregord8d297c2009-07-21 23:53:31 +00002962 // Return the last template parameter list, which corresponds to the
2963 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002964 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00002965}
2966
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002967void Sema::NoteAllFoundTemplates(TemplateName Name) {
2968 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2969 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002970 << (isa<FunctionTemplateDecl>(Template)
2971 ? 0
2972 : isa<ClassTemplateDecl>(Template)
2973 ? 1
2974 : isa<VarTemplateDecl>(Template)
2975 ? 2
2976 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2977 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002978 return;
2979 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002980
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002981 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002982 for (OverloadedTemplateStorage::iterator I = OST->begin(),
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002983 IEnd = OST->end();
2984 I != IEnd; ++I)
2985 Diag((*I)->getLocation(), diag::note_template_declared_here)
2986 << 0 << (*I)->getDeclName();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002987
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002988 return;
2989 }
2990}
2991
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002992static QualType
2993checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2994 const SmallVectorImpl<TemplateArgument> &Converted,
2995 SourceLocation TemplateLoc,
2996 TemplateArgumentListInfo &TemplateArgs) {
2997 ASTContext &Context = SemaRef.getASTContext();
2998 switch (BTD->getBuiltinTemplateKind()) {
Eric Fiselier6ad68552016-07-01 01:24:09 +00002999 case BTK__make_integer_seq: {
David Majnemerd9b1a4f2015-11-04 03:40:30 +00003000 // Specializations of __make_integer_seq<S, T, N> are treated like
3001 // S<T, 0, ..., N-1>.
3002
3003 // C++14 [inteseq.intseq]p1:
3004 // T shall be an integer type.
3005 if (!Converted[1].getAsType()->isIntegralType(Context)) {
3006 SemaRef.Diag(TemplateArgs[1].getLocation(),
3007 diag::err_integer_sequence_integral_element_type);
3008 return QualType();
3009 }
3010
3011 // C++14 [inteseq.make]p1:
3012 // If N is negative the program is ill-formed.
3013 TemplateArgument NumArgsArg = Converted[2];
3014 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
3015 if (NumArgs < 0) {
3016 SemaRef.Diag(TemplateArgs[2].getLocation(),
3017 diag::err_integer_sequence_negative_length);
3018 return QualType();
3019 }
3020
3021 QualType ArgTy = NumArgsArg.getIntegralType();
3022 TemplateArgumentListInfo SyntheticTemplateArgs;
3023 // The type argument gets reused as the first template argument in the
3024 // synthetic template argument list.
3025 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
3026 // Expand N into 0 ... N-1.
3027 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3028 I < NumArgs; ++I) {
3029 TemplateArgument TA(Context, I, ArgTy);
Richard Smith7873de02016-08-11 22:25:46 +00003030 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3031 TA, ArgTy, TemplateArgs[2].getLocation()));
David Majnemerd9b1a4f2015-11-04 03:40:30 +00003032 }
3033 // The first template argument will be reused as the template decl that
3034 // our synthetic template arguments will be applied to.
3035 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
3036 TemplateLoc, SyntheticTemplateArgs);
3037 }
Eric Fiselier6ad68552016-07-01 01:24:09 +00003038
3039 case BTK__type_pack_element:
3040 // Specializations of
3041 // __type_pack_element<Index, T_1, ..., T_N>
3042 // are treated like T_Index.
3043 assert(Converted.size() == 2 &&
3044 "__type_pack_element should be given an index and a parameter pack");
3045
3046 // If the Index is out of bounds, the program is ill-formed.
3047 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3048 llvm::APSInt Index = IndexArg.getAsIntegral();
3049 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3050 "type std::size_t, and hence be non-negative");
3051 if (Index >= Ts.pack_size()) {
3052 SemaRef.Diag(TemplateArgs[0].getLocation(),
3053 diag::err_type_pack_element_out_of_bounds);
3054 return QualType();
3055 }
3056
3057 // We simply return the type at index `Index`.
3058 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
3059 return Nth->getAsType();
3060 }
David Majnemerd9b1a4f2015-11-04 03:40:30 +00003061 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3062}
3063
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003064/// Determine whether this alias template is "enable_if_t".
3065static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3066 return AliasTemplate->getName().equals("enable_if_t");
3067}
3068
3069/// Collect all of the separable terms in the given condition, which
3070/// might be a conjunction.
3071///
3072/// FIXME: The right answer is to convert the logical expression into
3073/// disjunctive normal form, so we can find the first failed term
3074/// within each possible clause.
3075static void collectConjunctionTerms(Expr *Clause,
3076 SmallVectorImpl<Expr *> &Terms) {
3077 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3078 if (BinOp->getOpcode() == BO_LAnd) {
3079 collectConjunctionTerms(BinOp->getLHS(), Terms);
3080 collectConjunctionTerms(BinOp->getRHS(), Terms);
3081 }
3082
3083 return;
3084 }
3085
3086 Terms.push_back(Clause);
3087}
3088
Douglas Gregorbb33f572017-07-05 20:20:15 +00003089// The ranges-v3 library uses an odd pattern of a top-level "||" with
3090// a left-hand side that is value-dependent but never true. Identify
3091// the idiom and ignore that term.
3092static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3093 // Top-level '||'.
3094 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3095 if (!BinOp) return Cond;
3096
3097 if (BinOp->getOpcode() != BO_LOr) return Cond;
3098
3099 // With an inner '==' that has a literal on the right-hand side.
3100 Expr *LHS = BinOp->getLHS();
Douglas Gregorc0fe1f22017-07-05 21:12:37 +00003101 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
Douglas Gregorbb33f572017-07-05 20:20:15 +00003102 if (!InnerBinOp) return Cond;
3103
3104 if (InnerBinOp->getOpcode() != BO_EQ ||
3105 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3106 return Cond;
3107
3108 // If the inner binary operation came from a macro expansion named
3109 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3110 // of the '||', which is the real, user-provided condition.
Douglas Gregorc0fe1f22017-07-05 21:12:37 +00003111 SourceLocation Loc = InnerBinOp->getExprLoc();
Douglas Gregorbb33f572017-07-05 20:20:15 +00003112 if (!Loc.isMacroID()) return Cond;
3113
3114 StringRef MacroName = PP.getImmediateMacroName(Loc);
3115 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3116 return BinOp->getRHS();
3117
3118 return Cond;
3119}
3120
Clement Courbetf44c6f42018-12-11 08:39:11 +00003121namespace {
3122
3123// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3124// within failing boolean expression, such as substituting template parameters
3125// for actual types.
3126class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3127public:
3128 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3129 : Policy(P) {}
3130
3131 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3132 const auto *DR = dyn_cast<DeclRefExpr>(E);
3133 if (DR && DR->getQualifier()) {
3134 // If this is a qualified name, expand the template arguments in nested
3135 // qualifiers.
3136 DR->getQualifier()->print(OS, Policy, true);
3137 // Then print the decl itself.
3138 const ValueDecl *VD = DR->getDecl();
3139 OS << VD->getName();
3140 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3141 // This is a template variable, print the expanded template arguments.
3142 printTemplateArgumentList(OS, IV->getTemplateArgs().asArray(), Policy);
3143 }
3144 return true;
Clement Courbet9d432e02018-12-04 07:59:57 +00003145 }
Clement Courbetf44c6f42018-12-11 08:39:11 +00003146 return false;
Clement Courbet9d432e02018-12-04 07:59:57 +00003147 }
Clement Courbetf44c6f42018-12-11 08:39:11 +00003148
3149private:
3150 const PrintingPolicy Policy;
3151};
3152
3153} // end anonymous namespace
Clement Courbet9d432e02018-12-04 07:59:57 +00003154
Douglas Gregor672281a2017-09-14 23:38:42 +00003155std::pair<Expr *, std::string>
Clement Courbetf44c6f42018-12-11 08:39:11 +00003156Sema::findFailedBooleanCondition(Expr *Cond) {
Douglas Gregor672281a2017-09-14 23:38:42 +00003157 Cond = lookThroughRangesV3Condition(PP, Cond);
Douglas Gregorbb33f572017-07-05 20:20:15 +00003158
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003159 // Separate out all of the terms in a conjunction.
3160 SmallVector<Expr *, 4> Terms;
3161 collectConjunctionTerms(Cond, Terms);
3162
3163 // Determine which term failed.
3164 Expr *FailedCond = nullptr;
3165 for (Expr *Term : Terms) {
Douglas Gregor672281a2017-09-14 23:38:42 +00003166 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3167
Clement Courbetd8720412018-12-10 08:53:17 +00003168 // Literals are uninteresting.
3169 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3170 isa<IntegerLiteral>(TermAsWritten))
3171 continue;
3172
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003173 // The initialization of the parameter from the argument is
3174 // a constant-evaluated context.
3175 EnterExpressionEvaluationContext ConstantEvaluated(
Douglas Gregor672281a2017-09-14 23:38:42 +00003176 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003177
3178 bool Succeeded;
Douglas Gregor672281a2017-09-14 23:38:42 +00003179 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003180 !Succeeded) {
Douglas Gregor672281a2017-09-14 23:38:42 +00003181 FailedCond = TermAsWritten;
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003182 break;
3183 }
3184 }
Clement Courbetf44c6f42018-12-11 08:39:11 +00003185 if (!FailedCond)
Clement Courbetd8720412018-12-10 08:53:17 +00003186 FailedCond = Cond->IgnoreParenImpCasts();
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003187
3188 std::string Description;
3189 {
3190 llvm::raw_string_ostream Out(Description);
Clement Courbetfb2c74d2018-12-20 09:05:15 +00003191 PrintingPolicy Policy = getPrintingPolicy();
3192 Policy.PrintCanonicalTypes = true;
3193 FailedBooleanConditionPrinterHelper Helper(Policy);
3194 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003195 }
3196 return { FailedCond, Description };
3197}
3198
Douglas Gregordc572a32009-03-30 22:58:21 +00003199QualType Sema::CheckTemplateIdType(TemplateName Name,
3200 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003201 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00003202 DependentTemplateName *DTN
3203 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00003204 if (DTN && DTN->isIdentifier())
3205 // When building a template-id where the template-name is dependent,
3206 // assume the template is a type template. Either our assumption is
3207 // correct, or the code is ill-formed and will be diagnosed when the
3208 // dependent name is substituted.
3209 return Context.getDependentTemplateSpecializationType(ETK_None,
3210 DTN->getQualifier(),
3211 DTN->getIdentifier(),
3212 TemplateArgs);
3213
Douglas Gregordc572a32009-03-30 22:58:21 +00003214 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00003215 if (!Template || isa<FunctionTemplateDecl>(Template) ||
Saar Razfdf80e82019-12-06 01:30:21 +02003216 isa<VarTemplateDecl>(Template) || isa<ConceptDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00003217 // We might have a substituted template template parameter pack. If so,
3218 // build a template specialization type for it.
3219 if (Name.getAsSubstTemplateTemplateParmPack())
3220 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003221
Douglas Gregor8b6070b2011-03-04 21:37:14 +00003222 Diag(TemplateLoc, diag::err_template_id_not_a_type)
3223 << Name;
3224 NoteAllFoundTemplates(Name);
3225 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00003226 }
Douglas Gregordc572a32009-03-30 22:58:21 +00003227
Douglas Gregorc40290e2009-03-09 23:48:35 +00003228 // Check that the template argument list is well-formed for this
3229 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003230 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00003231 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Saar Razfdf80e82019-12-06 01:30:21 +02003232 false, Converted,
3233 /*UpdateArgsWithConversion=*/true))
Douglas Gregorc40290e2009-03-09 23:48:35 +00003234 return QualType();
3235
Douglas Gregorc40290e2009-03-09 23:48:35 +00003236 QualType CanonType;
3237
Douglas Gregor678d76c2011-07-01 01:22:09 +00003238 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00003239 if (TypeAliasTemplateDecl *AliasTemplate =
3240 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Saar Razfdf80e82019-12-06 01:30:21 +02003241
Richard Smith3f1b5d02011-05-05 21:57:07 +00003242 // Find the canonical type for this type alias template specialization.
3243 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3244 if (Pattern->isInvalidDecl())
3245 return QualType();
3246
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003247 TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack,
3248 Converted);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003249
3250 // Only substitute for the innermost template argument list.
3251 MultiLevelTemplateArgumentList TemplateArgLists;
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003252 TemplateArgLists.addOuterTemplateArguments(&StackTemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00003253 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
3254 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00003255 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003256
Richard Smith802c4b72012-08-23 06:16:52 +00003257 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003258 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003259 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003260 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00003261
Richard Smith3f1b5d02011-05-05 21:57:07 +00003262 CanonType = SubstType(Pattern->getUnderlyingType(),
3263 TemplateArgLists, AliasTemplate->getLocation(),
3264 AliasTemplate->getDeclName());
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003265 if (CanonType.isNull()) {
3266 // If this was enable_if and we failed to find the nested type
3267 // within enable_if in a SFINAE context, dig out the specific
3268 // enable_if condition that failed and present that instead.
3269 if (isEnableIfAliasTemplate(AliasTemplate)) {
3270 if (auto DeductionInfo = isSFINAEContext()) {
3271 if (*DeductionInfo &&
3272 (*DeductionInfo)->hasSFINAEDiagnostic() &&
3273 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3274 diag::err_typename_nested_not_found_enable_if &&
3275 TemplateArgs[0].getArgument().getKind()
3276 == TemplateArgument::Expression) {
3277 Expr *FailedCond;
3278 std::string FailedDescription;
3279 std::tie(FailedCond, FailedDescription) =
Clement Courbetf44c6f42018-12-11 08:39:11 +00003280 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003281
3282 // Remove the old SFINAE diagnostic.
3283 PartialDiagnosticAt OldDiag =
3284 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3285 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3286
3287 // Add a new SFINAE diagnostic specifying which condition
3288 // failed.
3289 (*DeductionInfo)->addSFINAEDiagnostic(
3290 OldDiag.first,
3291 PDiag(diag::err_typename_nested_not_found_requirement)
3292 << FailedDescription
3293 << FailedCond->getSourceRange());
3294 }
3295 }
3296 }
3297
Richard Smith3f1b5d02011-05-05 21:57:07 +00003298 return QualType();
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003299 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00003300 } else if (Name.isDependent() ||
3301 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00003302 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00003303 // This class template specialization is a dependent
3304 // type. Therefore, its canonical type is another class template
3305 // specialization type that contains all of the converted
3306 // arguments in canonical form. This ensures that, e.g., A<T> and
3307 // A<T, T> have identical types when A is declared as:
3308 //
3309 // template<typename T, typename U = T> struct A;
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00003310 CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
John McCall2408e322010-04-27 00:57:59 +00003311
3312 // This might work out to be a current instantiation, in which
3313 // case the canonical type needs to be the InjectedClassNameType.
3314 //
3315 // TODO: in theory this could be a simple hashtable lookup; most
3316 // changes to CurContext don't change the set of current
3317 // instantiations.
3318 if (isa<ClassTemplateDecl>(Template)) {
3319 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3320 // If we get out to a namespace, we're done.
3321 if (Ctx->isFileContext()) break;
3322
3323 // If this isn't a record, keep looking.
3324 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3325 if (!Record) continue;
3326
3327 // Look for one of the two cases with InjectedClassNameTypes
3328 // and check whether it's the same template.
3329 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3330 !Record->getDescribedClassTemplate())
3331 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003332
John McCall2408e322010-04-27 00:57:59 +00003333 // Fetch the injected class name type and check whether its
3334 // injected type is equal to the type we just built.
3335 QualType ICNT = Context.getTypeDeclType(Record);
3336 QualType Injected = cast<InjectedClassNameType>(ICNT)
3337 ->getInjectedSpecializationType();
3338
3339 if (CanonType != Injected->getCanonicalTypeInternal())
3340 continue;
3341
3342 // If so, the canonical type of this TST is the injected
3343 // class name type of the record we just found.
3344 assert(ICNT.isCanonical());
3345 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00003346 break;
3347 }
3348 }
Mike Stump11289f42009-09-09 15:08:12 +00003349 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00003350 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00003351 // Find the class template specialization declaration that
3352 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00003353 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00003354 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00003355 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003356 if (!Decl) {
3357 // This is the first time we have referenced this class template
3358 // specialization. Create the canonical declaration and add it to
3359 // the set of specializations.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003360 Decl = ClassTemplateSpecializationDecl::Create(
3361 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3362 ClassTemplate->getDeclContext(),
3363 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3364 ClassTemplate->getLocation(), ClassTemplate, Converted, nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003365 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00003366 if (ClassTemplate->isOutOfLine())
3367 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00003368 }
3369
Erich Keanea32910d2017-03-23 18:51:54 +00003370 if (Decl->getSpecializationKind() == TSK_Undeclared) {
3371 MultiLevelTemplateArgumentList TemplateArgLists;
3372 TemplateArgLists.addOuterTemplateArguments(Converted);
3373 InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(),
3374 Decl);
3375 }
3376
Chandler Carruth2acfb222013-09-27 22:14:40 +00003377 // Diagnose uses of this specialization.
3378 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3379
Douglas Gregorc40290e2009-03-09 23:48:35 +00003380 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00003381 assert(isa<RecordType>(CanonType) &&
3382 "type of non-dependent specialization is not a RecordType");
David Majnemerd9b1a4f2015-11-04 03:40:30 +00003383 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3384 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
3385 TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003386 }
Mike Stump11289f42009-09-09 15:08:12 +00003387
Douglas Gregorc40290e2009-03-09 23:48:35 +00003388 // Build the fully-sugared type for this class template
3389 // specialization, which refers back to the class template
3390 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00003391 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003392}
3393
Richard Smithb23c5e82019-05-09 03:31:27 +00003394void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,
3395 TemplateNameKind &TNK,
3396 SourceLocation NameLoc,
3397 IdentifierInfo *&II) {
3398 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
3399
3400 TemplateName Name = ParsedName.get();
3401 auto *ATN = Name.getAsAssumedTemplateName();
3402 assert(ATN && "not an assumed template name");
3403 II = ATN->getDeclName().getAsIdentifierInfo();
3404
3405 if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
3406 // Resolved to a type template name.
3407 ParsedName = TemplateTy::make(Name);
3408 TNK = TNK_Type_template;
3409 }
3410}
3411
3412bool Sema::resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
3413 SourceLocation NameLoc,
3414 bool Diagnose) {
3415 // We assumed this undeclared identifier to be an (ADL-only) function
3416 // template name, but it was used in a context where a type was required.
3417 // Try to typo-correct it now.
3418 AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
3419 assert(ATN && "not an assumed template name");
3420
3421 LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
3422 struct CandidateCallback : CorrectionCandidateCallback {
3423 bool ValidateCandidate(const TypoCorrection &TC) override {
3424 return TC.getCorrectionDecl() &&
3425 getAsTypeTemplateDecl(TC.getCorrectionDecl());
3426 }
3427 std::unique_ptr<CorrectionCandidateCallback> clone() override {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00003428 return std::make_unique<CandidateCallback>(*this);
Richard Smithb23c5e82019-05-09 03:31:27 +00003429 }
3430 } FilterCCC;
3431
3432 TypoCorrection Corrected =
3433 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
3434 FilterCCC, CTK_ErrorRecovery);
3435 if (Corrected && Corrected.getFoundDecl()) {
3436 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
3437 << ATN->getDeclName());
3438 Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>());
3439 return false;
3440 }
3441
3442 if (Diagnose)
3443 Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
3444 return true;
3445}
3446
3447TypeResult Sema::ActOnTemplateIdType(
3448 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3449 TemplateTy TemplateD, IdentifierInfo *TemplateII,
3450 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
3451 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
3452 bool IsCtorOrDtorName, bool IsClassName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00003453 if (SS.isInvalid())
3454 return true;
3455
Richard Smith62559bd2017-02-01 21:36:38 +00003456 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3457 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3458
3459 // C++ [temp.res]p3:
3460 // A qualified-id that refers to a type and in which the
3461 // nested-name-specifier depends on a template-parameter (14.6.2)
3462 // shall be prefixed by the keyword typename to indicate that the
3463 // qualified-id denotes a type, forming an
3464 // elaborated-type-specifier (7.1.5.3).
3465 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
Richard Smith3411fbf2017-02-01 21:41:18 +00003466 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
Richard Smith62559bd2017-02-01 21:36:38 +00003467 << SS.getScopeRep() << TemplateII->getName();
3468 // Recover as if 'typename' were specified.
3469 // FIXME: This is not quite correct recovery as we don't transform SS
3470 // into the corresponding dependent form (and we don't diagnose missing
3471 // 'template' keywords within SS as a result).
3472 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3473 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3474 TemplateArgsIn, RAngleLoc);
3475 }
3476
3477 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3478 // it's not actually allowed to be used as a type in most cases. Because
3479 // we annotate it before we know whether it's valid, we have to check for
3480 // this case here.
3481 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
Richard Smith74f02342017-01-19 21:00:13 +00003482 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3483 Diag(TemplateIILoc,
3484 TemplateKWLoc.isInvalid()
3485 ? diag::err_out_of_line_qualified_id_type_names_constructor
3486 : diag::ext_out_of_line_qualified_id_type_names_constructor)
3487 << TemplateII << 0 /*injected-class-name used as template name*/
3488 << 1 /*if any keyword was present, it was 'template'*/;
3489 }
3490 }
3491
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003492 TemplateName Template = TemplateD.get();
Richard Smithb23c5e82019-05-09 03:31:27 +00003493 if (Template.getAsAssumedTemplateName() &&
3494 resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
3495 return true;
Douglas Gregor8bf42052009-02-09 18:46:07 +00003496
Douglas Gregorc40290e2009-03-09 23:48:35 +00003497 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003498 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003499 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00003500
Douglas Gregor5a064722011-02-28 17:23:35 +00003501 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00003502 QualType T
3503 = Context.getDependentTemplateSpecializationType(ETK_None,
3504 DTN->getQualifier(),
3505 DTN->getIdentifier(),
3506 TemplateArgs);
3507 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00003508 TypeLocBuilder TLB;
3509 DependentTemplateSpecializationTypeLoc SpecTL
3510 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003511 SpecTL.setElaboratedKeywordLoc(SourceLocation());
3512 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00003513 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00003514 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00003515 SpecTL.setLAngleLoc(LAngleLoc);
3516 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00003517 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3518 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3519 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3520 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003521
Richard Smith74f02342017-01-19 21:00:13 +00003522 QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003523 if (Result.isNull())
3524 return true;
3525
Douglas Gregore7c20652011-03-02 00:47:37 +00003526 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003527 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00003528 TemplateSpecializationTypeLoc SpecTL
3529 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003530 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00003531 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003532 SpecTL.setLAngleLoc(LAngleLoc);
3533 SpecTL.setRAngleLoc(RAngleLoc);
3534 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3535 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00003536
Abramo Bagnara4244b432012-01-27 08:46:19 +00003537 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
3538 // constructor or destructor name (in such a case, the scope specifier
3539 // will be attached to the enclosing Decl or Expr node).
3540 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00003541 // Create an elaborated-type-specifier containing the nested-name-specifier.
3542 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
3543 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00003544 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00003545 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3546 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003547
Douglas Gregore7c20652011-03-02 00:47:37 +00003548 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00003549}
John McCall06f6fe8d2009-09-04 01:14:41 +00003550
Douglas Gregore7c20652011-03-02 00:47:37 +00003551TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00003552 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00003553 SourceLocation TagLoc,
3554 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003555 SourceLocation TemplateKWLoc,
3556 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00003557 SourceLocation TemplateLoc,
3558 SourceLocation LAngleLoc,
3559 ASTTemplateArgsPtr TemplateArgsIn,
3560 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003561 TemplateName Template = TemplateD.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00003562
Douglas Gregore7c20652011-03-02 00:47:37 +00003563 // Translate the parser's template argument list in our AST format.
3564 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3565 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003566
Douglas Gregore7c20652011-03-02 00:47:37 +00003567 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00003568 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00003569 ElaboratedTypeKeyword Keyword
3570 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00003571
Douglas Gregore7c20652011-03-02 00:47:37 +00003572 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3573 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
Simon Pilgrim6905d222016-12-30 22:55:33 +00003574 DTN->getQualifier(),
3575 DTN->getIdentifier(),
Douglas Gregore7c20652011-03-02 00:47:37 +00003576 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003577
3578 // Build type-source information.
Douglas Gregore7c20652011-03-02 00:47:37 +00003579 TypeLocBuilder TLB;
3580 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003581 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3582 SpecTL.setElaboratedKeywordLoc(TagLoc);
3583 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00003584 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003585 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003586 SpecTL.setLAngleLoc(LAngleLoc);
3587 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003588 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3589 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3590 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3591 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00003592
3593 if (TypeAliasTemplateDecl *TAT =
3594 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3595 // C++0x [dcl.type.elab]p2:
3596 // If the identifier resolves to a typedef-name or the simple-template-id
3597 // resolves to an alias template specialization, the
3598 // elaborated-type-specifier is ill-formed.
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00003599 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3600 << TAT << NTK_TypeAliasTemplate << TagKind;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003601 Diag(TAT->getLocation(), diag::note_declared_at);
3602 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003603
Douglas Gregore7c20652011-03-02 00:47:37 +00003604 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3605 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00003606 return TypeResult(true);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003607
Douglas Gregore7c20652011-03-02 00:47:37 +00003608 // Check the tag kind
3609 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00003610 RecordDecl *D = RT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00003611
John McCalld8fe9af2009-09-08 17:47:29 +00003612 IdentifierInfo *Id = D->getIdentifier();
3613 assert(Id && "templated class must have an identifier");
Simon Pilgrim6905d222016-12-30 22:55:33 +00003614
Richard Trieucaa33d32011-06-10 03:11:26 +00003615 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00003616 TagLoc, Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00003617 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00003618 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00003619 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00003620 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00003621 }
3622 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003623
Douglas Gregore7c20652011-03-02 00:47:37 +00003624 // Provide source-location information for the template specialization.
3625 TypeLocBuilder TLB;
3626 TemplateSpecializationTypeLoc SpecTL
3627 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003628 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003629 SpecTL.setTemplateNameLoc(TemplateLoc);
3630 SpecTL.setLAngleLoc(LAngleLoc);
3631 SpecTL.setRAngleLoc(RAngleLoc);
3632 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3633 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00003634
Douglas Gregore7c20652011-03-02 00:47:37 +00003635 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003636 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00003637 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3638 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00003639 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003640 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3641 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003642}
3643
Larisse Voufo39a1e502013-08-06 01:03:05 +00003644static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3645 NamedDecl *PrevDecl,
3646 SourceLocation Loc,
3647 bool IsPartialSpecialization);
3648
3649static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003650
Richard Smith300e0c32013-09-24 04:49:23 +00003651static bool isTemplateArgumentTemplateParameter(
3652 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3653 switch (Arg.getKind()) {
3654 case TemplateArgument::Null:
3655 case TemplateArgument::NullPtr:
3656 case TemplateArgument::Integral:
3657 case TemplateArgument::Declaration:
3658 case TemplateArgument::Pack:
3659 case TemplateArgument::TemplateExpansion:
3660 return false;
3661
3662 case TemplateArgument::Type: {
3663 QualType Type = Arg.getAsType();
3664 const TemplateTypeParmType *TPT =
3665 Arg.getAsType()->getAs<TemplateTypeParmType>();
3666 return TPT && !Type.hasQualifiers() &&
3667 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3668 }
3669
3670 case TemplateArgument::Expression: {
3671 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3672 if (!DRE || !DRE->getDecl())
3673 return false;
3674 const NonTypeTemplateParmDecl *NTTP =
3675 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3676 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3677 }
3678
3679 case TemplateArgument::Template:
3680 const TemplateTemplateParmDecl *TTP =
3681 dyn_cast_or_null<TemplateTemplateParmDecl>(
3682 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
3683 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3684 }
3685 llvm_unreachable("unexpected kind of template argument");
3686}
3687
3688static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
3689 ArrayRef<TemplateArgument> Args) {
3690 if (Params->size() != Args.size())
3691 return false;
3692
3693 unsigned Depth = Params->getDepth();
3694
3695 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3696 TemplateArgument Arg = Args[I];
3697
3698 // If the parameter is a pack expansion, the argument must be a pack
3699 // whose only element is a pack expansion.
3700 if (Params->getParam(I)->isParameterPack()) {
3701 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3702 !Arg.pack_begin()->isPackExpansion())
3703 return false;
3704 Arg = Arg.pack_begin()->getPackExpansionPattern();
3705 }
3706
3707 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3708 return false;
3709 }
3710
3711 return true;
3712}
3713
Richard Smith4b55a9c2014-04-17 03:29:33 +00003714/// Convert the parser's template argument list representation into our form.
3715static TemplateArgumentListInfo
3716makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
3717 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
3718 TemplateId.RAngleLoc);
3719 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
3720 TemplateId.NumArgs);
3721 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
3722 return TemplateArgs;
3723}
3724
Richard Smith0e617ec2016-12-27 07:56:27 +00003725template<typename PartialSpecDecl>
3726static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3727 if (Partial->getDeclContext()->isDependentContext())
3728 return;
3729
3730 // FIXME: Get the TDK from deduction in order to provide better diagnostics
3731 // for non-substitution-failure issues?
3732 TemplateDeductionInfo Info(Partial->getLocation());
3733 if (S.isMoreSpecializedThanPrimary(Partial, Info))
3734 return;
3735
3736 auto *Template = Partial->getSpecializedTemplate();
3737 S.Diag(Partial->getLocation(),
Richard Smithfa4a09d2016-12-27 20:03:09 +00003738 diag::ext_partial_spec_not_more_specialized_than_primary)
3739 << isa<VarTemplateDecl>(Template);
Richard Smith0e617ec2016-12-27 07:56:27 +00003740
3741 if (Info.hasSFINAEDiagnostic()) {
3742 PartialDiagnosticAt Diag = {SourceLocation(),
3743 PartialDiagnostic::NullDiagnostic()};
3744 Info.takeSFINAEDiagnostic(Diag);
3745 SmallString<128> SFINAEArgString;
3746 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3747 S.Diag(Diag.first,
3748 diag::note_partial_spec_not_more_specialized_than_primary)
3749 << SFINAEArgString;
3750 }
3751
3752 S.Diag(Template->getLocation(), diag::note_template_decl_here);
3753}
3754
Richard Smith4e05eaa2017-02-16 00:36:47 +00003755static void
3756noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
3757 const llvm::SmallBitVector &DeducibleParams) {
3758 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3759 if (!DeducibleParams[I]) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00003760 NamedDecl *Param = TemplateParams->getParam(I);
Richard Smith4e05eaa2017-02-16 00:36:47 +00003761 if (Param->getDeclName())
3762 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3763 << Param->getDeclName();
3764 else
3765 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3766 << "(anonymous)";
3767 }
3768 }
3769}
3770
3771
Richard Smith57aae072016-12-28 02:37:25 +00003772template<typename PartialSpecDecl>
3773static void checkTemplatePartialSpecialization(Sema &S,
3774 PartialSpecDecl *Partial) {
3775 // C++1z [temp.class.spec]p8: (DR1495)
3776 // - The specialization shall be more specialized than the primary
3777 // template (14.5.5.2).
3778 checkMoreSpecializedThanPrimary(S, Partial);
3779
3780 // C++ [temp.class.spec]p8: (DR1315)
3781 // - Each template-parameter shall appear at least once in the
3782 // template-id outside a non-deduced context.
3783 // C++1z [temp.class.spec.match]p3 (P0127R2)
3784 // If the template arguments of a partial specialization cannot be
3785 // deduced because of the structure of its template-parameter-list
3786 // and the template-id, the program is ill-formed.
3787 auto *TemplateParams = Partial->getTemplateParameters();
3788 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3789 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3790 TemplateParams->getDepth(), DeducibleParams);
3791
3792 if (!DeducibleParams.all()) {
3793 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3794 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3795 << isa<VarTemplatePartialSpecializationDecl>(Partial)
3796 << (NumNonDeducible > 1)
3797 << SourceRange(Partial->getLocation(),
3798 Partial->getTemplateArgsAsWritten()->RAngleLoc);
Richard Smith4e05eaa2017-02-16 00:36:47 +00003799 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
Richard Smith57aae072016-12-28 02:37:25 +00003800 }
3801}
3802
3803void Sema::CheckTemplatePartialSpecialization(
3804 ClassTemplatePartialSpecializationDecl *Partial) {
3805 checkTemplatePartialSpecialization(*this, Partial);
3806}
3807
3808void Sema::CheckTemplatePartialSpecialization(
3809 VarTemplatePartialSpecializationDecl *Partial) {
3810 checkTemplatePartialSpecialization(*this, Partial);
3811}
3812
Richard Smith4e05eaa2017-02-16 00:36:47 +00003813void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
3814 // C++1z [temp.param]p11:
3815 // A template parameter of a deduction guide template that does not have a
3816 // default-argument shall be deducible from the parameter-type-list of the
3817 // deduction guide template.
3818 auto *TemplateParams = TD->getTemplateParameters();
3819 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3820 MarkDeducedTemplateParameters(TD, DeducibleParams);
3821 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3822 // A parameter pack is deducible (to an empty pack).
3823 auto *Param = TemplateParams->getParam(I);
3824 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3825 DeducibleParams[I] = true;
3826 }
3827
3828 if (!DeducibleParams.all()) {
3829 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3830 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3831 << (NumNonDeducible > 1);
3832 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3833 }
3834}
3835
Larisse Voufo39a1e502013-08-06 01:03:05 +00003836DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00003837 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00003838 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00003839 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003840 // D must be variable template id.
Faisal Vali2ab8c152017-12-30 04:15:27 +00003841 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00003842 "Variable template specialization is declared with a template it.");
3843
3844 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00003845 TemplateArgumentListInfo TemplateArgs =
3846 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003847 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3848 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3849 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00003850
Richard Smithbeef3452014-01-16 23:39:20 +00003851 TemplateName Name = TemplateId->Template.get();
3852
3853 // The template-id must name a variable template.
3854 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00003855 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3856 if (!VarTemplate) {
3857 NamedDecl *FnTemplate;
3858 if (auto *OTS = Name.getAsOverloadedTemplate())
3859 FnTemplate = *OTS->begin();
3860 else
3861 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3862 if (FnTemplate)
3863 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3864 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00003865 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3866 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00003867 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003868
3869 // Check for unexpanded parameter packs in any of the template arguments.
3870 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3871 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3872 UPPC_PartialSpecialization))
3873 return true;
3874
3875 // Check that the template argument list is well-formed for this
3876 // template.
3877 SmallVector<TemplateArgument, 4> Converted;
3878 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
Saar Razfdf80e82019-12-06 01:30:21 +02003879 false, Converted,
3880 /*UpdateArgsWithConversion=*/true))
Larisse Voufo39a1e502013-08-06 01:03:05 +00003881 return true;
3882
Larisse Voufo39a1e502013-08-06 01:03:05 +00003883 // Find the variable template (partial) specialization declaration that
3884 // corresponds to these arguments.
3885 if (IsPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00003886 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
3887 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00003888 return true;
3889
Richard Smith57aae072016-12-28 02:37:25 +00003890 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
3891 // also do them during instantiation.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003892 bool InstantiationDependent;
3893 if (!Name.isDependent() &&
3894 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00003895 TemplateArgs.arguments(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00003896 InstantiationDependent)) {
3897 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3898 << VarTemplate->getDeclName();
3899 IsPartialSpecialization = false;
3900 }
Richard Smith300e0c32013-09-24 04:49:23 +00003901
3902 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
3903 Converted)) {
3904 // C++ [temp.class.spec]p9b3:
3905 //
3906 // -- The argument list of the specialization shall not be identical
3907 // to the implicit argument list of the primary template.
3908 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3909 << /*variable template*/ 1
3910 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
3911 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
3912 // FIXME: Recover from this by treating the declaration as a redeclaration
3913 // of the primary template.
3914 return true;
3915 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003916 }
3917
Craig Topperc3ec1492014-05-26 06:22:03 +00003918 void *InsertPos = nullptr;
3919 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003920
3921 if (IsPartialSpecialization)
3922 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00003923 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003924 else
Craig Topper7e0daca2014-06-26 04:58:53 +00003925 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003926
Craig Topperc3ec1492014-05-26 06:22:03 +00003927 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003928
3929 // Check whether we can declare a variable template specialization in
3930 // the current scope.
3931 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
3932 TemplateNameLoc,
3933 IsPartialSpecialization))
3934 return true;
3935
3936 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3937 // Since the only prior variable template specialization with these
3938 // arguments was referenced but not declared, reuse that
3939 // declaration node as our own, updating its source location and
3940 // the list of outer template parameters to reflect our new declaration.
3941 Specialization = PrevDecl;
3942 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00003943 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003944 } else if (IsPartialSpecialization) {
3945 // Create a new class template partial specialization declaration node.
3946 VarTemplatePartialSpecializationDecl *PrevPartial =
3947 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003948 VarTemplatePartialSpecializationDecl *Partial =
3949 VarTemplatePartialSpecializationDecl::Create(
3950 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
3951 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
David Majnemer8b622692016-07-03 21:17:51 +00003952 Converted, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003953
3954 if (!PrevPartial)
3955 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
3956 Specialization = Partial;
3957
3958 // If we are providing an explicit specialization of a member variable
3959 // template specialization, make a note of that.
3960 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00003961 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00003962
Richard Smith57aae072016-12-28 02:37:25 +00003963 CheckTemplatePartialSpecialization(Partial);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003964 } else {
3965 // Create a new class template specialization declaration node for
3966 // this explicit specialization or friend declaration.
3967 Specialization = VarTemplateSpecializationDecl::Create(
3968 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
David Majnemer8b622692016-07-03 21:17:51 +00003969 VarTemplate, DI->getType(), DI, SC, Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003970 Specialization->setTemplateArgsInfo(TemplateArgs);
3971
3972 if (!PrevDecl)
3973 VarTemplate->AddSpecialization(Specialization, InsertPos);
3974 }
3975
3976 // C++ [temp.expl.spec]p6:
3977 // If a template, a member template or the member of a class template is
3978 // explicitly specialized then that specialization shall be declared
3979 // before the first use of that specialization that would cause an implicit
3980 // instantiation to take place, in every translation unit in which such a
3981 // use occurs; no diagnostic is required.
3982 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3983 bool Okay = false;
3984 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
3985 // Is there any previous explicit specialization declaration?
3986 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3987 Okay = true;
3988 break;
3989 }
3990 }
3991
3992 if (!Okay) {
3993 SourceRange Range(TemplateNameLoc, RAngleLoc);
3994 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3995 << Name << Range;
3996
3997 Diag(PrevDecl->getPointOfInstantiation(),
3998 diag::note_instantiation_required_here)
3999 << (PrevDecl->getTemplateSpecializationKind() !=
4000 TSK_ImplicitInstantiation);
4001 return true;
4002 }
4003 }
4004
4005 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
4006 Specialization->setLexicalDeclContext(CurContext);
4007
4008 // Add the specialization into its lexical context, so that it can
4009 // be seen when iterating through the list of declarations in that
4010 // context. However, specializations are not found by name lookup.
4011 CurContext->addDecl(Specialization);
4012
4013 // Note that this is an explicit specialization.
4014 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4015
4016 if (PrevDecl) {
4017 // Check that this isn't a redefinition of this specialization,
4018 // merging with previous declarations.
4019 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00004020 forRedeclarationInCurContext());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004021 PrevSpec.addDecl(PrevDecl);
4022 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00004023 } else if (Specialization->isStaticDataMember() &&
4024 Specialization->isOutOfLine()) {
4025 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004026 }
4027
Larisse Voufo39a1e502013-08-06 01:03:05 +00004028 return Specialization;
4029}
4030
4031namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004032/// A partial specialization whose template arguments have matched
Larisse Voufo39a1e502013-08-06 01:03:05 +00004033/// a given template-id.
4034struct PartialSpecMatchResult {
4035 VarTemplatePartialSpecializationDecl *Partial;
4036 TemplateArgumentList *Args;
4037};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004038} // end anonymous namespace
Larisse Voufo39a1e502013-08-06 01:03:05 +00004039
4040DeclResult
4041Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
4042 SourceLocation TemplateNameLoc,
4043 const TemplateArgumentListInfo &TemplateArgs) {
4044 assert(Template && "A variable template id without template?");
4045
4046 // Check that the template argument list is well-formed for this template.
4047 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004048 if (CheckTemplateArgumentList(
4049 Template, TemplateNameLoc,
4050 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Saar Razfdf80e82019-12-06 01:30:21 +02004051 Converted, /*UpdateArgsWithConversion=*/true))
Larisse Voufo39a1e502013-08-06 01:03:05 +00004052 return true;
4053
4054 // Find the variable template specialization declaration that
4055 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00004056 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004057 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Richard Smith6739a102016-05-05 00:56:12 +00004058 Converted, InsertPos)) {
4059 checkSpecializationVisibility(TemplateNameLoc, Spec);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004060 // If we already have a variable template specialization, return it.
4061 return Spec;
Richard Smith6739a102016-05-05 00:56:12 +00004062 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004063
4064 // This is the first time we have referenced this variable template
4065 // specialization. Create the canonical declaration and add it to
4066 // the set of specializations, based on the closest partial specialization
4067 // that it represents. That is,
4068 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4069 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00004070 Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004071 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
4072 bool AmbiguousPartialSpec = false;
4073 typedef PartialSpecMatchResult MatchResult;
4074 SmallVector<MatchResult, 4> Matched;
4075 SourceLocation PointOfInstantiation = TemplateNameLoc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00004076 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4077 /*ForTakingAddress=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004078
4079 // 1. Attempt to find the closest partial specialization that this
4080 // specializes, if any.
4081 // If any of the template arguments is dependent, then this is probably
4082 // a placeholder for an incomplete declarative context; which must be
4083 // complete by instantiation time. Thus, do not search through the partial
4084 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00004085 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4086 // Perhaps better after unification of DeduceTemplateArguments() and
4087 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00004088 bool InstantiationDependent = false;
4089 if (!TemplateSpecializationType::anyDependentTemplateArguments(
4090 TemplateArgs, InstantiationDependent)) {
4091
4092 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4093 Template->getPartialSpecializations(PartialSpecs);
4094
4095 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
4096 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
4097 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4098
4099 if (TemplateDeductionResult Result =
4100 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
4101 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00004102 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00004103 FailedCandidates.addCandidate().set(
4104 DeclAccessPair::make(Template, AS_public), Partial,
4105 MakeDeductionFailureInfo(Context, Result, Info));
Larisse Voufo39a1e502013-08-06 01:03:05 +00004106 (void)Result;
4107 } else {
4108 Matched.push_back(PartialSpecMatchResult());
4109 Matched.back().Partial = Partial;
4110 Matched.back().Args = Info.take();
4111 }
4112 }
4113
Larisse Voufo39a1e502013-08-06 01:03:05 +00004114 if (Matched.size() >= 1) {
4115 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4116 if (Matched.size() == 1) {
4117 // -- If exactly one matching specialization is found, the
4118 // instantiation is generated from that specialization.
4119 // We don't need to do anything for this.
4120 } else {
4121 // -- If more than one matching specialization is found, the
4122 // partial order rules (14.5.4.2) are used to determine
4123 // whether one of the specializations is more specialized
4124 // than the others. If none of the specializations is more
4125 // specialized than all of the other matching
4126 // specializations, then the use of the variable template is
4127 // ambiguous and the program is ill-formed.
4128 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4129 PEnd = Matched.end();
4130 P != PEnd; ++P) {
4131 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4132 PointOfInstantiation) ==
4133 P->Partial)
4134 Best = P;
4135 }
4136
4137 // Determine if the best partial specialization is more specialized than
4138 // the others.
4139 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4140 PEnd = Matched.end();
4141 P != PEnd; ++P) {
4142 if (P != Best && getMoreSpecializedPartialSpecialization(
4143 P->Partial, Best->Partial,
4144 PointOfInstantiation) != Best->Partial) {
4145 AmbiguousPartialSpec = true;
4146 break;
4147 }
4148 }
4149 }
4150
4151 // Instantiate using the best variable template partial specialization.
4152 InstantiationPattern = Best->Partial;
4153 InstantiationArgs = Best->Args;
4154 } else {
4155 // -- If no match is found, the instantiation is generated
4156 // from the primary template.
4157 // InstantiationPattern = Template->getTemplatedDecl();
4158 }
4159 }
4160
Larisse Voufo39a1e502013-08-06 01:03:05 +00004161 // 2. Create the canonical declaration.
Richard Smith6739a102016-05-05 00:56:12 +00004162 // Note that we do not instantiate a definition until we see an odr-use
4163 // in DoMarkVarDeclReferenced().
Larisse Voufo39a1e502013-08-06 01:03:05 +00004164 // FIXME: LateAttrs et al.?
4165 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4166 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
4167 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
4168 if (!Decl)
4169 return true;
4170
4171 if (AmbiguousPartialSpec) {
4172 // Partial ordering did not produce a clear winner. Complain.
4173 Decl->setInvalidDecl();
4174 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4175 << Decl;
4176
4177 // Print the matching partial specializations.
Yaron Keren1cb81462016-11-16 13:45:34 +00004178 for (MatchResult P : Matched)
4179 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4180 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4181 *P.Args);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004182 return true;
4183 }
4184
4185 if (VarTemplatePartialSpecializationDecl *D =
4186 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4187 Decl->setInstantiationOf(D, InstantiationArgs);
4188
Richard Smith6739a102016-05-05 00:56:12 +00004189 checkSpecializationVisibility(TemplateNameLoc, Decl);
4190
Larisse Voufo39a1e502013-08-06 01:03:05 +00004191 assert(Decl && "No variable template specialization?");
4192 return Decl;
4193}
4194
4195ExprResult
4196Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
4197 const DeclarationNameInfo &NameInfo,
4198 VarTemplateDecl *Template, SourceLocation TemplateLoc,
4199 const TemplateArgumentListInfo *TemplateArgs) {
4200
4201 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4202 *TemplateArgs);
4203 if (Decl.isInvalid())
4204 return ExprError();
4205
4206 VarDecl *Var = cast<VarDecl>(Decl.get());
4207 if (!Var->getTemplateSpecializationKind())
4208 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
4209 NameInfo.getLoc());
4210
4211 // Build an ordinary singleton decl ref.
4212 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00004213 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004214}
4215
Richard Smithecad88d2018-04-26 01:08:00 +00004216void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4217 SourceLocation Loc) {
4218 Diag(Loc, diag::err_template_missing_args)
4219 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4220 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4221 Diag(TD->getLocation(), diag::note_template_decl_here)
4222 << TD->getTemplateParameters()->getSourceRange();
4223 }
4224}
4225
Saar Razd7aae332019-07-10 21:25:49 +00004226ExprResult
4227Sema::CheckConceptTemplateId(const CXXScopeSpec &SS,
Saar Raz5d98ba62019-10-15 15:24:26 +00004228 SourceLocation TemplateKWLoc,
4229 SourceLocation ConceptNameLoc,
4230 NamedDecl *FoundDecl,
4231 ConceptDecl *NamedConcept,
Saar Razd7aae332019-07-10 21:25:49 +00004232 const TemplateArgumentListInfo *TemplateArgs) {
Saar Raz5d98ba62019-10-15 15:24:26 +00004233 assert(NamedConcept && "A concept template id without a template?");
4234
4235 llvm::SmallVector<TemplateArgument, 4> Converted;
4236 if (CheckTemplateArgumentList(NamedConcept, ConceptNameLoc,
4237 const_cast<TemplateArgumentListInfo&>(*TemplateArgs),
4238 /*PartialTemplateArgs=*/false, Converted,
4239 /*UpdateArgsWithConversion=*/false))
4240 return ExprError();
4241
Saar Razfdf80e82019-12-06 01:30:21 +02004242 ConstraintSatisfaction Satisfaction;
Saar Raz5d98ba62019-10-15 15:24:26 +00004243 bool AreArgsDependent = false;
4244 for (TemplateArgument &Arg : Converted) {
4245 if (Arg.isDependent()) {
4246 AreArgsDependent = true;
4247 break;
4248 }
4249 }
Saar Razfdf80e82019-12-06 01:30:21 +02004250 if (!AreArgsDependent &&
4251 CheckConstraintSatisfaction(NamedConcept,
4252 {NamedConcept->getConstraintExpr()},
4253 Converted,
4254 SourceRange(SS.isSet() ? SS.getBeginLoc() :
4255 ConceptNameLoc,
4256 TemplateArgs->getRAngleLoc()),
4257 Satisfaction))
Saar Raz5d98ba62019-10-15 15:24:26 +00004258 return ExprError();
Saar Razfdf80e82019-12-06 01:30:21 +02004259
Saar Raz5d98ba62019-10-15 15:24:26 +00004260 return ConceptSpecializationExpr::Create(Context,
4261 SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc{},
4262 TemplateKWLoc, ConceptNameLoc, FoundDecl, NamedConcept,
4263 ASTTemplateArgumentListInfo::Create(Context, *TemplateArgs), Converted,
Saar Razfdf80e82019-12-06 01:30:21 +02004264 AreArgsDependent ? nullptr : &Satisfaction);
Saar Razd7aae332019-07-10 21:25:49 +00004265}
4266
John McCalldadc5752010-08-24 06:29:42 +00004267ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004268 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00004269 LookupResult &R,
4270 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00004271 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00004272 // FIXME: Can we do any checking at this point? I guess we could check the
4273 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00004274 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00004275 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00004276 // foo<int> could identify a single function unambiguously
4277 // This approach does NOT work, since f<int>(1);
4278 // gets resolved prior to resorting to overload resolution
4279 // i.e., template<class T> void f(double);
4280 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00004281
4282 // These should be filtered out by our callers.
John McCalle66edc12009-11-24 19:00:30 +00004283 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4284
Richard Smith04100942018-04-26 02:10:22 +00004285 // Non-function templates require a template argument list.
4286 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4287 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4288 diagnoseMissingTemplateArguments(TemplateName(TD), R.getNameLoc());
4289 return ExprError();
4290 }
4291 }
4292
Richard Smith0bf96f92018-04-25 22:58:55 +00004293 auto AnyDependentArguments = [&]() -> bool {
4294 bool InstantiationDependent;
4295 return TemplateArgs &&
4296 TemplateSpecializationType::anyDependentTemplateArguments(
4297 *TemplateArgs, InstantiationDependent);
4298 };
4299
Larisse Voufo39a1e502013-08-06 01:03:05 +00004300 // In C++1y, check variable template ids.
Richard Smith0bf96f92018-04-25 22:58:55 +00004301 if (R.getAsSingle<VarTemplateDecl>() && !AnyDependentArguments()) {
Richard Smithd7d11ef2014-02-03 20:09:56 +00004302 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
4303 R.getAsSingle<VarTemplateDecl>(),
4304 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004305 }
4306
Saar Razf567b002019-10-17 00:16:01 +00004307 if (R.getAsSingle<ConceptDecl>()) {
Saar Raz5d98ba62019-10-15 15:24:26 +00004308 return CheckConceptTemplateId(SS, TemplateKWLoc,
4309 R.getLookupNameInfo().getBeginLoc(),
4310 R.getFoundDecl(),
4311 R.getAsSingle<ConceptDecl>(), TemplateArgs);
Saar Razd7aae332019-07-10 21:25:49 +00004312 }
4313
John McCall58cc69d2010-01-27 01:50:18 +00004314 // We don't want lookup warnings at this point.
4315 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004316
John McCalle66edc12009-11-24 19:00:30 +00004317 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00004318 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00004319 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00004320 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004321 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004322 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00004323 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00004324
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004325 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00004326}
4327
John McCalle66edc12009-11-24 19:00:30 +00004328// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00004329ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004330Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004331 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004332 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00004333 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004334
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00004335 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00004336 DeclContext *DC;
4337 if (!(DC = computeDeclContext(SS, false)) ||
4338 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00004339 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00004340 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004341
Douglas Gregor786123d2010-05-21 23:18:07 +00004342 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004343 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Richard Smith79810042018-05-11 02:43:08 +00004344 if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(),
4345 /*Entering*/false, MemberOfUnknownSpecialization,
4346 TemplateKWLoc))
4347 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004348
John McCalle66edc12009-11-24 19:00:30 +00004349 if (R.isAmbiguous())
4350 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004351
John McCalle66edc12009-11-24 19:00:30 +00004352 if (R.empty()) {
Richard Smith79810042018-05-11 02:43:08 +00004353 Diag(NameInfo.getLoc(), diag::err_no_member)
4354 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00004355 return ExprError();
4356 }
4357
4358 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004359 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00004360 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00004361 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00004362 Diag(Temp->getLocation(), diag::note_referenced_class_template);
4363 return ExprError();
4364 }
4365
Abramo Bagnara7945c982012-01-27 09:46:47 +00004366 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00004367}
4368
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004369/// Form a dependent template name.
Douglas Gregorb67535d2009-03-31 00:43:58 +00004370///
4371/// This action forms a dependent template name given the template
4372/// name and its (presumably dependent) scope specifier. For
4373/// example, given "MetaFun::template apply", the scope specifier \p
4374/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
4375/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004376TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00004377 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004378 SourceLocation TemplateKWLoc,
Richard Smithc08b6932018-04-27 02:00:13 +00004379 const UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00004380 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00004381 bool EnteringContext,
Richard Smithfd3dae02017-01-20 00:20:39 +00004382 TemplateTy &Result,
4383 bool AllowInjectedClassName) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004384 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4385 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004386 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004387 diag::warn_cxx98_compat_template_outside_of_template :
4388 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004389 << FixItHint::CreateRemoval(TemplateKWLoc);
4390
Craig Topperc3ec1492014-05-26 06:22:03 +00004391 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00004392 if (SS.isSet())
4393 LookupCtx = computeDeclContext(SS, EnteringContext);
4394 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00004395 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00004396 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00004397 // C++0x [temp.names]p5:
4398 // If a name prefixed by the keyword template is not the name of
4399 // a template, the program is ill-formed. [Note: the keyword
4400 // template may not be applied to non-template members of class
4401 // templates. -end note ] [ Note: as is the case with the
4402 // typename prefix, the template prefix is allowed in cases
4403 // where it is not strictly necessary; i.e., when the
4404 // nested-name-specifier or the expression on the left of the ->
4405 // or . is not dependent on a template-parameter, or the use
4406 // does not appear in the scope of a template. -end note]
4407 //
4408 // Note: C++03 was more strict here, because it banned the use of
4409 // the "template" keyword prior to a template-name that was not a
4410 // dependent name. C++ DR468 relaxed this requirement (the
4411 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00004412 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00004413 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00004414 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00004415 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00004416 MemberOfUnknownSpecialization);
Richard Smith79810042018-05-11 02:43:08 +00004417 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization) {
Douglas Gregorbb119652010-06-16 23:00:59 +00004418 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00004419 } else if (TNK == TNK_Non_template) {
Richard Smith79810042018-05-11 02:43:08 +00004420 // Do the lookup again to determine if this is a "nothing found" case or
4421 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
4422 // need to do this.
4423 DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004424 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
Richard Smith79810042018-05-11 02:43:08 +00004425 LookupOrdinaryName);
4426 bool MOUS;
4427 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext,
Richard Smithafcfb6b2019-02-15 21:53:07 +00004428 MOUS, TemplateKWLoc) && !R.isAmbiguous())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004429 Diag(Name.getBeginLoc(), diag::err_no_member)
Richard Smith79810042018-05-11 02:43:08 +00004430 << DNI.getName() << LookupCtx << SS.getRange();
Douglas Gregorbb119652010-06-16 23:00:59 +00004431 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00004432 } else {
4433 // We found something; return it.
Richard Smithfd3dae02017-01-20 00:20:39 +00004434 auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
4435 if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
Faisal Vali2ab8c152017-12-30 04:15:27 +00004436 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4437 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
Richard Smithfd3dae02017-01-20 00:20:39 +00004438 // C++14 [class.qual]p2:
4439 // In a lookup in which function names are not ignored and the
4440 // nested-name-specifier nominates a class C, if the name specified
4441 // [...] is the injected-class-name of C, [...] the name is instead
4442 // considered to name the constructor
4443 //
4444 // We don't get here if naming the constructor would be valid, so we
4445 // just reject immediately and recover by treating the
4446 // injected-class-name as naming the template.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004447 Diag(Name.getBeginLoc(),
Richard Smithfd3dae02017-01-20 00:20:39 +00004448 diag::ext_out_of_line_qualified_id_type_names_constructor)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004449 << Name.Identifier
4450 << 0 /*injected-class-name used as template name*/
4451 << 1 /*'template' keyword was used*/;
Richard Smithfd3dae02017-01-20 00:20:39 +00004452 }
Douglas Gregorbb119652010-06-16 23:00:59 +00004453 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00004454 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00004455 }
4456
Aaron Ballman4a979672014-01-03 13:56:08 +00004457 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004458
Douglas Gregor3cf81312009-11-03 23:16:33 +00004459 switch (Name.getKind()) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00004460 case UnqualifiedIdKind::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004461 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00004462 Name.Identifier));
4463 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004464
Faisal Vali2ab8c152017-12-30 04:15:27 +00004465 case UnqualifiedIdKind::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00004466 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00004467 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00004468 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00004469
Faisal Vali2ab8c152017-12-30 04:15:27 +00004470 case UnqualifiedIdKind::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00004471 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00004472
Douglas Gregor3cf81312009-11-03 23:16:33 +00004473 default:
4474 break;
4475 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004476
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004477 Diag(Name.getBeginLoc(), diag::err_template_kw_refers_to_non_template)
4478 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
4479 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00004480 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00004481}
4482
Mike Stump11289f42009-09-09 15:08:12 +00004483bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00004484 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004485 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00004486 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00004487 QualType ArgType;
4488 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00004489
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004490 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004491 switch(Arg.getKind()) {
4492 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004493 // C++ [temp.arg.type]p1:
4494 // A template-argument for a template-parameter which is a
4495 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00004496 ArgType = Arg.getAsType();
4497 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004498 break;
Richard Smith77a9c602018-02-28 03:02:23 +00004499 case TemplateArgument::Template:
4500 case TemplateArgument::TemplateExpansion: {
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004501 // We have a template type parameter but the template argument
4502 // is a template without any arguments.
4503 SourceRange SR = AL.getSourceRange();
Richard Smith77a9c602018-02-28 03:02:23 +00004504 TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
Richard Smithecad88d2018-04-26 01:08:00 +00004505 diagnoseMissingTemplateArguments(Name, SR.getEnd());
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004506 return true;
4507 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004508 case TemplateArgument::Expression: {
4509 // We have a template type parameter but the template argument is an
4510 // expression; see if maybe it is missing the "typename" keyword.
4511 CXXScopeSpec SS;
4512 DeclarationNameInfo NameInfo;
4513
4514 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
4515 SS.Adopt(ArgExpr->getQualifierLoc());
4516 NameInfo = ArgExpr->getNameInfo();
4517 } else if (DependentScopeDeclRefExpr *ArgExpr =
4518 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4519 SS.Adopt(ArgExpr->getQualifierLoc());
4520 NameInfo = ArgExpr->getNameInfo();
4521 } else if (CXXDependentScopeMemberExpr *ArgExpr =
4522 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00004523 if (ArgExpr->isImplicitAccess()) {
4524 SS.Adopt(ArgExpr->getQualifierLoc());
4525 NameInfo = ArgExpr->getMemberNameInfo();
4526 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004527 }
4528
Reid Kleckner377c1592014-06-10 23:29:48 +00004529 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004530 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4531 LookupParsedName(Result, CurScope, &SS);
4532
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00004533 if (Result.getAsSingle<TypeDecl>() ||
4534 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00004535 LookupResult::NotFoundInCurrentInstantiation) {
4536 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004537 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00004538 Diag(Loc, getLangOpts().MSVCCompat
4539 ? diag::ext_ms_template_type_arg_missing_typename
4540 : diag::err_template_arg_must_be_type_suggest)
4541 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004542 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00004543
4544 // Recover by synthesizing a type using the location information that we
4545 // already have.
4546 ArgType =
4547 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
4548 TypeLocBuilder TLB;
4549 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
4550 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4551 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4552 TL.setNameLoc(NameInfo.getLoc());
4553 TSI = TLB.getTypeSourceInfo(Context, ArgType);
4554
4555 // Overwrite our input TemplateArgumentLoc so that we can recover
4556 // properly.
4557 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
4558 TemplateArgumentLocInfo(TSI));
4559
4560 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004561 }
4562 }
4563 // fallthrough
Galina Kistanova3779cb32017-06-07 06:25:05 +00004564 LLVM_FALLTHROUGH;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004565 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004566 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004567 // We have a template type parameter but the template argument
4568 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00004569 SourceRange SR = AL.getSourceRange();
4570 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004571 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00004572
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004573 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004574 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004575 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004576
Reid Kleckner377c1592014-06-10 23:29:48 +00004577 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004578 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004579
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004580 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00004581 ArgType = Context.getCanonicalType(ArgType);
Simon Pilgrim6905d222016-12-30 22:55:33 +00004582
Douglas Gregore46db902011-06-17 22:11:49 +00004583 // Objective-C ARC:
4584 // If an explicitly-specified template argument type is a lifetime type
4585 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004586 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00004587 ArgType->isObjCLifetimeType() &&
4588 !ArgType.getObjCLifetime()) {
4589 Qualifiers Qs;
4590 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
4591 ArgType = Context.getQualifiedType(ArgType, Qs);
4592 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00004593
Douglas Gregore46db902011-06-17 22:11:49 +00004594 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004595 return false;
4596}
4597
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004598/// Substitute template arguments into the default template argument for
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004599/// the given template type parameter.
4600///
4601/// \param SemaRef the semantic analysis object for which we are performing
4602/// the substitution.
4603///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004604/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004605/// for.
4606///
4607/// \param TemplateLoc the location of the template name that started the
4608/// template-id we are checking.
4609///
4610/// \param RAngleLoc the location of the right angle bracket ('>') that
4611/// terminates the template-id.
4612///
4613/// \param Param the template template parameter whose default we are
4614/// substituting into.
4615///
4616/// \param Converted the list of template arguments provided for template
4617/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004618/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00004619static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004620SubstDefaultTemplateArgument(Sema &SemaRef,
4621 TemplateDecl *Template,
4622 SourceLocation TemplateLoc,
4623 SourceLocation RAngleLoc,
4624 TemplateTypeParmDecl *Param,
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00004625 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00004626 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004627
4628 // If the argument type is dependent, instantiate it now based
4629 // on the previously-computed template arguments.
Erik Pilkingtonba88e212018-11-12 21:31:06 +00004630 if (ArgType->getType()->isInstantiationDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004631 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00004632 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004633 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004634 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00004635 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004636
David Majnemer8b622692016-07-03 21:17:51 +00004637 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004638
4639 // Only substitute for the innermost template argument list.
4640 MultiLevelTemplateArgumentList TemplateArgLists;
4641 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4642 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4643 TemplateArgLists.addOuterTemplateArguments(None);
4644
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00004645 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00004646 ArgType =
4647 SemaRef.SubstType(ArgType, TemplateArgLists,
4648 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004649 }
4650
4651 return ArgType;
4652}
4653
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004654/// Substitute template arguments into the default template argument for
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004655/// the given non-type template parameter.
4656///
4657/// \param SemaRef the semantic analysis object for which we are performing
4658/// the substitution.
4659///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004660/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004661/// for.
4662///
4663/// \param TemplateLoc the location of the template name that started the
4664/// template-id we are checking.
4665///
4666/// \param RAngleLoc the location of the right angle bracket ('>') that
4667/// terminates the template-id.
4668///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004669/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004670/// substituting into.
4671///
4672/// \param Converted the list of template arguments provided for template
4673/// parameters that precede \p Param in the template parameter list.
4674///
4675/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00004676static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004677SubstDefaultTemplateArgument(Sema &SemaRef,
4678 TemplateDecl *Template,
4679 SourceLocation TemplateLoc,
4680 SourceLocation RAngleLoc,
4681 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004682 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004683 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00004684 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004685 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004686 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004687 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004688
David Majnemer8b622692016-07-03 21:17:51 +00004689 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004690
4691 // Only substitute for the innermost template argument list.
4692 MultiLevelTemplateArgumentList TemplateArgLists;
4693 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4694 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4695 TemplateArgLists.addOuterTemplateArguments(None);
4696
Richard Smithcb167c82019-08-24 02:30:00 +00004697 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
Faisal Valid143a0c2017-04-01 21:30:49 +00004698 EnterExpressionEvaluationContext ConstantEvaluated(
4699 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00004700 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004701}
4702
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004703/// Substitute template arguments into the default template argument for
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004704/// the given template template parameter.
4705///
4706/// \param SemaRef the semantic analysis object for which we are performing
4707/// the substitution.
4708///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004709/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004710/// for.
4711///
4712/// \param TemplateLoc the location of the template name that started the
4713/// template-id we are checking.
4714///
4715/// \param RAngleLoc the location of the right angle bracket ('>') that
4716/// terminates the template-id.
4717///
4718/// \param Param the template template parameter whose default we are
4719/// substituting into.
4720///
4721/// \param Converted the list of template arguments provided for template
4722/// parameters that precede \p Param in the template parameter list.
4723///
Simon Pilgrim6905d222016-12-30 22:55:33 +00004724/// \param QualifierLoc Will be set to the nested-name-specifier (with
Douglas Gregordf846d12011-03-02 18:46:51 +00004725/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00004726///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004727/// \returns the substituted template argument, or NULL if an error occurred.
4728static TemplateName
4729SubstDefaultTemplateArgument(Sema &SemaRef,
4730 TemplateDecl *Template,
4731 SourceLocation TemplateLoc,
4732 SourceLocation RAngleLoc,
4733 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004734 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00004735 NestedNameSpecifierLoc &QualifierLoc) {
Richard Smith54f18e82016-08-31 02:15:21 +00004736 Sema::InstantiatingTemplate Inst(
4737 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
4738 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004739 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004740 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004741
David Majnemer8b622692016-07-03 21:17:51 +00004742 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004743
4744 // Only substitute for the innermost template argument list.
4745 MultiLevelTemplateArgumentList TemplateArgLists;
4746 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4747 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4748 TemplateArgLists.addOuterTemplateArguments(None);
4749
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00004750 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00004751 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00004752 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00004753 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00004754 QualifierLoc =
4755 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00004756 if (!QualifierLoc)
4757 return TemplateName();
4758 }
David Majnemer89189202013-08-28 23:48:32 +00004759
4760 return SemaRef.SubstTemplateName(
4761 QualifierLoc,
4762 Param->getDefaultArgument().getArgument().getAsTemplate(),
4763 Param->getDefaultArgument().getTemplateNameLoc(),
4764 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004765}
4766
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004767/// If the given template parameter has a default template
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004768/// argument, substitute into that default template argument and
4769/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004770TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004771Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
4772 SourceLocation TemplateLoc,
4773 SourceLocation RAngleLoc,
4774 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00004775 SmallVectorImpl<TemplateArgument>
4776 &Converted,
4777 bool &HasDefaultArg) {
4778 HasDefaultArg = false;
4779
4780 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004781 if (!hasVisibleDefaultArgument(TypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004782 return TemplateArgumentLoc();
4783
Richard Smithc87b9382013-07-04 01:01:24 +00004784 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00004785 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004786 TemplateLoc,
4787 RAngleLoc,
4788 TypeParm,
4789 Converted);
4790 if (DI)
4791 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4792
4793 return TemplateArgumentLoc();
4794 }
4795
4796 if (NonTypeTemplateParmDecl *NonTypeParm
4797 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004798 if (!hasVisibleDefaultArgument(NonTypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004799 return TemplateArgumentLoc();
4800
Richard Smithc87b9382013-07-04 01:01:24 +00004801 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00004802 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00004803 TemplateLoc,
4804 RAngleLoc,
4805 NonTypeParm,
4806 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004807 if (Arg.isInvalid())
4808 return TemplateArgumentLoc();
4809
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004810 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004811 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
4812 }
4813
4814 TemplateTemplateParmDecl *TempTempParm
4815 = cast<TemplateTemplateParmDecl>(Param);
Richard Smith95d83952015-06-10 20:36:34 +00004816 if (!hasVisibleDefaultArgument(TempTempParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004817 return TemplateArgumentLoc();
4818
Richard Smithc87b9382013-07-04 01:01:24 +00004819 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00004820 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004821 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004822 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004823 RAngleLoc,
4824 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00004825 Converted,
4826 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004827 if (TName.isNull())
4828 return TemplateArgumentLoc();
4829
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004830 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00004831 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004832 TempTempParm->getDefaultArgument().getTemplateNameLoc());
4833}
4834
Richard Smith11255ec2017-01-18 19:19:22 +00004835/// Convert a template-argument that we parsed as a type into a template, if
4836/// possible. C++ permits injected-class-names to perform dual service as
4837/// template template arguments and as template type arguments.
4838static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
4839 // Extract and step over any surrounding nested-name-specifier.
4840 NestedNameSpecifierLoc QualLoc;
4841 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4842 if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
4843 return TemplateArgumentLoc();
4844
4845 QualLoc = ETLoc.getQualifierLoc();
4846 TLoc = ETLoc.getNamedTypeLoc();
4847 }
4848
4849 // If this type was written as an injected-class-name, it can be used as a
4850 // template template argument.
4851 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4852 return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
4853 QualLoc, InjLoc.getNameLoc());
4854
4855 // If this type was written as an injected-class-name, it may have been
4856 // converted to a RecordType during instantiation. If the RecordType is
4857 // *not* wrapped in a TemplateSpecializationType and denotes a class
4858 // template specialization, it must have come from an injected-class-name.
4859 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
4860 if (auto *CTSD =
4861 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
4862 return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
4863 QualLoc, RecLoc.getNameLoc());
4864
4865 return TemplateArgumentLoc();
4866}
4867
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004868/// Check that the given template argument corresponds to the given
Douglas Gregorda0fb532009-11-11 19:31:23 +00004869/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004870///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004871/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004872/// checked.
4873///
Richard Trieu15b66532015-01-24 02:48:32 +00004874/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004875///
4876/// \param Template The template in which the template argument resides.
4877///
4878/// \param TemplateLoc The location of the template name for the template
4879/// whose argument list we're matching.
4880///
4881/// \param RAngleLoc The location of the right angle bracket ('>') that closes
4882/// the template argument list.
4883///
4884/// \param ArgumentPackIndex The index into the argument pack where this
4885/// argument will be placed. Only valid if the parameter is a parameter pack.
4886///
4887/// \param Converted The checked, converted argument will be added to the
4888/// end of this small vector.
4889///
4890/// \param CTAK Describes how we arrived at this particular template argument:
4891/// explicitly written, deduced, etc.
4892///
4893/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004894bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00004895 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00004896 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004897 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004898 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004899 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004900 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00004901 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00004902 // Check template type parameters.
4903 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004904 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004905
Douglas Gregoreebed722009-11-11 19:41:09 +00004906 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004907 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004908 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00004909 // with the template arguments we've seen thus far. But if the
4910 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004911 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004912 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
4913 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004914
Richard Smith8d2eaf92019-10-03 18:24:40 +00004915 if (NTTPType->isInstantiationDependentType() &&
Peter Collingbourne01687632010-12-10 17:08:53 +00004916 !isa<TemplateTemplateParmDecl>(Template) &&
4917 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004918 // Do substitution on the type of the non-type template parameter.
4919 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00004920 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004921 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004922 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004923 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004924
4925 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00004926 Converted);
Richard Smith07ed9cf2019-06-20 19:49:13 +00004927
4928 // If the parameter is a pack expansion, expand this slice of the pack.
4929 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
4930 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this,
4931 ArgumentPackIndex);
4932 NTTPType = SubstType(PET->getPattern(),
4933 MultiLevelTemplateArgumentList(TemplateArgs),
4934 NTTP->getLocation(),
4935 NTTP->getDeclName());
4936 } else {
4937 NTTPType = SubstType(NTTPType,
4938 MultiLevelTemplateArgumentList(TemplateArgs),
4939 NTTP->getLocation(),
4940 NTTP->getDeclName());
4941 }
4942
Douglas Gregorda0fb532009-11-11 19:31:23 +00004943 // If that worked, check the non-type template parameter type
4944 // for validity.
4945 if (!NTTPType.isNull())
4946 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
4947 NTTP->getLocation());
4948 if (NTTPType.isNull())
4949 return true;
4950 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004951
Douglas Gregorda0fb532009-11-11 19:31:23 +00004952 switch (Arg.getArgument().getKind()) {
4953 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00004954 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004955
Douglas Gregorda0fb532009-11-11 19:31:23 +00004956 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004957 TemplateArgument Result;
Erich Keanec90bb6d2018-05-07 17:05:20 +00004958 unsigned CurSFINAEErrors = NumSFINAEErrors;
John Wiegley01296292011-04-08 18:41:53 +00004959 ExprResult Res =
4960 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
4961 Result, CTAK);
4962 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00004963 return true;
Erich Keanec90bb6d2018-05-07 17:05:20 +00004964 // If the current template argument causes an error, give up now.
4965 if (CurSFINAEErrors < NumSFINAEErrors)
4966 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004967
Richard Trieu15b66532015-01-24 02:48:32 +00004968 // If the resulting expression is new, then use it in place of the
4969 // old expression in the template argument.
4970 if (Res.get() != Arg.getArgument().getAsExpr()) {
4971 TemplateArgument TA(Res.get());
4972 Arg = TemplateArgumentLoc(TA, Res.get());
4973 }
4974
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004975 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004976 break;
4977 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004978
Douglas Gregorda0fb532009-11-11 19:31:23 +00004979 case TemplateArgument::Declaration:
4980 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00004981 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00004982 // We've already checked this template argument, so just copy
4983 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004984 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00004985 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004986
Douglas Gregorda0fb532009-11-11 19:31:23 +00004987 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004988 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00004989 // We were given a template template argument. It may not be ill-formed;
4990 // see below.
4991 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004992 = Arg.getArgument().getAsTemplateOrTemplatePattern()
4993 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004994 // We have a template argument such as \c T::template X, which we
4995 // parsed as a template template argument. However, since we now
4996 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004997 // template name into an expression.
4998
4999 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
5000 Arg.getTemplateNameLoc());
5001
Douglas Gregor3a43fd62011-02-25 20:49:16 +00005002 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00005003 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00005004 // FIXME: the template-template arg was a DependentTemplateName,
5005 // so it was provided with a template keyword. However, its source
5006 // location is not stored in the template argument structure.
5007 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005008 ExprResult E = DependentScopeDeclRefExpr::Create(
5009 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5010 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005011
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005012 // If we parsed the template argument as a pack expansion, create a
5013 // pack expansion expression.
5014 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005015 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00005016 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005017 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005018 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005019
Douglas Gregorda0fb532009-11-11 19:31:23 +00005020 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005021 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00005022 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00005023 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005024
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005025 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00005026 break;
5027 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005028
Douglas Gregorda0fb532009-11-11 19:31:23 +00005029 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00005030 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00005031 // therefore cannot be a non-type template argument.
5032 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
5033 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005034
Douglas Gregorda0fb532009-11-11 19:31:23 +00005035 Diag(Param->getLocation(), diag::note_template_param_here);
5036 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005037
Douglas Gregorda0fb532009-11-11 19:31:23 +00005038 case TemplateArgument::Type: {
5039 // We have a non-type template parameter but the template
5040 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005041
Douglas Gregorda0fb532009-11-11 19:31:23 +00005042 // C++ [temp.arg]p2:
5043 // In a template-argument, an ambiguity between a type-id and
5044 // an expression is resolved to a type-id, regardless of the
5045 // form of the corresponding template-parameter.
5046 //
5047 // We warn specifically about this case, since it can be rather
5048 // confusing for users.
5049 QualType T = Arg.getArgument().getAsType();
5050 SourceRange SR = Arg.getSourceRange();
5051 if (T->isFunctionType())
5052 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5053 else
5054 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5055 Diag(Param->getLocation(), diag::note_template_param_here);
5056 return true;
5057 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005058
Douglas Gregorda0fb532009-11-11 19:31:23 +00005059 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005060 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00005061 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005062
Douglas Gregorda0fb532009-11-11 19:31:23 +00005063 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005064 }
5065
5066
Douglas Gregorda0fb532009-11-11 19:31:23 +00005067 // Check template template parameters.
5068 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005069
Richard Smith5d331022018-03-08 01:07:33 +00005070 TemplateParameterList *Params = TempParm->getTemplateParameters();
5071 if (TempParm->isExpandedParameterPack())
5072 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5073
Douglas Gregorda0fb532009-11-11 19:31:23 +00005074 // Substitute into the template parameter list of the template
5075 // template parameter, since previously-supplied template arguments
5076 // may appear within the template template parameter.
Richard Smith5d331022018-03-08 01:07:33 +00005077 //
5078 // FIXME: Skip this if the parameters aren't instantiation-dependent.
Douglas Gregorda0fb532009-11-11 19:31:23 +00005079 {
5080 // Set up a template instantiation context.
5081 LocalInstantiationScope Scope(*this);
5082 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00005083 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00005084 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00005085 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00005086 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005087
David Majnemer8b622692016-07-03 21:17:51 +00005088 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
Richard Smith5d331022018-03-08 01:07:33 +00005089 Params = SubstTemplateParams(Params, CurContext,
5090 MultiLevelTemplateArgumentList(TemplateArgs));
5091 if (!Params)
Douglas Gregorda0fb532009-11-11 19:31:23 +00005092 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00005093 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005094
Richard Smith11255ec2017-01-18 19:19:22 +00005095 // C++1z [temp.local]p1: (DR1004)
5096 // When [the injected-class-name] is used [...] as a template-argument for
5097 // a template template-parameter [...] it refers to the class template
5098 // itself.
5099 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
5100 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
5101 Arg.getTypeSourceInfo()->getTypeLoc());
5102 if (!ConvertedArg.getArgument().isNull())
5103 Arg = ConvertedArg;
5104 }
5105
Douglas Gregorda0fb532009-11-11 19:31:23 +00005106 switch (Arg.getArgument().getKind()) {
5107 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00005108 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005109
Douglas Gregorda0fb532009-11-11 19:31:23 +00005110 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005111 case TemplateArgument::TemplateExpansion:
Richard Smith5d331022018-03-08 01:07:33 +00005112 if (CheckTemplateTemplateArgument(Params, Arg))
Douglas Gregorda0fb532009-11-11 19:31:23 +00005113 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005114
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005115 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00005116 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005117
Douglas Gregorda0fb532009-11-11 19:31:23 +00005118 case TemplateArgument::Expression:
5119 case TemplateArgument::Type:
5120 // We have a template template parameter but the template
5121 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00005122 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005123 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00005124 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005125
Douglas Gregorda0fb532009-11-11 19:31:23 +00005126 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00005127 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00005128 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00005129 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00005130 case TemplateArgument::NullPtr:
5131 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005132
Douglas Gregorda0fb532009-11-11 19:31:23 +00005133 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005134 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00005135 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005136
Douglas Gregorda0fb532009-11-11 19:31:23 +00005137 return false;
5138}
5139
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005140/// Check whether the template parameter is a pack expansion, and if so,
Richard Smith1fde8ec2012-09-07 02:06:42 +00005141/// determine the number of parameters produced by that expansion. For instance:
5142///
5143/// \code
5144/// template<typename ...Ts> struct A {
5145/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
5146/// };
5147/// \endcode
5148///
5149/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
5150/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00005151static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00005152 if (NonTypeTemplateParmDecl *NTTP
5153 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5154 if (NTTP->isExpandedParameterPack())
5155 return NTTP->getNumExpansionTypes();
5156 }
5157
5158 if (TemplateTemplateParmDecl *TTP
5159 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
5160 if (TTP->isExpandedParameterPack())
5161 return TTP->getNumExpansionTemplateParameters();
5162 }
5163
David Blaikie7a30dc52013-02-21 01:47:18 +00005164 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00005165}
5166
Richard Smith35c1df52015-06-17 20:16:32 +00005167/// Diagnose a missing template argument.
5168template<typename TemplateParmDecl>
5169static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
5170 TemplateDecl *TD,
5171 const TemplateParmDecl *D,
5172 TemplateArgumentListInfo &Args) {
5173 // Dig out the most recent declaration of the template parameter; there may be
5174 // declarations of the template that are more recent than TD.
5175 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
5176 ->getTemplateParameters()
5177 ->getParam(D->getIndex()));
5178
5179 // If there's a default argument that's not visible, diagnose that we're
5180 // missing a module import.
5181 llvm::SmallVector<Module*, 8> Modules;
5182 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
5183 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
5184 D->getDefaultArgumentLoc(), Modules,
5185 Sema::MissingImportKind::DefaultArgument,
Richard Smith6739a102016-05-05 00:56:12 +00005186 /*Recover*/true);
Richard Smith35c1df52015-06-17 20:16:32 +00005187 return true;
5188 }
5189
5190 // FIXME: If there's a more recent default argument that *is* visible,
5191 // diagnose that it was declared too late.
5192
Richard Smith4a8f3512018-07-19 19:00:37 +00005193 TemplateParameterList *Params = TD->getTemplateParameters();
5194
5195 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5196 << /*not enough args*/0
5197 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD))
5198 << TD;
5199 S.Diag(TD->getLocation(), diag::note_template_decl_here)
5200 << Params->getSourceRange();
5201 return true;
Richard Smith35c1df52015-06-17 20:16:32 +00005202}
5203
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005204/// Check that the given template argument list is well-formed
Douglas Gregord32e0282009-02-09 23:23:08 +00005205/// for specializing the given template.
Richard Smith11255ec2017-01-18 19:19:22 +00005206bool Sema::CheckTemplateArgumentList(
5207 TemplateDecl *Template, SourceLocation TemplateLoc,
5208 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
5209 SmallVectorImpl<TemplateArgument> &Converted,
Saar Razfdf80e82019-12-06 01:30:21 +02005210 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5211
5212 if (ConstraintsNotSatisfied)
5213 *ConstraintsNotSatisfied = false;
5214
Richard Trieu15b66532015-01-24 02:48:32 +00005215 // Make a copy of the template arguments for processing. Only make the
5216 // changes at the end when successful in matching the arguments to the
5217 // template.
5218 TemplateArgumentListInfo NewArgs = TemplateArgs;
5219
Erich Keaneaf0795b2017-10-24 01:39:56 +00005220 // Make sure we get the template parameter list from the most
5221 // recentdeclaration, since that is the only one that has is guaranteed to
5222 // have all the default template argument information.
5223 TemplateParameterList *Params =
5224 cast<TemplateDecl>(Template->getMostRecentDecl())
5225 ->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00005226
Richard Trieu15b66532015-01-24 02:48:32 +00005227 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00005228
Mike Stump11289f42009-09-09 15:08:12 +00005229 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00005230 // [...] The type and form of each template-argument specified in
5231 // a template-id shall match the type and form specified for the
5232 // corresponding parameter declared by the template in its
5233 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00005234 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005235 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00005236 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00005237 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00005238 for (TemplateParameterList::iterator Param = Params->begin(),
5239 ParamEnd = Params->end();
5240 Param != ParamEnd; /* increment in loop */) {
5241 // If we have an expanded parameter pack, make sure we don't have too
5242 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00005243 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00005244 if (*Expansions == ArgumentPack.size()) {
5245 // We're done with this parameter pack. Pack up its arguments and add
5246 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00005247 Converted.push_back(
Benjamin Kramercce63472015-08-05 09:40:22 +00005248 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00005249 ArgumentPack.clear();
5250
Richard Smith1fde8ec2012-09-07 02:06:42 +00005251 // This argument is assigned to the next parameter.
5252 ++Param;
5253 continue;
5254 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5255 // Not enough arguments for this parameter pack.
5256 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
Richard Smith4a8f3512018-07-19 19:00:37 +00005257 << /*not enough args*/0
Richard Smith0c062b42017-01-14 02:19:59 +00005258 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
Richard Smith1fde8ec2012-09-07 02:06:42 +00005259 << Template;
5260 Diag(Template->getLocation(), diag::note_template_decl_here)
5261 << Params->getSourceRange();
5262 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00005263 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00005264 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005265
Richard Smith1fde8ec2012-09-07 02:06:42 +00005266 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00005267 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00005268 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005269 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00005270 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00005271 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005272
Richard Smith96d71c32014-11-12 23:38:38 +00005273 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00005274 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00005275 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
5276 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00005277 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00005278 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00005279 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00005280 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00005281 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00005282 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00005283 Diag((*Param)->getLocation(), diag::note_template_param_here);
5284 return true;
5285 }
5286
Richard Smith1fde8ec2012-09-07 02:06:42 +00005287 // We're now done with this argument.
5288 ++ArgIdx;
5289
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005290 if ((*Param)->isTemplateParameterPack()) {
5291 // The template parameter was a template parameter pack, so take the
5292 // deduced argument and place it on the argument pack. Note that we
5293 // stay on the same template parameter so that we can deduce more
5294 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00005295 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005296 } else {
5297 // Move to the next template parameter.
5298 ++Param;
5299 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00005300
Richard Smith96d71c32014-11-12 23:38:38 +00005301 // If we just saw a pack expansion into a non-pack, then directly convert
5302 // the remaining arguments, because we don't know what parameters they'll
5303 // match up with.
5304 if (PackExpansionIntoNonPack) {
5305 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00005306 // If we were part way through filling in an expanded parameter pack,
5307 // fall back to just producing individual arguments.
5308 Converted.insert(Converted.end(),
5309 ArgumentPack.begin(), ArgumentPack.end());
5310 ArgumentPack.clear();
5311 }
5312
5313 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00005314 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00005315 ++ArgIdx;
5316 }
5317
Richard Smith1fde8ec2012-09-07 02:06:42 +00005318 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00005319 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00005320
Douglas Gregor84d49a22009-11-11 21:54:23 +00005321 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005322 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005323
Douglas Gregor2f157c92011-06-03 02:59:40 +00005324 // If we're checking a partial template argument list, we're done.
5325 if (PartialTemplateArgs) {
5326 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
Benjamin Kramercce63472015-08-05 09:40:22 +00005327 Converted.push_back(
5328 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Richard Smith1fde8ec2012-09-07 02:06:42 +00005329 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00005330 }
5331
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005332 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005333 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00005334 if ((*Param)->isTemplateParameterPack()) {
5335 assert(!getExpandedPackSize(*Param) &&
5336 "Should have dealt with this already");
5337
5338 // A non-expanded parameter pack before the end of the parameter list
5339 // only occurs for an ill-formed template parameter list, unless we've
5340 // got a partial argument list for a function template, so just bail out.
5341 if (Param + 1 != ParamEnd)
5342 return true;
5343
Benjamin Kramercce63472015-08-05 09:40:22 +00005344 Converted.push_back(
5345 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00005346 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00005347
5348 ++Param;
5349 continue;
5350 }
5351
Douglas Gregor8e072612012-02-03 07:34:46 +00005352 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00005353 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005354
Douglas Gregor84d49a22009-11-11 21:54:23 +00005355 // Retrieve the default template argument from the template
5356 // parameter. For each kind of template parameter, we substitute the
5357 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005358 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00005359 // the default argument.
5360 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00005361 if (!hasVisibleDefaultArgument(TTP))
Richard Smith35c1df52015-06-17 20:16:32 +00005362 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
5363 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005364
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005365 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00005366 Template,
5367 TemplateLoc,
5368 RAngleLoc,
5369 TTP,
5370 Converted);
5371 if (!ArgType)
5372 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005373
Douglas Gregor84d49a22009-11-11 21:54:23 +00005374 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
5375 ArgType);
5376 } else if (NonTypeTemplateParmDecl *NTTP
5377 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00005378 if (!hasVisibleDefaultArgument(NTTP))
Richard Smith35c1df52015-06-17 20:16:32 +00005379 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
5380 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005381
John McCalldadc5752010-08-24 06:29:42 +00005382 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005383 TemplateLoc,
5384 RAngleLoc,
5385 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00005386 Converted);
5387 if (E.isInvalid())
5388 return true;
5389
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005390 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00005391 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
5392 } else {
5393 TemplateTemplateParmDecl *TempParm
5394 = cast<TemplateTemplateParmDecl>(*Param);
5395
Richard Smith95d83952015-06-10 20:36:34 +00005396 if (!hasVisibleDefaultArgument(TempParm))
Richard Smith35c1df52015-06-17 20:16:32 +00005397 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
5398 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005399
Douglas Gregordf846d12011-03-02 18:46:51 +00005400 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00005401 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005402 TemplateLoc,
5403 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00005404 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00005405 Converted,
5406 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005407 if (Name.isNull())
5408 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005409
Douglas Gregor9d802122011-03-02 17:09:35 +00005410 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
5411 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00005412 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005413
Douglas Gregor84d49a22009-11-11 21:54:23 +00005414 // Introduce an instantiation record that describes where we are using
Richard Smith54f18e82016-08-31 02:15:21 +00005415 // the default template argument. We're not actually instantiating a
5416 // template here, we just create this object to put a note into the
5417 // context stack.
Alp Tokerd4a72d52013-10-08 08:09:04 +00005418 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
5419 SourceRange(TemplateLoc, RAngleLoc));
5420 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00005421 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005422
Douglas Gregor84d49a22009-11-11 21:54:23 +00005423 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00005424 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00005425 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00005426 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005427
Richard Trieu15b66532015-01-24 02:48:32 +00005428 // Core issue 150 (assumed resolution): if this is a template template
5429 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00005430 // template definition.
5431 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00005432 NewArgs.addArgument(Arg);
5433
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005434 // Move to the next template parameter and argument.
5435 ++Param;
5436 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00005437 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005438
Richard Smith07f79912014-06-06 16:00:50 +00005439 // If we're performing a partial argument substitution, allow any trailing
5440 // pack expansions; they might be empty. This can happen even if
5441 // PartialTemplateArgs is false (the list of arguments is complete but
5442 // still dependent).
5443 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5444 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00005445 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
5446 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00005447 }
5448
Douglas Gregor8e072612012-02-03 07:34:46 +00005449 // If we have any leftover arguments, then there were too many arguments.
5450 // Complain and fail.
Richard Smith4a8f3512018-07-19 19:00:37 +00005451 if (ArgIdx < NumArgs) {
5452 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5453 << /*too many args*/1
5454 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5455 << Template
5456 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
5457 Diag(Template->getLocation(), diag::note_template_decl_here)
5458 << Params->getSourceRange();
5459 return true;
5460 }
Richard Trieu15b66532015-01-24 02:48:32 +00005461
5462 // No problems found with the new argument list, propagate changes back
5463 // to caller.
Richard Smith11255ec2017-01-18 19:19:22 +00005464 if (UpdateArgsWithConversions)
5465 TemplateArgs = std::move(NewArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005466
Saar Razfdf80e82019-12-06 01:30:21 +02005467 if (!PartialTemplateArgs &&
5468 EnsureTemplateArgumentListConstraints(
5469 Template, Converted, SourceRange(TemplateLoc,
5470 TemplateArgs.getRAngleLoc()))) {
5471 if (ConstraintsNotSatisfied)
5472 *ConstraintsNotSatisfied = true;
5473 return true;
5474 }
5475
Richard Smith1fde8ec2012-09-07 02:06:42 +00005476 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00005477}
5478
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005479namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005480 class UnnamedLocalNoLinkageFinder
5481 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005482 {
5483 Sema &S;
5484 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005485
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005486 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005487
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005488 public:
5489 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5490
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005491 bool Visit(QualType T) {
Daniel Jasper5cad6852017-01-02 22:55:45 +00005492 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005493 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005494
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005495#define TYPE(Class, Parent) \
5496 bool Visit##Class##Type(const Class##Type *);
5497#define ABSTRACT_TYPE(Class, Parent) \
5498 bool Visit##Class##Type(const Class##Type *) { return false; }
5499#define NON_CANONICAL_TYPE(Class, Parent) \
5500 bool Visit##Class##Type(const Class##Type *) { return false; }
John McCall36b12a82019-10-02 06:35:23 +00005501#include "clang/AST/TypeNodes.inc"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005502
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005503 bool VisitTagDecl(const TagDecl *Tag);
5504 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5505 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005506} // end anonymous namespace
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005507
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005508bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005509 return false;
5510}
5511
5512bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5513 return Visit(T->getElementType());
5514}
5515
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005516bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005517 return Visit(T->getPointeeType());
5518}
5519
5520bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005521 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005522 return Visit(T->getPointeeType());
5523}
5524
5525bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005526 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005527 return Visit(T->getPointeeType());
5528}
5529
5530bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005531 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005532 return Visit(T->getPointeeType());
5533}
5534
5535bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005536 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005537 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5538}
5539
5540bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005541 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005542 return Visit(T->getElementType());
5543}
5544
5545bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005546 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005547 return Visit(T->getElementType());
5548}
5549
5550bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005551 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005552 return Visit(T->getElementType());
5553}
5554
5555bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005556 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005557 return Visit(T->getElementType());
5558}
5559
5560bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005561 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005562 return Visit(T->getElementType());
5563}
5564
Andrew Gozillon572bbb02017-10-02 06:25:51 +00005565bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
5566 const DependentAddressSpaceType *T) {
5567 return Visit(T->getPointeeType());
5568}
5569
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005570bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5571 return Visit(T->getElementType());
5572}
5573
Erich Keanef702b022018-07-13 19:46:04 +00005574bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
5575 const DependentVectorType *T) {
5576 return Visit(T->getElementType());
5577}
5578
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005579bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5580 return Visit(T->getElementType());
5581}
5582
5583bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5584 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005585 for (const auto &A : T->param_types()) {
5586 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005587 return true;
5588 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005589
Alp Toker314cc812014-01-25 16:55:45 +00005590 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005591}
5592
5593bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5594 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00005595 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005596}
5597
5598bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5599 const UnresolvedUsingType*) {
5600 return false;
5601}
5602
5603bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5604 return false;
5605}
5606
5607bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5608 return Visit(T->getUnderlyingType());
5609}
5610
5611bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5612 return false;
5613}
5614
Alexis Hunte852b102011-05-24 22:41:36 +00005615bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5616 const UnaryTransformType*) {
5617 return false;
5618}
5619
Richard Smith30482bc2011-02-20 03:19:35 +00005620bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5621 return Visit(T->getDeducedType());
5622}
5623
Richard Smith600b5262017-01-26 20:40:47 +00005624bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5625 const DeducedTemplateSpecializationType *T) {
5626 return Visit(T->getDeducedType());
5627}
5628
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005629bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5630 return VisitTagDecl(T->getDecl());
5631}
5632
5633bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5634 return VisitTagDecl(T->getDecl());
5635}
5636
5637bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5638 const TemplateTypeParmType*) {
5639 return false;
5640}
5641
Douglas Gregorada4b792011-01-14 02:55:32 +00005642bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5643 const SubstTemplateTypeParmPackType *) {
5644 return false;
5645}
5646
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005647bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
5648 const TemplateSpecializationType*) {
5649 return false;
5650}
5651
5652bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
5653 const InjectedClassNameType* T) {
5654 return VisitTagDecl(T->getDecl());
5655}
5656
5657bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
5658 const DependentNameType* T) {
5659 return VisitNestedNameSpecifier(T->getQualifier());
5660}
5661
5662bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
5663 const DependentTemplateSpecializationType* T) {
5664 return VisitNestedNameSpecifier(T->getQualifier());
5665}
5666
Douglas Gregord2fa7662010-12-20 02:24:11 +00005667bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
5668 const PackExpansionType* T) {
5669 return Visit(T->getPattern());
5670}
5671
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005672bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5673 return false;
5674}
5675
5676bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
5677 const ObjCInterfaceType *) {
5678 return false;
5679}
5680
5681bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
5682 const ObjCObjectPointerType *) {
5683 return false;
5684}
5685
Eli Friedman0dfb8892011-10-06 23:00:33 +00005686bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
5687 return Visit(T->getValueType());
5688}
5689
Xiuli Pan9c14e282016-01-09 12:53:17 +00005690bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
5691 return false;
5692}
5693
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005694bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
5695 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005696 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005697 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00005698 diag::warn_cxx98_compat_template_arg_local_type :
5699 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005700 << S.Context.getTypeDeclType(Tag) << SR;
5701 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005702 }
5703
John McCall5ea95772013-03-09 00:54:27 +00005704 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005705 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005706 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00005707 diag::warn_cxx98_compat_template_arg_unnamed_type :
5708 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005709 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
5710 return true;
5711 }
5712
5713 return false;
5714}
5715
5716bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5717 NestedNameSpecifier *NNS) {
5718 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5719 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005720
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005721 switch (NNS->getKind()) {
5722 case NestedNameSpecifier::Identifier:
5723 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005724 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005725 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00005726 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005727 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005728
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005729 case NestedNameSpecifier::TypeSpec:
5730 case NestedNameSpecifier::TypeSpecWithTemplate:
5731 return Visit(QualType(NNS->getAsType(), 0));
5732 }
David Blaikie8a40f702012-01-17 06:56:22 +00005733 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005734}
5735
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005736/// Check a template argument against its corresponding
Douglas Gregord32e0282009-02-09 23:23:08 +00005737/// template type parameter.
5738///
5739/// This routine implements the semantics of C++ [temp.arg.type]. It
5740/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005741bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00005742 TypeSourceInfo *ArgInfo) {
5743 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00005744 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00005745 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00005746
5747 if (Arg->isVariablyModifiedType()) {
5748 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005749 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005750 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00005751 }
5752
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005753 // C++03 [temp.arg.type]p2:
5754 // A local type, a type with no linkage, an unnamed type or a type
5755 // compounded from any of these types shall not be used as a
5756 // template-argument for a template type-parameter.
5757 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00005758 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005759 // a warning.
Daniel Jasper5cad6852017-01-02 22:55:45 +00005760 if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005761 UnnamedLocalNoLinkageFinder Finder(*this, SR);
5762 (void)Finder.Visit(Context.getCanonicalType(Arg));
5763 }
5764
Douglas Gregord32e0282009-02-09 23:23:08 +00005765 return false;
5766}
5767
Douglas Gregor20fdef32012-04-10 17:08:25 +00005768enum NullPointerValueKind {
5769 NPV_NotNullPointer,
5770 NPV_NullPointer,
5771 NPV_Error
5772};
5773
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005774/// Determine whether the given template argument is a null pointer
Douglas Gregor20fdef32012-04-10 17:08:25 +00005775/// value of the appropriate type.
5776static NullPointerValueKind
5777isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
Reid Klecknercd016d82017-07-07 22:04:29 +00005778 QualType ParamType, Expr *Arg,
5779 Decl *Entity = nullptr) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00005780 if (Arg->isValueDependent() || Arg->isTypeDependent())
5781 return NPV_NotNullPointer;
David Majnemer69c3ddc2015-09-11 20:18:09 +00005782
Reid Klecknercd016d82017-07-07 22:04:29 +00005783 // dllimport'd entities aren't constant but are available inside of template
5784 // arguments.
5785 if (Entity && Entity->hasAttr<DLLImportAttr>())
5786 return NPV_NotNullPointer;
5787
Richard Smithdb0ac552015-12-18 22:40:25 +00005788 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
David Majnemerb54368c2015-09-11 20:55:29 +00005789 llvm_unreachable(
5790 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
David Majnemer69c3ddc2015-09-11 20:18:09 +00005791
David Majnemer5c734ad2014-08-14 00:49:23 +00005792 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00005793 return NPV_NotNullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005794
Douglas Gregor20fdef32012-04-10 17:08:25 +00005795 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00005796 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
5797 if (ArgRV.isInvalid())
5798 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005799 Arg = ArgRV.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005800
Douglas Gregor20fdef32012-04-10 17:08:25 +00005801 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005802 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00005803 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005804 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00005805 EvalResult.HasSideEffects) {
5806 SourceLocation DiagLoc = Arg->getExprLoc();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005807
Douglas Gregor350880c2012-04-10 19:03:30 +00005808 // If our only note is the usual "invalid subexpression" note, just point
5809 // the caret at its location rather than producing an essentially
5810 // redundant note.
5811 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5812 diag::note_invalid_subexpr_in_const_expr) {
5813 DiagLoc = Notes[0].first;
5814 Notes.clear();
5815 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005816
Douglas Gregor350880c2012-04-10 19:03:30 +00005817 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5818 << Arg->getType() << Arg->getSourceRange();
5819 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5820 S.Diag(Notes[I].first, Notes[I].second);
Simon Pilgrim6905d222016-12-30 22:55:33 +00005821
Douglas Gregor350880c2012-04-10 19:03:30 +00005822 S.Diag(Param->getLocation(), diag::note_template_param_here);
5823 return NPV_Error;
5824 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005825
Douglas Gregor20fdef32012-04-10 17:08:25 +00005826 // C++11 [temp.arg.nontype]p1:
5827 // - an address constant expression of type std::nullptr_t
5828 if (Arg->getType()->isNullPtrType())
5829 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005830
Douglas Gregor20fdef32012-04-10 17:08:25 +00005831 // - a constant expression that evaluates to a null pointer value (4.10); or
5832 // - a constant expression that evaluates to a null member pointer value
5833 // (4.11); or
5834 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
5835 (EvalResult.Val.isMemberPointer() &&
5836 !EvalResult.Val.getMemberPointerDecl())) {
5837 // If our expression has an appropriate type, we've succeeded.
5838 bool ObjCLifetimeConversion;
5839 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5840 S.IsQualificationConversion(Arg->getType(), ParamType, false,
5841 ObjCLifetimeConversion))
5842 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005843
Douglas Gregor20fdef32012-04-10 17:08:25 +00005844 // The types didn't match, but we know we got a null pointer; complain,
5845 // then recover as if the types were correct.
5846 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
5847 << Arg->getType() << ParamType << Arg->getSourceRange();
5848 S.Diag(Param->getLocation(), diag::note_template_param_here);
5849 return NPV_NullPointer;
5850 }
5851
5852 // If we don't have a null pointer value, but we do have a NULL pointer
5853 // constant, suggest a cast to the appropriate type.
5854 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
5855 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
5856 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005857 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005858 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getEndLoc()),
Alp Tokerb6cc5922014-05-03 03:45:55 +00005859 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00005860 S.Diag(Param->getLocation(), diag::note_template_param_here);
5861 return NPV_NullPointer;
5862 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005863
Douglas Gregor20fdef32012-04-10 17:08:25 +00005864 // FIXME: If we ever want to support general, address-constant expressions
5865 // as non-type template arguments, we should return the ExprResult here to
5866 // be interpreted by the caller.
5867 return NPV_NotNullPointer;
5868}
5869
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005870/// Checks whether the given template argument is compatible with its
David Majnemer61c39a12013-08-23 05:39:39 +00005871/// template parameter.
5872static bool CheckTemplateArgumentIsCompatibleWithParameter(
5873 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
5874 Expr *Arg, QualType ArgType) {
5875 bool ObjCLifetimeConversion;
5876 if (ParamType->isPointerType() &&
Simon Pilgrimf4cc3b32019-10-05 13:21:08 +00005877 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
David Majnemer61c39a12013-08-23 05:39:39 +00005878 S.IsQualificationConversion(ArgType, ParamType, false,
5879 ObjCLifetimeConversion)) {
5880 // For pointer-to-object types, qualification conversions are
5881 // permitted.
5882 } else {
5883 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
5884 if (!ParamRef->getPointeeType()->isFunctionType()) {
5885 // C++ [temp.arg.nontype]p5b3:
5886 // For a non-type template-parameter of type reference to
5887 // object, no conversions apply. The type referred to by the
5888 // reference may be more cv-qualified than the (otherwise
5889 // identical) type of the template- argument. The
5890 // template-parameter is bound directly to the
5891 // template-argument, which shall be an lvalue.
5892
5893 // FIXME: Other qualifiers?
5894 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
5895 unsigned ArgQuals = ArgType.getCVRQualifiers();
5896
5897 if ((ParamQuals | ArgQuals) != ParamQuals) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005898 S.Diag(Arg->getBeginLoc(),
David Majnemer61c39a12013-08-23 05:39:39 +00005899 diag::err_template_arg_ref_bind_ignores_quals)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005900 << ParamType << Arg->getType() << Arg->getSourceRange();
David Majnemer61c39a12013-08-23 05:39:39 +00005901 S.Diag(Param->getLocation(), diag::note_template_param_here);
5902 return true;
5903 }
5904 }
5905 }
5906
5907 // At this point, the template argument refers to an object or
5908 // function with external linkage. We now need to check whether the
5909 // argument and parameter types are compatible.
5910 if (!S.Context.hasSameUnqualifiedType(ArgType,
5911 ParamType.getNonReferenceType())) {
5912 // We can't perform this conversion or binding.
5913 if (ParamType->isReferenceType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005914 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
5915 << ParamType << ArgIn->getType() << Arg->getSourceRange();
David Majnemer61c39a12013-08-23 05:39:39 +00005916 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005917 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
5918 << ArgIn->getType() << ParamType << Arg->getSourceRange();
David Majnemer61c39a12013-08-23 05:39:39 +00005919 S.Diag(Param->getLocation(), diag::note_template_param_here);
5920 return true;
5921 }
5922 }
5923
5924 return false;
5925}
5926
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005927/// Checks whether the given template argument is the address
Douglas Gregorccb07762009-02-11 19:52:55 +00005928/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005929static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00005930CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
5931 NonTypeTemplateParmDecl *Param,
5932 QualType ParamType,
5933 Expr *ArgIn,
5934 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005935 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005936 Expr *Arg = ArgIn;
5937 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00005938
Douglas Gregorb242683d2010-04-01 18:32:35 +00005939 bool AddressTaken = false;
5940 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00005941 if (S.getLangOpts().MicrosoftExt) {
5942 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
5943 // dereference and address-of operators.
5944 Arg = Arg->IgnoreParenCasts();
5945
5946 bool ExtWarnMSTemplateArg = false;
5947 UnaryOperatorKind FirstOpKind;
5948 SourceLocation FirstOpLoc;
5949 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5950 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
5951 if (UnOpKind == UO_Deref)
5952 ExtWarnMSTemplateArg = true;
5953 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
5954 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
5955 if (!AddrOpLoc.isValid()) {
5956 FirstOpKind = UnOpKind;
5957 FirstOpLoc = UnOp->getOperatorLoc();
5958 }
5959 } else
5960 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005961 }
David Majnemer61c39a12013-08-23 05:39:39 +00005962 if (FirstOpLoc.isValid()) {
5963 if (ExtWarnMSTemplateArg)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005964 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
5965 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00005966
David Majnemer61c39a12013-08-23 05:39:39 +00005967 if (FirstOpKind == UO_AddrOf)
5968 AddressTaken = true;
5969 else if (Arg->getType()->isPointerType()) {
5970 // We cannot let pointers get dereferenced here, that is obviously not a
5971 // constant expression.
5972 assert(FirstOpKind == UO_Deref);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005973 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
5974 << Arg->getSourceRange();
David Majnemer61c39a12013-08-23 05:39:39 +00005975 }
5976 }
5977 } else {
5978 // See through any implicit casts we added to fix the type.
5979 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00005980
David Majnemer61c39a12013-08-23 05:39:39 +00005981 // C++ [temp.arg.nontype]p1:
5982 //
5983 // A template-argument for a non-type, non-template
5984 // template-parameter shall be one of: [...]
5985 //
5986 // -- the address of an object or function with external
5987 // linkage, including function templates and function
5988 // template-ids but excluding non-static class members,
5989 // expressed as & id-expression where the & is optional if
5990 // the name refers to a function or array, or if the
5991 // corresponding template-parameter is a reference; or
5992
5993 // In C++98/03 mode, give an extension warning on any extra parentheses.
5994 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5995 bool ExtraParens = false;
5996 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5997 if (!Invalid && !ExtraParens) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005998 S.Diag(Arg->getBeginLoc(),
David Majnemer61c39a12013-08-23 05:39:39 +00005999 S.getLangOpts().CPlusPlus11
6000 ? diag::warn_cxx98_compat_template_arg_extra_parens
6001 : diag::ext_template_arg_extra_parens)
6002 << Arg->getSourceRange();
6003 ExtraParens = true;
6004 }
6005
6006 Arg = Parens->getSubExpr();
6007 }
6008
6009 while (SubstNonTypeTemplateParmExpr *subst =
6010 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6011 Arg = subst->getReplacement()->IgnoreImpCasts();
6012
6013 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6014 if (UnOp->getOpcode() == UO_AddrOf) {
6015 Arg = UnOp->getSubExpr();
6016 AddressTaken = true;
6017 AddrOpLoc = UnOp->getOperatorLoc();
6018 }
6019 }
6020
6021 while (SubstNonTypeTemplateParmExpr *subst =
6022 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6023 Arg = subst->getReplacement()->IgnoreImpCasts();
6024 }
John McCall7c454bb2011-07-15 05:09:51 +00006025
David Majnemer07910d62014-06-26 07:48:46 +00006026 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
6027 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6028
6029 // If our parameter has pointer type, check for a null template value.
6030 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
Reid Klecknercd016d82017-07-07 22:04:29 +00006031 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6032 Entity)) {
David Majnemer07910d62014-06-26 07:48:46 +00006033 case NPV_NullPointer:
6034 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00006035 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
6036 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00006037 return false;
6038
6039 case NPV_Error:
6040 return true;
6041
6042 case NPV_NotNullPointer:
6043 break;
6044 }
6045 }
6046
Chandler Carruth724a8a12010-01-31 10:01:20 +00006047 // Stop checking the precise nature of the argument if it is value dependent,
6048 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00006049 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00006050 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00006051 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006052 }
David Majnemer61c39a12013-08-23 05:39:39 +00006053
6054 if (isa<CXXUuidofExpr>(Arg)) {
6055 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
6056 ArgIn, Arg, ArgType))
6057 return true;
6058
6059 Converted = TemplateArgument(ArgIn);
6060 return false;
6061 }
6062
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006063 if (!DRE) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006064 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6065 << Arg->getSourceRange();
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006066 S.Diag(Param->getLocation(), diag::note_template_param_here);
6067 return true;
6068 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00006069
Douglas Gregorccb07762009-02-11 19:52:55 +00006070 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00006071 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006072 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6073 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006074 S.Diag(Param->getLocation(), diag::note_template_param_here);
6075 return true;
6076 }
Douglas Gregorccb07762009-02-11 19:52:55 +00006077
6078 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00006079 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006080 if (!Method->isStatic()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006081 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6082 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006083 S.Diag(Param->getLocation(), diag::note_template_param_here);
6084 return true;
6085 }
Richard Smith9380e0e2012-04-04 21:11:30 +00006086 }
Mike Stump11289f42009-09-09 15:08:12 +00006087
Richard Smith9380e0e2012-04-04 21:11:30 +00006088 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6089 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00006090
Richard Smith9380e0e2012-04-04 21:11:30 +00006091 // A non-type template argument must refer to an object or function.
6092 if (!Func && !Var) {
6093 // We found something, but we don't know specifically what it is.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006094 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6095 << Arg->getSourceRange();
Richard Smith9380e0e2012-04-04 21:11:30 +00006096 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
6097 return true;
6098 }
Douglas Gregorccb07762009-02-11 19:52:55 +00006099
Richard Smith9380e0e2012-04-04 21:11:30 +00006100 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00006101 if (Entity->getFormalLinkage() == InternalLinkage) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006102 S.Diag(Arg->getBeginLoc(),
6103 S.getLangOpts().CPlusPlus11
6104 ? diag::warn_cxx98_compat_template_arg_object_internal
6105 : diag::ext_template_arg_object_internal)
6106 << !Func << Entity << Arg->getSourceRange();
Richard Smith9380e0e2012-04-04 21:11:30 +00006107 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6108 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00006109 } else if (!Entity->hasLinkage()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006110 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6111 << !Func << Entity << Arg->getSourceRange();
Richard Smith9380e0e2012-04-04 21:11:30 +00006112 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6113 << !Func;
6114 return true;
6115 }
6116
6117 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006118 // If the template parameter has pointer type, the function decays.
6119 if (ParamType->isPointerType() && !AddressTaken)
6120 ArgType = S.Context.getPointerType(Func->getType());
6121 else if (AddressTaken && ParamType->isReferenceType()) {
6122 // If we originally had an address-of operator, but the
6123 // parameter has reference type, complain and (if things look
6124 // like they will work) drop the address-of operator.
6125 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
6126 ParamType.getNonReferenceType())) {
6127 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6128 << ParamType;
6129 S.Diag(Param->getLocation(), diag::note_template_param_here);
6130 return true;
6131 }
6132
6133 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6134 << ParamType
6135 << FixItHint::CreateRemoval(AddrOpLoc);
6136 S.Diag(Param->getLocation(), diag::note_template_param_here);
6137
6138 ArgType = Func->getType();
6139 }
Richard Smith9380e0e2012-04-04 21:11:30 +00006140 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006141 // A value of reference type is not an object.
6142 if (Var->getType()->isReferenceType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006143 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6144 << Var->getType() << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006145 S.Diag(Param->getLocation(), diag::note_template_param_here);
6146 return true;
6147 }
6148
Richard Smith9380e0e2012-04-04 21:11:30 +00006149 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00006150 if (Var->getTLSKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006151 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6152 << Arg->getSourceRange();
Richard Smith9380e0e2012-04-04 21:11:30 +00006153 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6154 return true;
6155 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00006156
6157 // If the template parameter has pointer type, we must have taken
6158 // the address of this object.
6159 if (ParamType->isReferenceType()) {
6160 if (AddressTaken) {
6161 // If we originally had an address-of operator, but the
6162 // parameter has reference type, complain and (if things look
6163 // like they will work) drop the address-of operator.
6164 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
6165 ParamType.getNonReferenceType())) {
6166 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6167 << ParamType;
6168 S.Diag(Param->getLocation(), diag::note_template_param_here);
6169 return true;
6170 }
6171
6172 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6173 << ParamType
6174 << FixItHint::CreateRemoval(AddrOpLoc);
6175 S.Diag(Param->getLocation(), diag::note_template_param_here);
6176
6177 ArgType = Var->getType();
6178 }
6179 } else if (!AddressTaken && ParamType->isPointerType()) {
6180 if (Var->getType()->isArrayType()) {
6181 // Array-to-pointer decay.
6182 ArgType = S.Context.getArrayDecayedType(Var->getType());
6183 } else {
6184 // If the template parameter has pointer type but the address of
6185 // this object was not taken, complain and (possibly) recover by
6186 // taking the address of the entity.
6187 ArgType = S.Context.getPointerType(Var->getType());
6188 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006189 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6190 << ParamType;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006191 S.Diag(Param->getLocation(), diag::note_template_param_here);
6192 return true;
6193 }
6194
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006195 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6196 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
Douglas Gregorb242683d2010-04-01 18:32:35 +00006197
6198 S.Diag(Param->getLocation(), diag::note_template_param_here);
6199 }
6200 }
Douglas Gregorccb07762009-02-11 19:52:55 +00006201 }
Mike Stump11289f42009-09-09 15:08:12 +00006202
David Majnemer61c39a12013-08-23 05:39:39 +00006203 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6204 Arg, ArgType))
6205 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006206
6207 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00006208 Converted =
6209 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006210 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00006211 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00006212}
6213
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006214/// Checks whether the given template argument is a pointer to
Douglas Gregorccb07762009-02-11 19:52:55 +00006215/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00006216static bool CheckTemplateArgumentPointerToMember(Sema &S,
6217 NonTypeTemplateParmDecl *Param,
6218 QualType ParamType,
6219 Expr *&ResultArg,
6220 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00006221 bool Invalid = false;
6222
Douglas Gregor20fdef32012-04-10 17:08:25 +00006223 Expr *Arg = ResultArg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006224 bool ObjCLifetimeConversion;
Douglas Gregorccb07762009-02-11 19:52:55 +00006225
6226 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00006227 //
Douglas Gregorccb07762009-02-11 19:52:55 +00006228 // A template-argument for a non-type, non-template
6229 // template-parameter shall be one of: [...]
6230 //
6231 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00006232 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00006233
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00006234 // In C++98/03 mode, give an extension warning on any extra parentheses.
6235 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6236 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00006237 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00006238 if (!Invalid && !ExtraParens) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006239 S.Diag(Arg->getBeginLoc(),
6240 S.getLangOpts().CPlusPlus11
6241 ? diag::warn_cxx98_compat_template_arg_extra_parens
6242 : diag::ext_template_arg_extra_parens)
6243 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00006244 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00006245 }
6246
6247 Arg = Parens->getSubExpr();
6248 }
6249
John McCall7c454bb2011-07-15 05:09:51 +00006250 while (SubstNonTypeTemplateParmExpr *subst =
6251 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6252 Arg = subst->getReplacement()->IgnoreImpCasts();
6253
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006254 // A pointer-to-member constant written &Class::member.
6255 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00006256 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00006257 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
6258 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00006259 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00006260 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006261 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006262 // A constant of pointer-to-member type.
6263 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00006264 ValueDecl *VD = DRE->getDecl();
6265 if (VD->getType()->isMemberPointerType()) {
6266 if (isa<NonTypeTemplateParmDecl>(VD)) {
6267 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6268 Converted = TemplateArgument(Arg);
6269 } else {
6270 VD = cast<ValueDecl>(VD->getCanonicalDecl());
6271 Converted = TemplateArgument(VD, ParamType);
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006272 }
George Burgess IV00f70bd2018-03-01 05:43:23 +00006273 return Invalid;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006274 }
6275 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006276
Craig Topperc3ec1492014-05-26 06:22:03 +00006277 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006278 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006279
Reid Klecknercd016d82017-07-07 22:04:29 +00006280 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6281
6282 // Check for a null pointer value.
6283 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
6284 Entity)) {
6285 case NPV_Error:
6286 return true;
6287 case NPV_NullPointer:
6288 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6289 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
6290 /*isNullPtr*/true);
6291 return false;
6292 case NPV_NotNullPointer:
6293 break;
6294 }
6295
6296 if (S.IsQualificationConversion(ResultArg->getType(),
6297 ParamType.getNonReferenceType(), false,
6298 ObjCLifetimeConversion)) {
6299 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
6300 ResultArg->getValueKind())
6301 .get();
6302 } else if (!S.Context.hasSameUnqualifiedType(
6303 ResultArg->getType(), ParamType.getNonReferenceType())) {
6304 // We can't perform this conversion.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006305 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
Reid Klecknercd016d82017-07-07 22:04:29 +00006306 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
6307 S.Diag(Param->getLocation(), diag::note_template_param_here);
6308 return true;
6309 }
6310
Douglas Gregorccb07762009-02-11 19:52:55 +00006311 if (!DRE)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006312 return S.Diag(Arg->getBeginLoc(),
Douglas Gregor20fdef32012-04-10 17:08:25 +00006313 diag::err_template_arg_not_pointer_to_member_form)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006314 << Arg->getSourceRange();
Douglas Gregorccb07762009-02-11 19:52:55 +00006315
David Majnemer3ac84e62013-10-22 21:56:38 +00006316 if (isa<FieldDecl>(DRE->getDecl()) ||
6317 isa<IndirectFieldDecl>(DRE->getDecl()) ||
6318 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00006319 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00006320 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00006321 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
6322 "Only non-static member pointers can make it here");
6323
6324 // Okay: this is the address of a non-static member, and therefore
6325 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00006326 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00006327 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00006328 } else {
6329 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00006330 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00006331 }
Douglas Gregorccb07762009-02-11 19:52:55 +00006332 return Invalid;
6333 }
6334
6335 // We found something else, but we don't know specifically what it is.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006336 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
6337 << Arg->getSourceRange();
Douglas Gregor20fdef32012-04-10 17:08:25 +00006338 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00006339 return true;
6340}
6341
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006342/// Check a template argument against its corresponding
Douglas Gregord32e0282009-02-09 23:23:08 +00006343/// non-type template parameter.
6344///
Douglas Gregor463421d2009-03-03 04:44:36 +00006345/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00006346/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00006347/// returns the converted template argument. \p ParamType is the
6348/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00006349ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00006350 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00006351 TemplateArgument &Converted,
6352 CheckTemplateArgumentKind CTAK) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006353 SourceLocation StartLoc = Arg->getBeginLoc();
Douglas Gregorc40290e2009-03-09 23:48:35 +00006354
Richard Smith5f274382016-09-28 23:55:27 +00006355 // If the parameter type somehow involves auto, deduce the type now.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00006356 if (getLangOpts().CPlusPlus17 && ParamType->isUndeducedType()) {
Richard Smith4ae5ec82017-02-22 20:01:55 +00006357 // During template argument deduction, we allow 'decltype(auto)' to
6358 // match an arbitrary dependent argument.
6359 // FIXME: The language rules don't say what happens in this case.
6360 // FIXME: We get an opaque dependent type out of decltype(auto) if the
6361 // expression is merely instantiation-dependent; is this enough?
6362 if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
6363 auto *AT = dyn_cast<AutoType>(ParamType);
6364 if (AT && AT->isDecltypeAuto()) {
6365 Converted = TemplateArgument(Arg);
6366 return Arg;
6367 }
6368 }
6369
Richard Smith87d263e2016-12-25 08:05:23 +00006370 // When checking a deduced template argument, deduce from its type even if
6371 // the type is dependent, in order to check the types of non-type template
6372 // arguments line up properly in partial ordering.
Richard Smith07ed9cf2019-06-20 19:49:13 +00006373 Optional<unsigned> Depth = Param->getDepth() + 1;
Richard Smith9771f502019-06-24 05:53:11 +00006374 Expr *DeductionArg = Arg;
6375 if (auto *PE = dyn_cast<PackExpansionExpr>(DeductionArg))
6376 DeductionArg = PE->getPattern();
Richard Smith5f274382016-09-28 23:55:27 +00006377 if (DeduceAutoType(
6378 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
Richard Smith9771f502019-06-24 05:53:11 +00006379 DeductionArg, ParamType, Depth) == DAR_Failed) {
Richard Smith5f274382016-09-28 23:55:27 +00006380 Diag(Arg->getExprLoc(),
6381 diag::err_non_type_template_parm_type_deduction_failure)
6382 << Param->getDeclName() << Param->getType() << Arg->getType()
6383 << Arg->getSourceRange();
6384 Diag(Param->getLocation(), diag::note_template_param_here);
6385 return ExprError();
6386 }
6387 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
6388 // an error. The error message normally references the parameter
6389 // declaration, but here we'll pass the argument location because that's
6390 // where the parameter type is deduced.
6391 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
6392 if (ParamType.isNull()) {
6393 Diag(Param->getLocation(), diag::note_template_param_here);
6394 return ExprError();
6395 }
6396 }
6397
Richard Smithd663fdd2014-12-17 20:42:37 +00006398 // We should have already dropped all cv-qualifiers by now.
6399 assert(!ParamType.hasQualifiers() &&
6400 "non-type template parameter type cannot be qualified");
6401
6402 if (CTAK == CTAK_Deduced &&
Richard Smithd92eddf2016-12-27 06:14:37 +00006403 !Context.hasSameType(ParamType.getNonLValueExprType(Context),
Richard Smith0e617ec2016-12-27 07:56:27 +00006404 Arg->getType())) {
Richard Smith957fbf12017-01-17 02:14:37 +00006405 // FIXME: If either type is dependent, we skip the check. This isn't
6406 // correct, since during deduction we're supposed to have replaced each
6407 // template parameter with some unique (non-dependent) placeholder.
6408 // FIXME: If the argument type contains 'auto', we carry on and fail the
6409 // type check in order to force specific types to be more specialized than
6410 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
6411 // work.
6412 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
6413 !Arg->getType()->getContainedAutoType()) {
6414 Converted = TemplateArgument(Arg);
6415 return Arg;
6416 }
6417 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
6418 // we should actually be checking the type of the template argument in P,
6419 // not the type of the template argument deduced from A, against the
6420 // template parameter type.
Richard Smithd663fdd2014-12-17 20:42:37 +00006421 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
Richard Smith0e617ec2016-12-27 07:56:27 +00006422 << Arg->getType()
Richard Smithd663fdd2014-12-17 20:42:37 +00006423 << ParamType.getUnqualifiedType();
6424 Diag(Param->getLocation(), diag::note_template_param_here);
6425 return ExprError();
6426 }
6427
Richard Smith87d263e2016-12-25 08:05:23 +00006428 // If either the parameter has a dependent type or the argument is
Richard Smith40c3d6e32019-09-19 22:00:16 +00006429 // type-dependent, there's nothing we can check now. The argument only
6430 // contains an unexpanded pack during partial ordering, and there's
6431 // nothing more we can check in that case.
6432 if (ParamType->isDependentType() || Arg->isTypeDependent() ||
6433 Arg->containsUnexpandedParameterPack()) {
Richard Smith07ed9cf2019-06-20 19:49:13 +00006434 // Force the argument to the type of the parameter to maintain invariants.
6435 auto *PE = dyn_cast<PackExpansionExpr>(Arg);
6436 if (PE)
6437 Arg = PE->getPattern();
6438 ExprResult E = ImpCastExprToType(
6439 Arg, ParamType.getNonLValueExprType(Context), CK_Dependent,
6440 ParamType->isLValueReferenceType() ? VK_LValue :
6441 ParamType->isRValueReferenceType() ? VK_XValue : VK_RValue);
6442 if (E.isInvalid())
6443 return ExprError();
6444 if (PE) {
6445 // Recreate a pack expansion if we unwrapped one.
6446 E = new (Context)
6447 PackExpansionExpr(E.get()->getType(), E.get(), PE->getEllipsisLoc(),
6448 PE->getNumExpansions());
6449 }
6450 Converted = TemplateArgument(E.get());
6451 return E;
Richard Smith87d263e2016-12-25 08:05:23 +00006452 }
6453
Richard Smithe5945872017-01-06 22:52:53 +00006454 // The initialization of the parameter from the argument is
6455 // a constant-evaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006456 EnterExpressionEvaluationContext ConstantEvaluated(
6457 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Richard Smithe5945872017-01-06 22:52:53 +00006458
Aaron Ballmanc351fba2017-12-04 20:27:34 +00006459 if (getLangOpts().CPlusPlus17) {
6460 // C++17 [temp.arg.nontype]p1:
Richard Smith410cc892014-11-26 03:26:53 +00006461 // A template-argument for a non-type template parameter shall be
6462 // a converted constant expression of the type of the template-parameter.
6463 APValue Value;
6464 ExprResult ArgResult = CheckConvertedConstantExpression(
6465 Arg, ParamType, Value, CCEK_TemplateArg);
6466 if (ArgResult.isInvalid())
6467 return ExprError();
6468
Richard Smith52e624f2016-12-21 21:42:57 +00006469 // For a value-dependent argument, CheckConvertedConstantExpression is
6470 // permitted (and expected) to be unable to determine a value.
6471 if (ArgResult.get()->isValueDependent()) {
Richard Smith01bfa682016-12-27 02:02:09 +00006472 Converted = TemplateArgument(ArgResult.get());
6473 return ArgResult;
Richard Smith52e624f2016-12-21 21:42:57 +00006474 }
6475
Richard Smithd663fdd2014-12-17 20:42:37 +00006476 QualType CanonParamType = Context.getCanonicalType(ParamType);
6477
Richard Smith410cc892014-11-26 03:26:53 +00006478 // Convert the APValue to a TemplateArgument.
6479 switch (Value.getKind()) {
Richard Smithe637cbe2019-05-21 23:15:18 +00006480 case APValue::None:
Richard Smith410cc892014-11-26 03:26:53 +00006481 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00006482 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00006483 break;
Richard Smithe637cbe2019-05-21 23:15:18 +00006484 case APValue::Indeterminate:
6485 llvm_unreachable("result of constant evaluation should be initialized");
6486 break;
Richard Smith410cc892014-11-26 03:26:53 +00006487 case APValue::Int:
6488 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00006489 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00006490 break;
6491 case APValue::MemberPointer: {
6492 assert(ParamType->isMemberPointerType());
6493
6494 // FIXME: We need TemplateArgument representation and mangling for these.
6495 if (!Value.getMemberPointerPath().empty()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006496 Diag(Arg->getBeginLoc(),
Richard Smith410cc892014-11-26 03:26:53 +00006497 diag::err_template_arg_member_ptr_base_derived_not_supported)
6498 << Value.getMemberPointerDecl() << ParamType
6499 << Arg->getSourceRange();
6500 return ExprError();
6501 }
6502
6503 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00006504 Converted = VD ? TemplateArgument(VD, CanonParamType)
6505 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00006506 break;
6507 }
6508 case APValue::LValue: {
6509 // For a non-type template-parameter of pointer or reference type,
6510 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00006511 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
6512 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00006513 // -- a temporary object
6514 // -- a string literal
6515 // -- the result of a typeid expression, or
Eric Christopher0d2c56a2017-03-31 01:45:39 +00006516 // -- a predefined __func__ variable
Richard Smithee0ce3022019-05-17 07:06:46 +00006517 APValue::LValueBase Base = Value.getLValueBase();
6518 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
6519 if (Base && !VD) {
6520 auto *E = Base.dyn_cast<const Expr *>();
6521 if (E && isa<CXXUuidofExpr>(E)) {
Bill Wendlingff573072019-01-27 07:24:03 +00006522 Converted = TemplateArgument(ArgResult.get()->IgnoreImpCasts());
Richard Smith410cc892014-11-26 03:26:53 +00006523 break;
6524 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006525 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6526 << Arg->getSourceRange();
Richard Smith410cc892014-11-26 03:26:53 +00006527 return ExprError();
6528 }
Richard Smith410cc892014-11-26 03:26:53 +00006529 // -- a subobject
6530 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
6531 VD && VD->getType()->isArrayType() &&
Richard Smith5b5e27a2019-05-10 20:05:31 +00006532 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
Richard Smith410cc892014-11-26 03:26:53 +00006533 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
6534 // Per defect report (no number yet):
6535 // ... other than a pointer to the first element of a complete array
6536 // object.
6537 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
6538 Value.isLValueOnePastTheEnd()) {
6539 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
6540 << Value.getAsString(Context, ParamType);
6541 return ExprError();
6542 }
Richard Smithd663fdd2014-12-17 20:42:37 +00006543 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00006544 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00006545 assert((!VD || !ParamType->isNullPtrType()) &&
6546 "non-null value of type nullptr_t?");
6547 Converted = VD ? TemplateArgument(VD, CanonParamType)
6548 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00006549 break;
6550 }
6551 case APValue::AddrLabelDiff:
6552 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
Leonard Chan86285d22019-01-16 18:53:05 +00006553 case APValue::FixedPoint:
Richard Smith410cc892014-11-26 03:26:53 +00006554 case APValue::Float:
6555 case APValue::ComplexInt:
6556 case APValue::ComplexFloat:
6557 case APValue::Vector:
6558 case APValue::Array:
6559 case APValue::Struct:
6560 case APValue::Union:
6561 llvm_unreachable("invalid kind for template argument");
6562 }
6563
6564 return ArgResult.get();
6565 }
6566
Douglas Gregor86560402009-02-10 23:36:10 +00006567 // C++ [temp.arg.nontype]p5:
6568 // The following conversions are performed on each expression used
6569 // as a non-type template-argument. If a non-type
6570 // template-argument cannot be converted to the type of the
6571 // corresponding template-parameter then the program is
6572 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00006573 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00006574 // C++11:
6575 // -- for a non-type template-parameter of integral or
6576 // enumeration type, conversions permitted in a converted
6577 // constant expression are applied.
6578 //
6579 // C++98:
6580 // -- for a non-type template-parameter of integral or
6581 // enumeration type, integral promotions (4.5) and integral
6582 // conversions (4.7) are applied.
6583
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006584 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00006585 // C++ [temp.arg.nontype]p1:
6586 // A template-argument for a non-type, non-template template-parameter
6587 // shall be one of:
6588 //
6589 // -- for a non-type template-parameter of integral or enumeration
6590 // type, a converted constant expression of the type of the
6591 // template-parameter; or
6592 llvm::APSInt Value;
6593 ExprResult ArgResult =
6594 CheckConvertedConstantExpression(Arg, ParamType, Value,
6595 CCEK_TemplateArg);
6596 if (ArgResult.isInvalid())
6597 return ExprError();
6598
Richard Smith01bfa682016-12-27 02:02:09 +00006599 // We can't check arbitrary value-dependent arguments.
6600 if (ArgResult.get()->isValueDependent()) {
6601 Converted = TemplateArgument(ArgResult.get());
6602 return ArgResult;
6603 }
6604
Richard Smithf8379a02012-01-18 23:55:52 +00006605 // Widen the argument value to sizeof(parameter type). This is almost
6606 // always a no-op, except when the parameter type is bool. In
6607 // that case, this may extend the argument from 1 bit to 8 bits.
6608 QualType IntegerType = ParamType;
6609 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6610 IntegerType = Enum->getDecl()->getIntegerType();
6611 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
6612
Benjamin Kramer6003ad52012-06-07 15:09:51 +00006613 Converted = TemplateArgument(Context, Value,
6614 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00006615 return ArgResult;
6616 }
6617
Richard Smith08b12f12011-10-27 22:11:44 +00006618 ExprResult ArgResult = DefaultLvalueConversion(Arg);
6619 if (ArgResult.isInvalid())
6620 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006621 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00006622
6623 QualType ArgType = Arg->getType();
6624
Douglas Gregor86560402009-02-10 23:36:10 +00006625 // C++ [temp.arg.nontype]p1:
6626 // A template-argument for a non-type, non-template
6627 // template-parameter shall be one of:
6628 //
6629 // -- an integral constant-expression of integral or enumeration
6630 // type; or
6631 // -- the name of a non-type template-parameter; or
Douglas Gregor264ec4f2009-02-17 01:05:43 +00006632 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00006633 if (!ArgType->isIntegralOrEnumerationType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006634 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
6635 << ArgType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00006636 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00006637 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00006638 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00006639 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
6640 QualType T;
Simon Pilgrim6905d222016-12-30 22:55:33 +00006641
Douglas Gregore2b37442012-05-04 22:38:52 +00006642 public:
6643 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00006644
6645 void diagnoseNotICE(Sema &S, SourceLocation Loc,
6646 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00006647 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
6648 }
6649 } Diagnoser(ArgType);
6650
6651 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006652 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00006653 if (!Arg)
6654 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00006655 }
6656
Richard Smithd663fdd2014-12-17 20:42:37 +00006657 // From here on out, all we care about is the unqualified form
6658 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006659 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00006660
6661 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00006662 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00006663 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00006664 } else if (ParamType->isBooleanType()) {
6665 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006666 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00006667 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
6668 !ParamType->isEnumeralType()) {
6669 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006670 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00006671 } else {
6672 // We can't perform this conversion.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006673 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6674 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00006675 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00006676 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00006677 }
6678
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006679 // Add the value of this argument to the list of converted
6680 // arguments. We use the bitwidth and signedness of the template
6681 // parameter.
6682 if (Arg->isValueDependent()) {
6683 // The argument is value-dependent. Create a new
6684 // TemplateArgument with the converted expression.
6685 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006686 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006687 }
6688
Douglas Gregor52aba872009-03-14 00:20:21 +00006689 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00006690 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00006691 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00006692
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006693 if (ParamType->isBooleanType()) {
6694 // Value must be zero or one.
6695 Value = Value != 0;
6696 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6697 if (Value.getBitWidth() != AllowedBits)
6698 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006699 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006700 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006701 llvm::APSInt OldValue = Value;
Simon Pilgrim6905d222016-12-30 22:55:33 +00006702
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006703 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006704 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00006705 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00006706 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006707 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006708 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Simon Pilgrim6905d222016-12-30 22:55:33 +00006709
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006710 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006711 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006712 && (OldValue.isSigned() && OldValue.isNegative())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006713 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
6714 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6715 << Arg->getSourceRange();
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006716 Diag(Param->getLocation(), diag::note_template_param_here);
6717 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006718
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006719 // Complain if we overflowed the template parameter's type.
6720 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006721 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006722 RequiredBits = OldValue.getActiveBits();
6723 else if (OldValue.isUnsigned())
6724 RequiredBits = OldValue.getActiveBits() + 1;
6725 else
6726 RequiredBits = OldValue.getMinSignedBits();
6727 if (RequiredBits > AllowedBits) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006728 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
6729 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6730 << Arg->getSourceRange();
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006731 Diag(Param->getLocation(), diag::note_template_param_here);
6732 }
Douglas Gregor52aba872009-03-14 00:20:21 +00006733 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00006734
Benjamin Kramer6003ad52012-06-07 15:09:51 +00006735 Converted = TemplateArgument(Context, Value,
Simon Pilgrim6905d222016-12-30 22:55:33 +00006736 ParamType->isEnumeralType()
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00006737 ? Context.getCanonicalType(ParamType)
6738 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006739 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00006740 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006741
Richard Smith08b12f12011-10-27 22:11:44 +00006742 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00006743 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
6744
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006745 // Handle pointer-to-function, reference-to-function, and
6746 // pointer-to-member-function all in (roughly) the same way.
6747 if (// -- For a non-type template-parameter of type pointer to
6748 // function, only the function-to-pointer conversion (4.3) is
6749 // applied. If the template-argument represents a set of
6750 // overloaded functions (or a pointer to such), the matching
6751 // function is selected from the set (13.4).
6752 (ParamType->isPointerType() &&
Simon Pilgrimf4cc3b32019-10-05 13:21:08 +00006753 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006754 // -- For a non-type template-parameter of type reference to
6755 // function, no conversions apply. If the template-argument
6756 // represents a set of overloaded functions, the matching
6757 // function is selected from the set (13.4).
6758 (ParamType->isReferenceType() &&
Simon Pilgrimf4cc3b32019-10-05 13:21:08 +00006759 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006760 // -- For a non-type template-parameter of type pointer to
6761 // member function, no conversions apply. If the
6762 // template-argument represents a set of overloaded member
6763 // functions, the matching member function is selected from
6764 // the set (13.4).
6765 (ParamType->isMemberPointerType() &&
Simon Pilgrimf4cc3b32019-10-05 13:21:08 +00006766 ParamType->castAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006767 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006768
Douglas Gregor064fdb22010-04-14 23:11:21 +00006769 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006770 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00006771 true,
6772 FoundResult)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006773 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
John Wiegley01296292011-04-08 18:41:53 +00006774 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00006775
6776 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6777 ArgType = Arg->getType();
6778 } else
John Wiegley01296292011-04-08 18:41:53 +00006779 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006780 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006781
John Wiegley01296292011-04-08 18:41:53 +00006782 if (!ParamType->isMemberPointerType()) {
6783 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6784 ParamType,
6785 Arg, Converted))
6786 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006787 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00006788 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00006789
Douglas Gregor20fdef32012-04-10 17:08:25 +00006790 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6791 Converted))
John Wiegley01296292011-04-08 18:41:53 +00006792 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006793 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006794 }
6795
Chris Lattner696197c2009-02-20 21:37:53 +00006796 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006797 // -- for a non-type template-parameter of type pointer to
6798 // object, qualification conversions (4.4) and the
6799 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00006800 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00006801 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006802 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00006803
John Wiegley01296292011-04-08 18:41:53 +00006804 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6805 ParamType,
6806 Arg, Converted))
6807 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006808 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00006809 }
Mike Stump11289f42009-09-09 15:08:12 +00006810
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006811 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006812 // -- For a non-type template-parameter of type reference to
6813 // object, no conversions apply. The type referred to by the
6814 // reference may be more cv-qualified than the (otherwise
6815 // identical) type of the template-argument. The
6816 // template-parameter is bound directly to the
6817 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00006818 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006819 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00006820
Douglas Gregor064fdb22010-04-14 23:11:21 +00006821 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006822 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
6823 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00006824 true,
6825 FoundResult)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006826 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
John Wiegley01296292011-04-08 18:41:53 +00006827 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00006828
6829 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6830 ArgType = Arg->getType();
6831 } else
John Wiegley01296292011-04-08 18:41:53 +00006832 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006833 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006834
John Wiegley01296292011-04-08 18:41:53 +00006835 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6836 ParamType,
6837 Arg, Converted))
6838 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006839 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006840 }
Douglas Gregor0e558532009-02-11 16:16:59 +00006841
Douglas Gregor20fdef32012-04-10 17:08:25 +00006842 // Deal with parameters of type std::nullptr_t.
6843 if (ParamType->isNullPtrType()) {
6844 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6845 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006846 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006847 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006848
Douglas Gregor20fdef32012-04-10 17:08:25 +00006849 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
6850 case NPV_NotNullPointer:
6851 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
6852 << Arg->getType() << ParamType;
6853 Diag(Param->getLocation(), diag::note_template_param_here);
6854 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00006855
Douglas Gregor20fdef32012-04-10 17:08:25 +00006856 case NPV_Error:
6857 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00006858
Douglas Gregor20fdef32012-04-10 17:08:25 +00006859 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00006860 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00006861 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
6862 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006863 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006864 }
6865 }
6866
Douglas Gregor0e558532009-02-11 16:16:59 +00006867 // -- For a non-type template-parameter of type pointer to data
6868 // member, qualification conversions (4.4) are applied.
6869 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
6870
Douglas Gregor20fdef32012-04-10 17:08:25 +00006871 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6872 Converted))
John Wiegley01296292011-04-08 18:41:53 +00006873 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006874 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00006875}
6876
Richard Smith26b86ea2016-12-31 21:41:23 +00006877static void DiagnoseTemplateParameterListArityMismatch(
6878 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
6879 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
6880
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006881/// Check a template argument against its corresponding
Douglas Gregord32e0282009-02-09 23:23:08 +00006882/// template template parameter.
6883///
6884/// This routine implements the semantics of C++ [temp.arg.template].
6885/// It returns true if an error occurred, and false otherwise.
Richard Smith5d331022018-03-08 01:07:33 +00006886bool Sema::CheckTemplateTemplateArgument(TemplateParameterList *Params,
6887 TemplateArgumentLoc &Arg) {
Eli Friedmanb826a002012-09-26 02:36:12 +00006888 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006889 TemplateDecl *Template = Name.getAsTemplateDecl();
6890 if (!Template) {
6891 // Any dependent template name is fine.
6892 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
6893 return false;
6894 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00006895
Richard Smith26b86ea2016-12-31 21:41:23 +00006896 if (Template->isInvalidDecl())
6897 return true;
6898
Richard Smith3f1b5d02011-05-05 21:57:07 +00006899 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00006900 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00006901 // the name of a class template or an alias template, expressed as an
6902 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00006903 // primary class templates are considered when matching the
6904 // template template argument with the corresponding parameter;
6905 // partial specializations are not considered even if their
6906 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00006907 //
6908 // Note that we also allow template template parameters here, which
6909 // will happen when we are dealing with, e.g., class template
6910 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00006911 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00006912 !isa<TemplateTemplateParmDecl>(Template) &&
David Majnemerc2406d42016-07-11 17:09:56 +00006913 !isa<TypeAliasTemplateDecl>(Template) &&
6914 !isa<BuiltinTemplateDecl>(Template)) {
6915 assert(isa<FunctionTemplateDecl>(Template) &&
6916 "Only function templates are possible here");
Faisal Valib8b04f82016-03-26 20:46:45 +00006917 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
David Majnemerc2406d42016-07-11 17:09:56 +00006918 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
6919 << Template;
Douglas Gregor85e0f662009-02-10 00:24:35 +00006920 }
6921
Richard Smith26b86ea2016-12-31 21:41:23 +00006922 // C++1z [temp.arg.template]p3: (DR 150)
6923 // A template-argument matches a template template-parameter P when P
6924 // is at least as specialized as the template-argument A.
6925 if (getLangOpts().RelaxedTemplateTemplateArgs) {
6926 // Quick check for the common case:
6927 // If P contains a parameter pack, then A [...] matches P if each of A's
6928 // template parameters matches the corresponding template parameter in
6929 // the template-parameter-list of P.
6930 if (TemplateParameterListsAreEqual(
6931 Template->getTemplateParameters(), Params, false,
6932 TPL_TemplateTemplateArgumentMatch, Arg.getLocation()))
6933 return false;
6934
6935 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
6936 Arg.getLocation()))
6937 return false;
6938 // FIXME: Produce better diagnostics for deduction failures.
6939 }
6940
Douglas Gregor85e0f662009-02-10 00:24:35 +00006941 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00006942 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006943 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006944 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006945 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00006946}
6947
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006948/// Given a non-type template argument that refers to a
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006949/// declaration and the type of its corresponding non-type template
6950/// parameter, produce an expression that properly refers to that
6951/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006952ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006953Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6954 QualType ParamType,
6955 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00006956 // C++ [temp.param]p8:
6957 //
6958 // A non-type template-parameter of type "array of T" or
6959 // "function returning T" is adjusted to be of type "pointer to
6960 // T" or "pointer to function returning T", respectively.
6961 if (ParamType->isArrayType())
6962 ParamType = Context.getArrayDecayedType(ParamType);
6963 else if (ParamType->isFunctionType())
6964 ParamType = Context.getPointerType(ParamType);
6965
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006966 // For a NULL non-type template argument, return nullptr casted to the
6967 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00006968 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006969 return ImpCastExprToType(
6970 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
6971 ParamType,
6972 ParamType->getAs<MemberPointerType>()
6973 ? CK_NullToMemberPointer
6974 : CK_NullToPointer);
6975 }
Eli Friedmanb826a002012-09-26 02:36:12 +00006976 assert(Arg.getKind() == TemplateArgument::Declaration &&
6977 "Only declaration template arguments permitted here");
6978
George Burgess IV00f70bd2018-03-01 05:43:23 +00006979 ValueDecl *VD = Arg.getAsDecl();
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006980
Richard Smithb2206622019-12-05 13:39:38 -08006981 CXXScopeSpec SS;
6982 if (ParamType->isMemberPointerType()) {
6983 // If this is a pointer to member, we need to use a qualified name to
6984 // form a suitable pointer-to-member constant.
6985 assert(VD->getDeclContext()->isRecord() &&
6986 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
6987 isa<IndirectFieldDecl>(VD)));
6988 QualType ClassType
6989 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
6990 NestedNameSpecifier *Qualifier
6991 = NestedNameSpecifier::Create(Context, nullptr, false,
6992 ClassType.getTypePtr());
6993 SS.MakeTrivial(Context, Qualifier, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006994 }
6995
Richard Smithb2206622019-12-05 13:39:38 -08006996 ExprResult RefExpr = BuildDeclarationNameExpr(
6997 SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
6998 if (RefExpr.isInvalid())
6999 return ExprError();
David L. Jones93cc9dd2019-12-04 22:08:38 -08007000
Richard Smithb2206622019-12-05 13:39:38 -08007001 // For a pointer, the argument declaration is the pointee. Take its address.
7002 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
7003 if (ParamType->isPointerType() && !ElemT.isNull() &&
7004 Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
7005 // Decay an array argument if we want a pointer to its first element.
7006 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
David L. Jones93cc9dd2019-12-04 22:08:38 -08007007 if (RefExpr.isInvalid())
7008 return ExprError();
Richard Smithb2206622019-12-05 13:39:38 -08007009 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
7010 // For any other pointer, take the address (or form a pointer-to-member).
7011 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
7012 if (RefExpr.isInvalid())
7013 return ExprError();
7014 } else {
7015 assert(ParamType->isReferenceType() &&
7016 "unexpected type for decl template argument");
7017 }
David L. Jones93cc9dd2019-12-04 22:08:38 -08007018
Richard Smithb2206622019-12-05 13:39:38 -08007019 // At this point we should have the right value category.
7020 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
7021 "value kind mismatch for non-type template argument");
David L. Jones93cc9dd2019-12-04 22:08:38 -08007022
Richard Smithb2206622019-12-05 13:39:38 -08007023 // The type of the template parameter can differ from the type of the
7024 // argument in various ways; convert it now if necessary.
7025 QualType DestExprType = ParamType.getNonLValueExprType(Context);
7026 if (!Context.hasSameType(RefExpr.get()->getType(), DestExprType)) {
7027 CastKind CK;
7028 QualType Ignored;
7029 if (Context.hasSimilarType(RefExpr.get()->getType(), DestExprType) ||
7030 IsFunctionConversion(RefExpr.get()->getType(), DestExprType, Ignored)) {
7031 CK = CK_NoOp;
7032 } else if (ParamType->isVoidPointerType() &&
7033 RefExpr.get()->getType()->isPointerType()) {
7034 CK = CK_BitCast;
7035 } else {
7036 // FIXME: Pointers to members can need conversion derived-to-base or
7037 // base-to-derived conversions. We currently don't retain enough
7038 // information to convert properly (we need to track a cast path or
7039 // subobject number in the template argument).
7040 llvm_unreachable(
7041 "unexpected conversion required for non-type template argument");
David L. Jones93cc9dd2019-12-04 22:08:38 -08007042 }
Richard Smithb2206622019-12-05 13:39:38 -08007043 RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
7044 RefExpr.get()->getValueKind());
David L. Jones93cc9dd2019-12-04 22:08:38 -08007045 }
7046
Richard Smithb2206622019-12-05 13:39:38 -08007047 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00007048}
7049
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007050/// Construct a new expression that refers to the given
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00007051/// integral template argument with the given source-location
7052/// information.
7053///
7054/// This routine takes care of the mapping from an integral template
7055/// argument (which may have any integral type) to the appropriate
7056/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007057ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00007058Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
7059 SourceLocation Loc) {
7060 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00007061 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00007062 QualType OrigT = Arg.getIntegralType();
7063
7064 // If this is an enum type that we're instantiating, we need to use an integer
7065 // type the same size as the enumerator. We don't want to build an
7066 // IntegerLiteral with enum type. The integer type of an enum type can be of
7067 // any integral type with C++11 enum classes, make sure we create the right
7068 // type of literal for it.
7069 QualType T = OrigT;
7070 if (const EnumType *ET = OrigT->getAs<EnumType>())
7071 T = ET->getDecl()->getIntegerType();
7072
7073 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00007074 if (T->isAnyCharacterType()) {
7075 CharacterLiteral::CharacterKind Kind;
7076 if (T->isWideCharType())
7077 Kind = CharacterLiteral::Wide;
Richard Smith3a8244d2018-05-01 05:02:45 +00007078 else if (T->isChar8Type() && getLangOpts().Char8)
7079 Kind = CharacterLiteral::UTF8;
Douglas Gregorfb65e592011-07-27 05:40:30 +00007080 else if (T->isChar16Type())
7081 Kind = CharacterLiteral::UTF16;
7082 else if (T->isChar32Type())
7083 Kind = CharacterLiteral::UTF32;
7084 else
7085 Kind = CharacterLiteral::Ascii;
7086
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00007087 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
7088 Kind, T, Loc);
7089 } else if (T->isBooleanType()) {
7090 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
7091 T, Loc);
7092 } else if (T->isNullPtrType()) {
7093 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
7094 } else {
7095 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00007096 }
7097
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00007098 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00007099 // FIXME: This is a hack. We need a better way to handle substituted
7100 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00007101 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
7102 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00007103 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00007104 Loc, Loc);
7105 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00007106
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007107 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00007108}
7109
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007110/// Match two template parameters within template parameter lists.
Douglas Gregor641040a2011-01-12 23:45:44 +00007111static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
7112 bool Complain,
7113 Sema::TemplateParameterListEqualKind Kind,
7114 SourceLocation TemplateArgLoc) {
7115 // Check the actual kind (type, non-type, template).
7116 if (Old->getKind() != New->getKind()) {
7117 if (Complain) {
7118 unsigned NextDiag = diag::err_template_param_different_kind;
7119 if (TemplateArgLoc.isValid()) {
7120 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7121 NextDiag = diag::note_template_param_different_kind;
7122 }
7123 S.Diag(New->getLocation(), NextDiag)
7124 << (Kind != Sema::TPL_TemplateMatch);
7125 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
7126 << (Kind != Sema::TPL_TemplateMatch);
7127 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007128
Douglas Gregor641040a2011-01-12 23:45:44 +00007129 return false;
7130 }
7131
Richard Smith26b86ea2016-12-31 21:41:23 +00007132 // Check that both are parameter packs or neither are parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007133 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007134 // template template parameter, the template template parameter can have
7135 // a parameter pack where the template template argument does not.
7136 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
7137 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
7138 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00007139 if (Complain) {
7140 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
7141 if (TemplateArgLoc.isValid()) {
7142 S.Diag(TemplateArgLoc,
7143 diag::err_template_arg_template_params_mismatch);
7144 NextDiag = diag::note_template_parameter_pack_non_pack;
7145 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007146
Douglas Gregor641040a2011-01-12 23:45:44 +00007147 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
7148 : isa<NonTypeTemplateParmDecl>(New)? 1
7149 : 2;
7150 S.Diag(New->getLocation(), NextDiag)
7151 << ParamKind << New->isParameterPack();
7152 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
7153 << ParamKind << Old->isParameterPack();
7154 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007155
Douglas Gregor641040a2011-01-12 23:45:44 +00007156 return false;
7157 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007158
Douglas Gregor641040a2011-01-12 23:45:44 +00007159 // For non-type template parameters, check the type of the parameter.
7160 if (NonTypeTemplateParmDecl *OldNTTP
7161 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
7162 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007163
Douglas Gregor641040a2011-01-12 23:45:44 +00007164 // If we are matching a template template argument to a template
7165 // template parameter and one of the non-type template parameter types
Richard Smith13894182017-04-13 21:37:24 +00007166 // is dependent, then we must wait until template instantiation time
7167 // to actually compare the arguments.
Douglas Gregor641040a2011-01-12 23:45:44 +00007168 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
Richard Smith13894182017-04-13 21:37:24 +00007169 (OldNTTP->getType()->isDependentType() ||
7170 NewNTTP->getType()->isDependentType()))
Douglas Gregor641040a2011-01-12 23:45:44 +00007171 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007172
Douglas Gregor641040a2011-01-12 23:45:44 +00007173 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
7174 if (Complain) {
7175 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
7176 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007177 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00007178 diag::err_template_arg_template_params_mismatch);
7179 NextDiag = diag::note_template_nontype_parm_different_type;
7180 }
7181 S.Diag(NewNTTP->getLocation(), NextDiag)
7182 << NewNTTP->getType()
7183 << (Kind != Sema::TPL_TemplateMatch);
7184 S.Diag(OldNTTP->getLocation(),
7185 diag::note_template_nontype_parm_prev_declaration)
7186 << OldNTTP->getType();
7187 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007188
Douglas Gregor641040a2011-01-12 23:45:44 +00007189 return false;
7190 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007191
Douglas Gregor641040a2011-01-12 23:45:44 +00007192 return true;
7193 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007194
Douglas Gregor641040a2011-01-12 23:45:44 +00007195 // For template template parameters, check the template parameter types.
7196 // The template parameter lists of template template
7197 // parameters must agree.
7198 if (TemplateTemplateParmDecl *OldTTP
7199 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007200 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00007201 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
7202 OldTTP->getTemplateParameters(),
7203 Complain,
7204 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007205 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00007206 : Kind),
7207 TemplateArgLoc);
7208 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007209
Saar Raz0330fba2019-10-15 18:44:06 +00007210 // TODO: Concepts: Match immediately-introduced-constraint for type
7211 // constraints
7212
Douglas Gregor641040a2011-01-12 23:45:44 +00007213 return true;
7214}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00007215
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007216/// Diagnose a known arity mismatch when comparing template argument
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007217/// lists.
7218static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007219void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007220 TemplateParameterList *New,
7221 TemplateParameterList *Old,
7222 Sema::TemplateParameterListEqualKind Kind,
7223 SourceLocation TemplateArgLoc) {
7224 unsigned NextDiag = diag::err_template_param_list_different_arity;
7225 if (TemplateArgLoc.isValid()) {
7226 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7227 NextDiag = diag::note_template_param_list_different_arity;
7228 }
7229 S.Diag(New->getTemplateLoc(), NextDiag)
7230 << (New->size() > Old->size())
7231 << (Kind != Sema::TPL_TemplateMatch)
7232 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
7233 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
7234 << (Kind != Sema::TPL_TemplateMatch)
7235 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
7236}
7237
Saar Raz0330fba2019-10-15 18:44:06 +00007238static void
7239DiagnoseTemplateParameterListRequiresClauseMismatch(Sema &S,
7240 TemplateParameterList *New,
7241 TemplateParameterList *Old){
7242 S.Diag(New->getTemplateLoc(), diag::err_template_different_requires_clause);
7243 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
7244 << /*declaration*/0;
7245}
7246
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007247/// Determine whether the given template parameter lists are
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007248/// equivalent.
7249///
Mike Stump11289f42009-09-09 15:08:12 +00007250/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007251/// source code as part of a new template declaration.
7252///
7253/// \param Old The old template parameter list, typically found via
7254/// name lookup of the template declared with this template parameter
7255/// list.
7256///
7257/// \param Complain If true, this routine will produce a diagnostic if
7258/// the template parameter lists are not equivalent.
7259///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00007260/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00007261///
7262/// \param TemplateArgLoc If this source location is valid, then we
7263/// are actually checking the template parameter list of a template
7264/// argument (New) against the template parameter list of its
7265/// corresponding template template parameter (Old). We produce
7266/// slightly different diagnostics in this scenario.
7267///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007268/// \returns True if the template parameter lists are equal, false
7269/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00007270bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007271Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
7272 TemplateParameterList *Old,
7273 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00007274 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00007275 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007276 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
7277 if (Complain)
7278 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7279 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007280
7281 return false;
7282 }
7283
Douglas Gregor641040a2011-01-12 23:45:44 +00007284 // C++0x [temp.arg.template]p3:
7285 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00007286 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00007287 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00007288 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007289 // template-parameter-list of P. [...]
7290 TemplateParameterList::iterator NewParm = New->begin();
7291 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007292 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007293 OldParmEnd = Old->end();
7294 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00007295 if (Kind != TPL_TemplateTemplateArgumentMatch ||
7296 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007297 if (NewParm == NewParmEnd) {
7298 if (Complain)
7299 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7300 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007301
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007302 return false;
7303 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007304
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007305 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
7306 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007307 return false;
7308
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007309 ++NewParm;
7310 continue;
7311 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007312
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007313 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00007314 // [...] When P's template- parameter-list contains a template parameter
7315 // pack (14.5.3), the template parameter pack will match zero or more
7316 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007317 // template-parameter-list of A with the same type and form as the
7318 // template parameter pack in P (ignoring whether those template
7319 // parameters are template parameter packs).
7320 for (; NewParm != NewParmEnd; ++NewParm) {
7321 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
7322 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007323 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007324 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007325 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007326
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007327 // Make sure we exhausted all of the arguments.
7328 if (NewParm != NewParmEnd) {
7329 if (Complain)
7330 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7331 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007332
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007333 return false;
7334 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007335
Saar Raz0330fba2019-10-15 18:44:06 +00007336 if (Kind != TPL_TemplateTemplateArgumentMatch) {
7337 const Expr *NewRC = New->getRequiresClause();
7338 const Expr *OldRC = Old->getRequiresClause();
7339 if (!NewRC != !OldRC) {
7340 if (Complain)
7341 DiagnoseTemplateParameterListRequiresClauseMismatch(*this, New, Old);
7342 return false;
7343 }
7344
7345 if (NewRC) {
7346 llvm::FoldingSetNodeID OldRCID, NewRCID;
7347 OldRC->Profile(OldRCID, Context, /*Canonical=*/true);
7348 NewRC->Profile(NewRCID, Context, /*Canonical=*/true);
7349 if (OldRCID != NewRCID) {
7350 if (Complain)
7351 DiagnoseTemplateParameterListRequiresClauseMismatch(*this, New, Old);
7352 return false;
7353 }
7354 }
7355 }
7356
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007357 return true;
7358}
7359
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007360/// Check whether a template can be declared within this scope.
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007361///
7362/// If the template declaration is valid in this scope, returns
7363/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00007364bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007365Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00007366 if (!S)
7367 return false;
7368
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007369 // Find the nearest enclosing declaration scope.
7370 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7371 (S->getFlags() & Scope::TemplateParamScope) != 0)
7372 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00007373
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00007374 // C++ [temp]p4:
7375 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007376 DeclContext *Ctx = S->getEntity();
Alex Lorenz560ae562016-11-02 15:46:34 +00007377 if (Ctx && Ctx->isExternCContext()) {
7378 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
7379 << TemplateParams->getSourceRange();
7380 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
7381 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
7382 return true;
7383 }
Richard Smith8df390f2016-09-08 23:14:54 +00007384 Ctx = Ctx->getRedeclContext();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007385
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00007386 // C++ [temp]p2:
7387 // A template-declaration can appear only as a namespace scope or
7388 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00007389 if (Ctx) {
7390 if (Ctx->isFileContext())
7391 return false;
7392 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
7393 // C++ [temp.mem]p2:
7394 // A local class shall not have member templates.
7395 if (RD->isLocalClass())
7396 return Diag(TemplateParams->getTemplateLoc(),
7397 diag::err_template_inside_local_class)
7398 << TemplateParams->getSourceRange();
7399 else
7400 return false;
7401 }
7402 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007403
Mike Stump11289f42009-09-09 15:08:12 +00007404 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007405 diag::err_template_outside_namespace_or_class_scope)
7406 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007407}
Douglas Gregor67a65642009-02-17 23:15:12 +00007408
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007409/// Determine what kind of template specialization the given declaration
Douglas Gregor54888652009-10-07 00:13:32 +00007410/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007411static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00007412 if (!D)
7413 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007414
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007415 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
7416 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00007417 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
7418 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007419 if (VarDecl *Var = dyn_cast<VarDecl>(D))
7420 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007421
Douglas Gregor54888652009-10-07 00:13:32 +00007422 return TSK_Undeclared;
7423}
7424
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007425/// Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007426/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00007427///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007428/// This routine determines whether a template specialization can be declared
7429/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00007430///
7431/// \param S the semantic analysis object for which this check is being
7432/// performed.
7433///
7434/// \param Specialized the entity being specialized or instantiated, which
7435/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007436/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00007437/// member class).
7438///
7439/// \param PrevDecl the previous declaration of this entity, if any.
7440///
7441/// \param Loc the location of the explicit specialization or instantiation of
7442/// this entity.
7443///
7444/// \param IsPartialSpecialization whether this is a partial specialization of
7445/// a class template.
7446///
Douglas Gregor54888652009-10-07 00:13:32 +00007447/// \returns true if there was an error that we cannot recover from, false
7448/// otherwise.
7449static bool CheckTemplateSpecializationScope(Sema &S,
7450 NamedDecl *Specialized,
7451 NamedDecl *PrevDecl,
7452 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007453 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00007454 // Keep these "kind" numbers in sync with the %select statements in the
7455 // various diagnostics emitted by this routine.
7456 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00007457 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00007458 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007459 else if (isa<VarTemplateDecl>(Specialized))
7460 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00007461 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00007462 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007463 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00007464 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007465 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00007466 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007467 else if (isa<RecordDecl>(Specialized))
7468 EntityKind = 7;
7469 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
7470 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00007471 else {
Richard Smith7d137e32012-03-23 03:33:32 +00007472 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007473 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007474 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00007475 return true;
7476 }
7477
Douglas Gregorf47b9112009-02-25 22:02:03 +00007478 // C++ [temp.expl.spec]p2:
Richard Smithc660c8f2018-03-16 13:36:56 +00007479 // An explicit specialization may be declared in any scope in which
7480 // the corresponding primary template may be defined.
Sebastian Redl50c68252010-08-31 00:36:30 +00007481 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00007482 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007483 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007484 return true;
7485 }
Douglas Gregore4b05162009-10-07 17:21:34 +00007486
7487 // C++ [temp.class.spec]p6:
Richard Smithc660c8f2018-03-16 13:36:56 +00007488 // A class template partial specialization may be declared in any
7489 // scope in which the primary template may be defined.
7490 DeclContext *SpecializedContext =
7491 Specialized->getDeclContext()->getRedeclContext();
7492 DeclContext *DC = S.CurContext->getRedeclContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00007493
Richard Smithc660c8f2018-03-16 13:36:56 +00007494 // Make sure that this redeclaration (or definition) occurs in the same
7495 // scope or an enclosing namespace.
7496 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
7497 : DC->Equals(SpecializedContext))) {
Richard Smitha98f8fc2013-12-07 05:09:50 +00007498 if (isa<TranslationUnitDecl>(SpecializedContext))
7499 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
7500 << EntityKind << Specialized;
Richard Smithc660c8f2018-03-16 13:36:56 +00007501 else {
7502 auto *ND = cast<NamedDecl>(SpecializedContext);
Alexey Bataev0068cb22015-03-20 07:21:46 +00007503 int Diag = diag::err_template_spec_redecl_out_of_scope;
Richard Smithc660c8f2018-03-16 13:36:56 +00007504 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
Alexey Bataev0068cb22015-03-20 07:21:46 +00007505 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
7506 S.Diag(Loc, Diag) << EntityKind << Specialized
Richard Smithc660c8f2018-03-16 13:36:56 +00007507 << ND << isa<CXXRecordDecl>(ND);
7508 }
Richard Smitha98f8fc2013-12-07 05:09:50 +00007509
7510 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007511
Richard Smithc660c8f2018-03-16 13:36:56 +00007512 // Don't allow specializing in the wrong class during error recovery.
7513 // Otherwise, things can go horribly wrong.
7514 if (DC->isRecord())
7515 return true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007516 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007517
Douglas Gregorf47b9112009-02-25 22:02:03 +00007518 return false;
7519}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007520
Richard Smith57aae072016-12-28 02:37:25 +00007521static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
7522 if (!E->isTypeDependent())
Richard Smith6056d5e2014-02-09 00:54:43 +00007523 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00007524 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00007525 Checker.TraverseStmt(E);
Richard Smith57aae072016-12-28 02:37:25 +00007526 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00007527 return E->getSourceRange();
7528 return Checker.MatchLoc;
7529}
7530
7531static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
7532 if (!TL.getType()->isDependentType())
7533 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00007534 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00007535 Checker.TraverseTypeLoc(TL);
Richard Smith57aae072016-12-28 02:37:25 +00007536 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00007537 return TL.getSourceRange();
7538 return Checker.MatchLoc;
7539}
7540
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007541/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007542/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007543static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00007544 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
7545 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007546 for (unsigned I = 0; I != NumArgs; ++I) {
7547 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00007548 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00007549 S, TemplateNameLoc, Param, Args[I].pack_begin(),
7550 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007551 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007552
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007553 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007554 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007555
Eli Friedmanb826a002012-09-26 02:36:12 +00007556 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007557 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00007558
7559 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007560
Douglas Gregor98318c22011-01-03 21:37:45 +00007561 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007562 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
7563 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00007564
7565 // Strip off any implicit casts we added as part of type checking.
7566 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
7567 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007568
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007569 // C++ [temp.class.spec]p8:
7570 // A non-type argument is non-specialized if it is the name of a
7571 // non-type parameter. All other non-type arguments are
7572 // specialized.
7573 //
7574 // Below, we check the two conditions that only apply to
7575 // specialized non-type arguments, so skip any non-specialized
7576 // arguments.
7577 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00007578 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007579 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007580
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007581 // C++ [temp.class.spec]p9:
7582 // Within the argument list of a class template partial
7583 // specialization, the following restrictions apply:
7584 // -- A partially specialized non-type argument expression
7585 // shall not involve a template parameter of the partial
7586 // specialization except when the argument expression is a
7587 // simple identifier.
Richard Smith57aae072016-12-28 02:37:25 +00007588 // -- The type of a template parameter corresponding to a
7589 // specialized non-type argument shall not be dependent on a
7590 // parameter of the specialization.
7591 // DR1315 removes the first bullet, leaving an incoherent set of rules.
7592 // We implement a compromise between the original rules and DR1315:
7593 // -- A specialized non-type template argument shall not be
7594 // type-dependent and the corresponding template parameter
7595 // shall have a non-dependent type.
Richard Smith6056d5e2014-02-09 00:54:43 +00007596 SourceRange ParamUseRange =
Richard Smith57aae072016-12-28 02:37:25 +00007597 findTemplateParameterInType(Param->getDepth(), ArgExpr);
Richard Smith6056d5e2014-02-09 00:54:43 +00007598 if (ParamUseRange.isValid()) {
7599 if (IsDefaultArgument) {
7600 S.Diag(TemplateNameLoc,
7601 diag::err_dependent_non_type_arg_in_partial_spec);
7602 S.Diag(ParamUseRange.getBegin(),
7603 diag::note_dependent_non_type_default_arg_in_partial_spec)
7604 << ParamUseRange;
7605 } else {
7606 S.Diag(ParamUseRange.getBegin(),
7607 diag::err_dependent_non_type_arg_in_partial_spec)
7608 << ParamUseRange;
7609 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007610 return true;
7611 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007612
Richard Smith6056d5e2014-02-09 00:54:43 +00007613 ParamUseRange = findTemplateParameter(
Richard Smith57aae072016-12-28 02:37:25 +00007614 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
Richard Smith6056d5e2014-02-09 00:54:43 +00007615 if (ParamUseRange.isValid()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007616 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
Richard Smith6056d5e2014-02-09 00:54:43 +00007617 diag::err_dependent_typed_non_type_arg_in_partial_spec)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007618 << Param->getType();
Richard Smith6056d5e2014-02-09 00:54:43 +00007619 S.Diag(Param->getLocation(), diag::note_template_param_here)
Richard Smith57aae072016-12-28 02:37:25 +00007620 << (IsDefaultArgument ? ParamUseRange : SourceRange())
7621 << ParamUseRange;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007622 return true;
7623 }
7624 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007625
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007626 return false;
7627}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007628
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007629/// Check the non-type template arguments of a class template
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007630/// partial specialization according to C++ [temp.class.spec]p9.
7631///
Richard Smith6056d5e2014-02-09 00:54:43 +00007632/// \param TemplateNameLoc the location of the template name.
Simon Pilgrim6905d222016-12-30 22:55:33 +00007633/// \param PrimaryTemplate the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00007634/// template.
7635/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00007636/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00007637/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007638///
Richard Smith6056d5e2014-02-09 00:54:43 +00007639/// \returns \c true if there was an error, \c false otherwise.
Richard Smith57aae072016-12-28 02:37:25 +00007640bool Sema::CheckTemplatePartialSpecializationArgs(
7641 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
7642 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
7643 // We have to be conservative when checking a template in a dependent
7644 // context.
7645 if (PrimaryTemplate->getDeclContext()->isDependentContext())
7646 return false;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007647
Richard Smith57aae072016-12-28 02:37:25 +00007648 TemplateParameterList *TemplateParams =
7649 PrimaryTemplate->getTemplateParameters();
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007650 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7651 NonTypeTemplateParmDecl *Param
7652 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
7653 if (!Param)
7654 continue;
7655
Richard Smith57aae072016-12-28 02:37:25 +00007656 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
7657 Param, &TemplateArgs[I],
7658 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007659 return true;
7660 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007661
7662 return false;
7663}
7664
Erich Keanec480f302018-07-12 21:09:05 +00007665DeclResult Sema::ActOnClassTemplateSpecialization(
7666 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7667 SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId,
7668 const ParsedAttributesView &Attr,
7669 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00007670 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00007671
Richard Smith4b55a9c2014-04-17 03:29:33 +00007672 CXXScopeSpec &SS = TemplateId.SS;
7673
Abramo Bagnara60804e12011-03-18 15:16:37 +00007674 // NOTE: KWLoc is the location of the tag keyword. This will instead
7675 // store the location of the outermost template keyword in the declaration.
7676 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00007677 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
7678 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
7679 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
7680 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00007681
Douglas Gregor67a65642009-02-17 23:15:12 +00007682 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00007683 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00007684 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00007685 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
7686
7687 if (!ClassTemplate) {
7688 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007689 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00007690 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
7691 return true;
7692 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007693
Richard Smithf445f192017-02-09 21:04:43 +00007694 bool isMemberSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00007695 bool isPartialSpecialization = false;
7696
Douglas Gregorf47b9112009-02-25 22:02:03 +00007697 // Check the validity of the template headers that introduce this
7698 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00007699 // FIXME: We probably shouldn't complain about these headers for
7700 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007701 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00007702 TemplateParameterList *TemplateParams =
7703 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00007704 KWLoc, TemplateNameLoc, SS, &TemplateId,
Richard Smithf445f192017-02-09 21:04:43 +00007705 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
Richard Smith4b55a9c2014-04-17 03:29:33 +00007706 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007707 if (Invalid)
7708 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007709
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007710 if (TemplateParams && TemplateParams->size() > 0) {
7711 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007712
Douglas Gregorec9518b2010-12-21 08:14:57 +00007713 if (TUK == TUK_Friend) {
7714 Diag(KWLoc, diag::err_partial_specialization_friend)
7715 << SourceRange(LAngleLoc, RAngleLoc);
7716 return true;
7717 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007718
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007719 // C++ [temp.class.spec]p10:
7720 // The template parameter list of a specialization shall not
7721 // contain default template argument values.
7722 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7723 Decl *Param = TemplateParams->getParam(I);
7724 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
7725 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00007726 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007727 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00007728 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007729 }
7730 } else if (NonTypeTemplateParmDecl *NTTP
7731 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
7732 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00007733 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007734 diag::err_default_arg_in_partial_spec)
7735 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00007736 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007737 }
7738 } else {
7739 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00007740 if (TTP->hasDefaultArgument()) {
7741 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007742 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00007743 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00007744 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00007745 }
7746 }
7747 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007748 } else if (TemplateParams) {
7749 if (TUK == TUK_Friend)
7750 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00007751 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007752 SourceRange(TemplateParams->getTemplateLoc(),
7753 TemplateParams->getRAngleLoc()))
7754 << SourceRange(LAngleLoc, RAngleLoc);
Richard Smith4b55a9c2014-04-17 03:29:33 +00007755 } else {
7756 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007757 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00007758
Douglas Gregor67a65642009-02-17 23:15:12 +00007759 // Check that the specialization uses the same tag kind as the
7760 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007761 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7762 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00007763 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007764 Kind, TUK == TUK_Definition, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00007765 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007766 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00007767 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007768 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00007769 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007770 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00007771 diag::note_previous_use);
7772 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7773 }
7774
Douglas Gregorc40290e2009-03-09 23:48:35 +00007775 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00007776 TemplateArgumentListInfo TemplateArgs =
7777 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00007778
Douglas Gregor14406932011-01-03 20:35:03 +00007779 // Check for unexpanded parameter packs in any of the template arguments.
7780 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007781 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00007782 UPPC_PartialSpecialization))
7783 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007784
Douglas Gregor67a65642009-02-17 23:15:12 +00007785 // Check that the template argument list is well-formed for this
7786 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007787 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007788 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
Saar Razfdf80e82019-12-06 01:30:21 +02007789 TemplateArgs, false, Converted,
7790 /*UpdateArgsWithConversion=*/true))
Douglas Gregorc08f4892009-03-25 00:13:59 +00007791 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00007792
Douglas Gregor2373c592009-05-31 09:31:02 +00007793 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00007794 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00007795 if (isPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00007796 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
7797 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007798 return true;
7799
Richard Smith57aae072016-12-28 02:37:25 +00007800 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
7801 // also do it during instantiation.
Douglas Gregor678d76c2011-07-01 01:22:09 +00007802 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007803 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00007804 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00007805 TemplateArgs.arguments(), InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00007806 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
7807 << ClassTemplate->getDeclName();
7808 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00007809 }
7810 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007811
Craig Topperc3ec1492014-05-26 06:22:03 +00007812 void *InsertPos = nullptr;
7813 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00007814
7815 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007816 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00007817 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00007818 else
Craig Topper7e0daca2014-06-26 04:58:53 +00007819 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00007820
Craig Topperc3ec1492014-05-26 06:22:03 +00007821 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00007822
Douglas Gregorf47b9112009-02-25 22:02:03 +00007823 // Check whether we can declare a class template specialization in
7824 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00007825 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007826 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
7827 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007828 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00007829 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007830
Douglas Gregor15301382009-07-30 17:40:51 +00007831 // The canonical type
7832 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00007833 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00007834 // Build the canonical type that describes the converted template
7835 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00007836 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7837 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00007838 Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007839
7840 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007841 ClassTemplate->getInjectedClassNameSpecialization())) {
7842 // C++ [temp.class.spec]p9b3:
7843 //
7844 // -- The argument list of the specialization shall not be identical
7845 // to the implicit argument list of the primary template.
Richard Smith0e617ec2016-12-27 07:56:27 +00007846 //
7847 // This rule has since been removed, because it's redundant given DR1495,
7848 // but we keep it because it produces better diagnostics and recovery.
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007849 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00007850 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00007851 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007852 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
7853 ClassTemplate->getIdentifier(),
7854 TemplateNameLoc,
7855 Attr,
7856 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00007857 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00007858 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00007859 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007860 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007861 }
Douglas Gregor15301382009-07-30 17:40:51 +00007862
Douglas Gregor2373c592009-05-31 09:31:02 +00007863 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00007864 ClassTemplatePartialSpecializationDecl *PrevPartial
7865 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007866 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00007867 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00007868 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007869 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00007870 TemplateParams,
7871 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007872 Converted,
John McCall6b51f282009-11-23 01:53:49 +00007873 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00007874 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00007875 PrevPartial);
Bruno Ricci4224c872018-12-21 14:35:24 +00007876 SetNestedNameSpecifier(*this, Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007877 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Benjamin Kramer9cc210652015-08-05 09:40:49 +00007878 Partial->setTemplateParameterListsInfo(
7879 Context, TemplateParameterLists.drop_back(1));
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007880 }
Douglas Gregor2373c592009-05-31 09:31:02 +00007881
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007882 if (!PrevPartial)
7883 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00007884 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00007885
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007886 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00007887 // template specialization, make a note of that.
7888 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
7889 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007890
Richard Smith57aae072016-12-28 02:37:25 +00007891 CheckTemplatePartialSpecialization(Partial);
Douglas Gregor67a65642009-02-17 23:15:12 +00007892 } else {
7893 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00007894 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00007895 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007896 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00007897 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007898 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007899 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007900 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00007901 PrevDecl);
Bruno Ricci4224c872018-12-21 14:35:24 +00007902 SetNestedNameSpecifier(*this, Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007903 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00007904 Specialization->setTemplateParameterListsInfo(Context,
Benjamin Kramer9cc210652015-08-05 09:40:49 +00007905 TemplateParameterLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007906 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007907
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007908 if (!PrevDecl)
7909 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00007910
David Majnemer678f50b2015-11-18 19:49:19 +00007911 if (CurContext->isDependentContext()) {
David Majnemer678f50b2015-11-18 19:49:19 +00007912 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7913 CanonType = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00007914 CanonTemplate, Converted);
David Majnemer678f50b2015-11-18 19:49:19 +00007915 } else {
7916 CanonType = Context.getTypeDeclType(Specialization);
7917 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007918 }
7919
Douglas Gregor06db9f52009-10-12 20:18:28 +00007920 // C++ [temp.expl.spec]p6:
7921 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007922 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007923 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007924 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007925 // use occurs; no diagnostic is required.
7926 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007927 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007928 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007929 // Is there any previous explicit specialization declaration?
7930 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7931 Okay = true;
7932 break;
7933 }
7934 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007935
Douglas Gregorc854c662010-02-26 06:03:23 +00007936 if (!Okay) {
7937 SourceRange Range(TemplateNameLoc, RAngleLoc);
7938 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
7939 << Context.getTypeDeclType(Specialization) << Range;
7940
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007941 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00007942 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007943 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00007944 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00007945 return true;
7946 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007947 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007948
Douglas Gregor2208a292009-09-26 20:57:03 +00007949 // If this is not a friend, note that this is an explicit specialization.
7950 if (TUK != TUK_Friend)
7951 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00007952
7953 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00007954 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00007955 RecordDecl *Def = Specialization->getDefinition();
7956 NamedDecl *Hidden = nullptr;
7957 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
7958 SkipBody->ShouldSkip = true;
Richard Smithc4577662018-09-12 02:13:47 +00007959 SkipBody->Previous = Def;
Richard Smith858e0e02017-05-11 23:11:16 +00007960 makeMergedDefinitionVisible(Hidden);
Richard Smithc7e6ff02015-05-18 20:36:47 +00007961 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00007962 SourceRange Range(TemplateNameLoc, RAngleLoc);
Richard Smith792c22d2016-12-24 04:09:05 +00007963 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00007964 Diag(Def->getLocation(), diag::note_previous_definition);
7965 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00007966 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00007967 }
7968 }
7969
Erich Keanec480f302018-07-12 21:09:05 +00007970 ProcessDeclAttributeList(S, Specialization, Attr);
John McCall659a3372010-12-18 03:30:47 +00007971
Richard Smith034b94a2012-08-17 03:20:55 +00007972 // Add alignment attributes if necessary; these attributes are checked when
7973 // the ASTContext lays out the structure.
Richard Smithc4577662018-09-12 02:13:47 +00007974 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
Richard Smith034b94a2012-08-17 03:20:55 +00007975 AddAlignmentAttributesForRecord(Specialization);
7976 AddMsStructLayoutForRecord(Specialization);
7977 }
7978
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00007979 if (ModulePrivateLoc.isValid())
7980 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
7981 << (isPartialSpecialization? 1 : 0)
7982 << FixItHint::CreateRemoval(ModulePrivateLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00007983
Douglas Gregord56a91e2009-02-26 22:19:44 +00007984 // Build the fully-sugared type for this class template
7985 // specialization as the user wrote in the specialization
7986 // itself. This means that we'll pretty-print the type retrieved
7987 // from the specialization's declaration the way that the user
7988 // actually wrote the specialization, rather than formatting the
7989 // name based on the "canonical" representation used to store the
7990 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007991 TypeSourceInfo *WrittenTy
7992 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7993 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007994 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00007995 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007996 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007997 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007998
Douglas Gregor1e249f82009-02-25 22:18:32 +00007999 // C++ [temp.expl.spec]p9:
8000 // A template explicit specialization is in the scope of the
8001 // namespace in which the template was defined.
8002 //
8003 // We actually implement this paragraph where we set the semantic
8004 // context (in the creation of the ClassTemplateSpecializationDecl),
8005 // but we also maintain the lexical context where the actual
8006 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00008007 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00008008
Douglas Gregor67a65642009-02-17 23:15:12 +00008009 // We may be starting the definition of this specialization.
Richard Smithc4577662018-09-12 02:13:47 +00008010 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
Douglas Gregor67a65642009-02-17 23:15:12 +00008011 Specialization->startDefinition();
8012
Douglas Gregor2208a292009-09-26 20:57:03 +00008013 if (TUK == TUK_Friend) {
8014 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
8015 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00008016 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00008017 /*FIXME:*/KWLoc);
8018 Friend->setAccess(AS_public);
8019 CurContext->addDecl(Friend);
8020 } else {
8021 // Add the specialization into its lexical context, so that it can
8022 // be seen when iterating through the list of declarations in that
8023 // context. However, specializations are not found by name lookup.
8024 CurContext->addDecl(Specialization);
8025 }
Richard Smithc4577662018-09-12 02:13:47 +00008026
8027 if (SkipBody && SkipBody->ShouldSkip)
8028 return SkipBody->Previous;
8029
John McCall48871652010-08-21 09:40:31 +00008030 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00008031}
Douglas Gregor333489b2009-03-27 23:10:48 +00008032
John McCall48871652010-08-21 09:40:31 +00008033Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00008034 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00008035 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008036 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00008037 ActOnDocumentableDecl(NewDecl);
8038 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00008039}
8040
Saar Razd7aae332019-07-10 21:25:49 +00008041Decl *Sema::ActOnConceptDefinition(Scope *S,
8042 MultiTemplateParamsArg TemplateParameterLists,
8043 IdentifierInfo *Name, SourceLocation NameLoc,
8044 Expr *ConstraintExpr) {
8045 DeclContext *DC = CurContext;
8046
8047 if (!DC->getRedeclContext()->isFileContext()) {
8048 Diag(NameLoc,
8049 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
8050 return nullptr;
8051 }
8052
8053 if (TemplateParameterLists.size() > 1) {
8054 Diag(NameLoc, diag::err_concept_extra_headers);
8055 return nullptr;
8056 }
8057
8058 if (TemplateParameterLists.front()->size() == 0) {
8059 Diag(NameLoc, diag::err_concept_no_parameters);
8060 return nullptr;
8061 }
8062
8063 ConceptDecl *NewDecl = ConceptDecl::Create(Context, DC, NameLoc, Name,
8064 TemplateParameterLists.front(),
8065 ConstraintExpr);
Saar Raz5d98ba62019-10-15 15:24:26 +00008066
Saar Raz0330fba2019-10-15 18:44:06 +00008067 if (NewDecl->hasAssociatedConstraints()) {
Saar Razd7aae332019-07-10 21:25:49 +00008068 // C++2a [temp.concept]p4:
8069 // A concept shall not have associated constraints.
Saar Razd7aae332019-07-10 21:25:49 +00008070 Diag(NameLoc, diag::err_concept_no_associated_constraints);
8071 NewDecl->setInvalidDecl();
8072 }
8073
8074 // Check for conflicting previous declaration.
8075 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NameLoc);
8076 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
8077 ForVisibleRedeclaration);
8078 LookupName(Previous, S);
8079
8080 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage=*/false,
8081 /*AllowInlineNamespace*/false);
8082 if (!Previous.empty()) {
8083 auto *Old = Previous.getRepresentativeDecl();
8084 Diag(NameLoc, isa<ConceptDecl>(Old) ? diag::err_redefinition :
8085 diag::err_redefinition_different_kind) << NewDecl->getDeclName();
8086 Diag(Old->getLocation(), diag::note_previous_definition);
8087 }
8088
8089 ActOnDocumentableDecl(NewDecl);
8090 PushOnScopeChains(NewDecl, S);
8091 return NewDecl;
8092}
8093
8094/// \brief Strips various properties off an implicit instantiation
John McCall4f7ced62010-02-11 01:33:53 +00008095/// that has just been explicitly specialized.
8096static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00008097 D->dropAttr<DLLImportAttr>();
8098 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00008099
Nico Webere4974382014-12-19 23:52:45 +00008100 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00008101 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00008102}
8103
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008104/// Compute the diagnostic location for an explicit instantiation
Nico Webera8f80b32012-01-09 19:52:25 +00008105// declaration or definition.
8106static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00008107 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00008108 // Explicit instantiations following a specialization have no effect and
8109 // hence no PointOfInstantiation. In that case, walk decl backwards
8110 // until a valid name loc is found.
8111 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00008112 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
8113 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00008114 PrevDiagLoc = Prev->getLocation();
8115 }
8116 assert(PrevDiagLoc.isValid() &&
8117 "Explicit instantiation without point of instantiation?");
8118 return PrevDiagLoc;
8119}
8120
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008121/// Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008122/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008123/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008124/// new specialization/instantiation will have any effect.
8125///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008126/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008127/// instantiation.
8128///
8129/// \param NewTSK the kind of the new explicit specialization or instantiation.
8130///
8131/// \param PrevDecl the previous declaration of the entity.
8132///
8133/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
8134///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008135/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008136/// declaration was instantiated (either implicitly or explicitly).
8137///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008138/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008139/// specialization or instantiation has no effect and should be ignored.
8140///
8141/// \returns true if there was an error that should prevent the introduction of
8142/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00008143bool
8144Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
8145 TemplateSpecializationKind NewTSK,
8146 NamedDecl *PrevDecl,
8147 TemplateSpecializationKind PrevTSK,
8148 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00008149 bool &HasNoEffect) {
8150 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008151
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008152 switch (NewTSK) {
8153 case TSK_Undeclared:
8154 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00008155 assert(
8156 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
8157 "previous declaration must be implicit!");
8158 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008159
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008160 case TSK_ExplicitSpecialization:
8161 switch (PrevTSK) {
8162 case TSK_Undeclared:
8163 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008164 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008165 // explicitly specialized or has merely been mentioned without any
8166 // instantiation.
8167 return false;
8168
8169 case TSK_ImplicitInstantiation:
8170 if (PrevPointOfInstantiation.isInvalid()) {
8171 // The declaration itself has not actually been instantiated, so it is
8172 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00008173 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008174 return false;
8175 }
8176 // Fall through
Galina Kistanova3779cb32017-06-07 06:25:05 +00008177 LLVM_FALLTHROUGH;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008178
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008179 case TSK_ExplicitInstantiationDeclaration:
8180 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008181 assert((PrevTSK == TSK_ImplicitInstantiation ||
8182 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008183 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008184
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008185 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008186 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008187 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008188 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008189 // implicit instantiation to take place, in every translation unit in
8190 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00008191 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00008192 // Is there any previous explicit specialization declaration?
8193 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
8194 return false;
8195 }
8196
Douglas Gregor1d957a32009-10-27 18:42:08 +00008197 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008198 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008199 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008200 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008201
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008202 return true;
8203 }
Galina Kistanova1d36e832017-06-08 18:20:32 +00008204 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008205
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008206 case TSK_ExplicitInstantiationDeclaration:
8207 switch (PrevTSK) {
8208 case TSK_ExplicitInstantiationDeclaration:
8209 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00008210 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008211 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008212
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008213 case TSK_Undeclared:
8214 case TSK_ImplicitInstantiation:
8215 // We're explicitly instantiating something that may have already been
8216 // implicitly instantiated; that's fine.
8217 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008218
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008219 case TSK_ExplicitSpecialization:
8220 // C++0x [temp.explicit]p4:
8221 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008222 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008223 // specialization for that template, the explicit instantiation has no
8224 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00008225 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008226 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008227
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008228 case TSK_ExplicitInstantiationDefinition:
8229 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008230 // If an entity is the subject of both an explicit instantiation
8231 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008232 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008233 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00008234 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00008235
8236 // Explicit instantiations following a specialization have no effect and
8237 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
8238 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00008239 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
8240 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008241 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008242 return false;
8243 }
Bruno Riccid8c17672018-12-21 20:38:06 +00008244 llvm_unreachable("Unexpected TemplateSpecializationKind!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008245
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008246 case TSK_ExplicitInstantiationDefinition:
8247 switch (PrevTSK) {
8248 case TSK_Undeclared:
8249 case TSK_ImplicitInstantiation:
8250 // We're explicitly instantiating something that may have already been
8251 // implicitly instantiated; that's fine.
8252 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008253
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008254 case TSK_ExplicitSpecialization:
8255 // C++ DR 259, C++0x [temp.explicit]p4:
8256 // For a given set of template parameters, if an explicit
8257 // instantiation of a template appears after a declaration of
8258 // an explicit specialization for that template, the explicit
8259 // instantiation has no effect.
Richard Smithe4caa482016-08-31 23:23:25 +00008260 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
Richard Smith0bf8a4922011-10-18 20:49:44 +00008261 << PrevDecl;
8262 Diag(PrevDecl->getLocation(),
8263 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008264 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008265 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008266
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008267 case TSK_ExplicitInstantiationDeclaration:
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00008268 // We're explicitly instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008269 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00008270
8271 // C++0x [temp.explicit]p4:
8272 // For a given set of template parameters, if an explicit instantiation
8273 // of a template appears after a declaration of an explicit
8274 // specialization for that template, the explicit instantiation has no
8275 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00008276 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00008277 // Is there any previous explicit specialization declaration?
8278 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
8279 HasNoEffect = true;
8280 break;
8281 }
8282 }
8283
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008284 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008285
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008286 case TSK_ExplicitInstantiationDefinition:
8287 // C++0x [temp.spec]p5:
8288 // For a given template and a given set of template-arguments,
8289 // - an explicit instantiation definition shall appear at most once
8290 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00008291
8292 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
8293 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00008294 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00008295 : diag::err_explicit_instantiation_duplicate)
8296 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00008297 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00008298 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008299 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008300 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008301 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008302 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008303
David Blaikie83d382b2011-09-23 05:06:16 +00008304 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008305}
8306
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008307/// Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00008308/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00008309///
James Dennettf14a6e52012-06-15 22:23:43 +00008310/// The only possible way to get a dependent function template specialization
8311/// is with a friend declaration, like so:
8312///
8313/// \code
8314/// template \<class T> void foo(T);
8315/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00008316/// friend void foo<>(T);
8317/// };
James Dennettf14a6e52012-06-15 22:23:43 +00008318/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00008319///
8320/// There really isn't any useful analysis we can do here, so we
8321/// just store the information.
8322bool
8323Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
8324 const TemplateArgumentListInfo &ExplicitTemplateArgs,
8325 LookupResult &Previous) {
8326 // Remove anything from Previous that isn't a function template in
8327 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00008328 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00008329 LookupResult::Filter F = Previous.makeFilter();
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008330 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
8331 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
John McCallb9c78482010-04-08 09:05:18 +00008332 while (F.hasNext()) {
8333 NamedDecl *D = F.next()->getUnderlyingDecl();
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008334 if (!isa<FunctionTemplateDecl>(D)) {
John McCallb9c78482010-04-08 09:05:18 +00008335 F.erase();
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008336 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
8337 continue;
8338 }
8339
8340 if (!FDLookupContext->InEnclosingNamespaceSetOf(
8341 D->getDeclContext()->getRedeclContext())) {
8342 F.erase();
8343 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
8344 continue;
8345 }
John McCallb9c78482010-04-08 09:05:18 +00008346 }
8347 F.done();
8348
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008349 if (Previous.empty()) {
8350 Diag(FD->getLocation(),
8351 diag::err_dependent_function_template_spec_no_match);
8352 for (auto &P : DiscardedCandidates)
8353 Diag(P.second->getLocation(),
8354 diag::note_dependent_function_template_spec_discard_reason)
8355 << P.first;
8356 return true;
8357 }
John McCallb9c78482010-04-08 09:05:18 +00008358
8359 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
8360 ExplicitTemplateArgs);
8361 return false;
8362}
8363
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008364/// Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008365/// specialization.
8366///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008367/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008368/// explicit function template specialization. On successful completion,
8369/// the function declaration \p FD will become a function template
8370/// specialization.
8371///
8372/// \param FD the function declaration, which will be updated to become a
8373/// function template specialization.
8374///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008375/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
8376/// if any. Note that this may be valid info even when 0 arguments are
8377/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
8378/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008379///
Francois Pichet3a44e432011-07-08 06:21:47 +00008380/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008381/// this function specialization.
Richard Smith8ce732b2019-01-07 06:00:46 +00008382///
8383/// \param QualifiedFriend whether this is a lookup for a qualified friend
8384/// declaration with no explicit template argument list that might be
8385/// befriending a function template specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008386bool Sema::CheckFunctionTemplateSpecialization(
8387 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smith8ce732b2019-01-07 06:00:46 +00008388 LookupResult &Previous, bool QualifiedFriend) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008389 // The set of function template specializations that could match this
8390 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00008391 UnresolvedSet<8> Candidates;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008392 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
8393 /*ForTakingAddress=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008394
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008395 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
8396 ConvertedTemplateArgs;
8397
Sebastian Redl50c68252010-08-31 00:36:30 +00008398 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00008399 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8400 I != E; ++I) {
8401 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
8402 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008403 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008404 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00008405 if (!FDLookupContext->InEnclosingNamespaceSetOf(
8406 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008407 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008408
Richard Smith574f4f62013-01-14 05:37:29 +00008409 // When matching a constexpr member function template specialization
8410 // against the primary template, we don't yet know whether the
8411 // specialization has an implicit 'const' (because we don't know whether
8412 // it will be a static member function until we know which template it
8413 // specializes), so adjust it now assuming it specializes this template.
8414 QualType FT = FD->getType();
8415 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00008416 CXXMethodDecl *OldMD =
8417 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00008418 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00008419 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00008420 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00008421 EPI.TypeQuals.addConst();
Alp Toker314cc812014-01-25 16:55:45 +00008422 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00008423 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00008424 }
8425 }
8426
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008427 TemplateArgumentListInfo Args;
8428 if (ExplicitTemplateArgs)
8429 Args = *ExplicitTemplateArgs;
8430
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008431 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008432 // A trailing template-argument can be left unspecified in the
8433 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008434 // provided it can be deduced from the function argument type.
8435 // Perform template argument deduction to determine whether we may be
8436 // specializing this template.
8437 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00008438 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00008439 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00008440 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
8441 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
Richard Smithc2bebe92016-05-11 20:37:46 +00008442 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
8443 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008444 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008445 // that we can provide nifty diagnostics.
Richard Smithc2bebe92016-05-11 20:37:46 +00008446 FailedCandidates.addCandidate().set(
8447 I.getPair(), FunTmpl->getTemplatedDecl(),
8448 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008449 (void)TDK;
8450 continue;
8451 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008452
Artem Belevich64135c32016-12-08 19:38:13 +00008453 // Target attributes are part of the cuda function signature, so
8454 // the deduced template's cuda target must match that of the
8455 // specialization. Given that C++ template deduction does not
8456 // take target attributes into account, we reject candidates
8457 // here that have a different target.
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008458 if (LangOpts.CUDA &&
Artem Belevich64135c32016-12-08 19:38:13 +00008459 IdentifyCUDATarget(Specialization,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00008460 /* IgnoreImplicitHDAttr = */ true) !=
8461 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008462 FailedCandidates.addCandidate().set(
8463 I.getPair(), FunTmpl->getTemplatedDecl(),
8464 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
8465 continue;
8466 }
8467
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008468 // Record this candidate.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008469 if (ExplicitTemplateArgs)
8470 ConvertedTemplateArgs[Specialization] = std::move(Args);
John McCall58cc69d2010-01-27 01:50:18 +00008471 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008472 }
8473 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008474
Richard Smith8ce732b2019-01-07 06:00:46 +00008475 // For a qualified friend declaration (with no explicit marker to indicate
8476 // that a template specialization was intended), note all (template and
8477 // non-template) candidates.
8478 if (QualifiedFriend && Candidates.empty()) {
8479 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
8480 << FD->getDeclName() << FDLookupContext;
8481 // FIXME: We should form a single candidate list and diagnose all
8482 // candidates at once, to get proper sorting and limiting.
8483 for (auto *OldND : Previous) {
8484 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
Richard Smith974c8b72019-10-19 00:04:43 +00008485 NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
Richard Smith8ce732b2019-01-07 06:00:46 +00008486 }
8487 FailedCandidates.NoteCandidates(*this, FD->getLocation());
8488 return true;
8489 }
8490
Douglas Gregor5de279c2009-09-26 03:41:46 +00008491 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008492 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith8ce732b2019-01-07 06:00:46 +00008493 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
Larisse Voufo98b20f12013-07-19 23:00:19 +00008494 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
8495 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00008496 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00008497 PDiag(diag::note_function_template_spec_matched));
8498
John McCall58cc69d2010-01-27 01:50:18 +00008499 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008500 return true;
John McCall58cc69d2010-01-27 01:50:18 +00008501
8502 // Ignore access information; it doesn't figure into redeclaration checking.
8503 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00008504
8505 FunctionTemplateSpecializationInfo *SpecInfo
8506 = Specialization->getTemplateSpecializationInfo();
8507 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00008508
8509 // Note: do not overwrite location info if previous template
8510 // specialization kind was explicit.
8511 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00008512 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00008513 Specialization->setLocation(FD->getLocation());
Richard Smith54f04402017-05-18 02:29:20 +00008514 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
Richard Smith5b8b3db2012-02-20 23:28:05 +00008515 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
8516 // function can differ from the template declaration with respect to
8517 // the constexpr specifier.
Richard Smith77e9e842017-05-09 23:02:10 +00008518 // FIXME: We need an update record for this AST mutation.
8519 // FIXME: What if there are multiple such prior declarations (for instance,
8520 // from different modules)?
Gauthier Harnisch796ed032019-06-14 08:56:20 +00008521 Specialization->setConstexprKind(FD->getConstexprKind());
Richard Smith5b8b3db2012-02-20 23:28:05 +00008522 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008523
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008524 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00008525 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00008526
8527 // If this is a friend declaration, then we're not really declaring
8528 // an explicit specialization.
8529 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008530
Douglas Gregor54888652009-10-07 00:13:32 +00008531 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00008532 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008533 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00008534 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008535 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00008536 false))
Douglas Gregor54888652009-10-07 00:13:32 +00008537 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00008538
8539 // C++ [temp.expl.spec]p6:
8540 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008541 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00008542 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008543 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00008544 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00008545 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00008546 if (!isFriend &&
8547 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00008548 TSK_ExplicitSpecialization,
8549 Specialization,
8550 SpecInfo->getTemplateSpecializationKind(),
8551 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008552 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00008553 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008554
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008555 // Mark the prior declaration as an explicit specialization, so that later
8556 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00008557 if (!isFriend) {
Faisal Vali81a88be2016-06-14 03:23:15 +00008558 // Since explicit specializations do not inherit '=delete' from their
8559 // primary function template - check if the 'specialization' that was
8560 // implicitly generated (during template argument deduction for partial
8561 // ordering) from the most specialized of all the function templates that
8562 // 'FD' could have been specializing, has a 'deleted' definition. If so,
8563 // first check that it was implicitly generated during template argument
8564 // deduction by making sure it wasn't referenced, and then reset the deleted
8565 // flag to not-deleted, so that we can inherit that information from 'FD'.
8566 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
8567 !Specialization->getCanonicalDecl()->isReferenced()) {
Richard Smith77e9e842017-05-09 23:02:10 +00008568 // FIXME: This assert will not hold in the presence of modules.
Faisal Vali81a88be2016-06-14 03:23:15 +00008569 assert(
8570 Specialization->getCanonicalDecl() == Specialization &&
8571 "This must be the only existing declaration of this specialization");
Richard Smith77e9e842017-05-09 23:02:10 +00008572 // FIXME: We need an update record for this AST mutation.
Faisal Vali81a88be2016-06-14 03:23:15 +00008573 Specialization->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008574 }
Richard Smith54f04402017-05-18 02:29:20 +00008575 // FIXME: We need an update record for this AST mutation.
John McCall816d75b2010-03-24 07:46:06 +00008576 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00008577 MarkUnusedFileScopedDecl(Specialization);
8578 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008579
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008580 // Turn the given function declaration into a function template
8581 // specialization, with the template arguments from the previous
8582 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008583 // Take copies of (semantic and syntactic) template argument lists.
8584 const TemplateArgumentList* TemplArgs = new (Context)
8585 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008586 FD->setFunctionTemplateSpecialization(
8587 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
8588 SpecInfo->getTemplateSpecializationKind(),
8589 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008590
Artem Belevich64135c32016-12-08 19:38:13 +00008591 // A function template specialization inherits the target attributes
8592 // of its template. (We require the attributes explicitly in the
8593 // code to match, but a template may have implicit attributes by
8594 // virtue e.g. of being constexpr, and it passes these implicit
8595 // attributes on to its specializations.)
8596 if (LangOpts.CUDA)
8597 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
8598
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008599 // The "previous declaration" for this function template specialization is
8600 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00008601 Previous.clear();
8602 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008603 return false;
8604}
8605
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008606/// Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008607/// specialization.
8608///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008609/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008610/// explicit member function specialization. On successful completion,
8611/// the function declaration \p FD will become a member function
8612/// specialization.
8613///
Douglas Gregor86d142a2009-10-08 07:24:58 +00008614/// \param Member the member declaration, which will be updated to become a
8615/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008616///
John McCall1f82f242009-11-18 22:49:29 +00008617/// \param Previous the set of declarations, one of which may be specialized
8618/// by this function specialization; the set will be modified to contain the
8619/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008620bool
John McCall1f82f242009-11-18 22:49:29 +00008621Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008622 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00008623
Douglas Gregor86d142a2009-10-08 07:24:58 +00008624 // Try to find the member we are instantiating.
Richard Smith22e7cc62016-05-24 00:01:49 +00008625 NamedDecl *FoundInstantiation = nullptr;
Craig Topperc3ec1492014-05-26 06:22:03 +00008626 NamedDecl *Instantiation = nullptr;
8627 NamedDecl *InstantiatedFrom = nullptr;
8628 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00008629
John McCall1f82f242009-11-18 22:49:29 +00008630 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008631 // Nowhere to look anyway.
8632 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008633 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8634 I != E; ++I) {
8635 NamedDecl *D = (*I)->getUnderlyingDecl();
8636 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00008637 QualType Adjusted = Function->getType();
8638 if (!hasExplicitCallingConv(Adjusted))
8639 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
Richard Smith4576a772018-09-10 06:35:32 +00008640 // This doesn't handle deduced return types, but both function
8641 // declarations should be undeduced at this point.
Rafael Espindola66747222013-12-10 00:59:31 +00008642 if (Context.hasSameType(Adjusted, Method->getType())) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008643 FoundInstantiation = *I;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008644 Instantiation = Method;
8645 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008646 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008647 break;
8648 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008649 }
8650 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00008651 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008652 VarDecl *PrevVar;
8653 if (Previous.isSingleResult() &&
8654 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00008655 if (PrevVar->isStaticDataMember()) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008656 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00008657 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008658 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008659 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008660 }
8661 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008662 CXXRecordDecl *PrevRecord;
8663 if (Previous.isSingleResult() &&
8664 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008665 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00008666 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008667 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008668 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008669 }
Richard Smith7d137e32012-03-23 03:33:32 +00008670 } else if (isa<EnumDecl>(Member)) {
8671 EnumDecl *PrevEnum;
8672 if (Previous.isSingleResult() &&
8673 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008674 FoundInstantiation = Previous.getRepresentativeDecl();
Richard Smith7d137e32012-03-23 03:33:32 +00008675 Instantiation = PrevEnum;
8676 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
8677 MSInfo = PrevEnum->getMemberSpecializationInfo();
8678 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008679 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008680
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008681 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008682 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008683 // specializations are always out-of-line, the caller will complain about
8684 // this mismatch later.
8685 return false;
8686 }
John McCalle820e5e2010-04-13 20:37:33 +00008687
Richard Smith77e9e842017-05-09 23:02:10 +00008688 // A member specialization in a friend declaration isn't really declaring
8689 // an explicit specialization, just identifying a specific (possibly implicit)
8690 // specialization. Don't change the template specialization kind.
8691 //
8692 // FIXME: Is this really valid? Other compilers reject.
John McCalle820e5e2010-04-13 20:37:33 +00008693 if (Member->getFriendObjectKind() != Decl::FOK_None) {
8694 // Preserve instantiation information.
8695 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
8696 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
8697 cast<CXXMethodDecl>(InstantiatedFrom),
8698 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
8699 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
8700 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
8701 cast<CXXRecordDecl>(InstantiatedFrom),
8702 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
8703 }
8704
8705 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00008706 Previous.addDecl(FoundInstantiation);
John McCalle820e5e2010-04-13 20:37:33 +00008707 return false;
8708 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008709
Douglas Gregor86d142a2009-10-08 07:24:58 +00008710 // Make sure that this is a specialization of a member.
8711 if (!InstantiatedFrom) {
8712 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
8713 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008714 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
8715 return true;
8716 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008717
Douglas Gregor06db9f52009-10-12 20:18:28 +00008718 // C++ [temp.expl.spec]p6:
8719 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00008720 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00008721 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008722 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00008723 // use occurs; no diagnostic is required.
8724 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00008725
Abramo Bagnara8075c852010-06-12 07:44:57 +00008726 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00008727 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
8728 TSK_ExplicitSpecialization,
8729 Instantiation,
8730 MSInfo->getTemplateSpecializationKind(),
8731 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008732 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00008733 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008734
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008735 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008736 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00008737 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008738 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00008739 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008740 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00008741
Richard Smith77e9e842017-05-09 23:02:10 +00008742 // Note that this member specialization is an "instantiation of" the
8743 // corresponding member of the original template.
8744 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008745 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
8746 if (InstantiationFunction->getTemplateSpecializationKind() ==
8747 TSK_ImplicitInstantiation) {
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008748 // Explicit specializations of member functions of class templates do not
8749 // inherit '=delete' from the member function they are specializing.
8750 if (InstantiationFunction->isDeleted()) {
Richard Smith77e9e842017-05-09 23:02:10 +00008751 // FIXME: This assert will not hold in the presence of modules.
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008752 assert(InstantiationFunction->getCanonicalDecl() ==
8753 InstantiationFunction);
Richard Smith77e9e842017-05-09 23:02:10 +00008754 // FIXME: We need an update record for this AST mutation.
Richard Smith5f274382016-09-28 23:55:27 +00008755 InstantiationFunction->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008756 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008757 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008758
Richard Smith77e9e842017-05-09 23:02:10 +00008759 MemberFunction->setInstantiationOfMemberFunction(
8760 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8761 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
8762 MemberVar->setInstantiationOfStaticDataMember(
Larisse Voufo39a1e502013-08-06 01:03:05 +00008763 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Richard Smith77e9e842017-05-09 23:02:10 +00008764 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
8765 MemberClass->setInstantiationOfMemberClass(
8766 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8767 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
8768 MemberEnum->setInstantiationOfMemberEnum(
Richard Smith7d137e32012-03-23 03:33:32 +00008769 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Richard Smith77e9e842017-05-09 23:02:10 +00008770 } else {
8771 llvm_unreachable("unknown member specialization kind");
Douglas Gregor86d142a2009-10-08 07:24:58 +00008772 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008773
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008774 // Save the caller the trouble of having to figure out which declaration
8775 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00008776 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00008777 Previous.addDecl(FoundInstantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008778 return false;
8779}
8780
Richard Smith77e9e842017-05-09 23:02:10 +00008781/// Complete the explicit specialization of a member of a class template by
8782/// updating the instantiated member to be marked as an explicit specialization.
8783///
8784/// \param OrigD The member declaration instantiated from the template.
8785/// \param Loc The location of the explicit specialization of the member.
8786template<typename DeclT>
8787static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
8788 SourceLocation Loc) {
8789 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
8790 return;
8791
8792 // FIXME: Inform AST mutation listeners of this AST mutation.
8793 // FIXME: If there are multiple in-class declarations of the member (from
8794 // multiple modules, or a declaration and later definition of a member type),
8795 // should we update all of them?
8796 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
8797 OrigD->setLocation(Loc);
8798}
8799
8800void Sema::CompleteMemberSpecialization(NamedDecl *Member,
8801 LookupResult &Previous) {
8802 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
8803 if (Instantiation == Member)
8804 return;
8805
8806 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
8807 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
8808 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
8809 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
8810 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
8811 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
8812 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
8813 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
8814 else
8815 llvm_unreachable("unknown member specialization kind");
8816}
8817
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008818/// Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008819///
8820/// \returns true if a serious error occurs, false otherwise.
8821static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00008822 SourceLocation InstLoc,
8823 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00008824 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
8825 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008826
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008827 if (CurContext->isRecord()) {
8828 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
8829 << D;
8830 return true;
8831 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008832
Richard Smith050d2612011-10-18 02:28:33 +00008833 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008834 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00008835 // template. If the name declared in the explicit instantiation is an
8836 // unqualified name, the explicit instantiation shall appear in the
8837 // namespace where its template is declared or, if that namespace is inline
8838 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008839 //
8840 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00008841 if (WasQualifiedName) {
8842 if (CurContext->Encloses(OrigContext))
8843 return false;
8844 } else {
8845 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
8846 return false;
8847 }
8848
8849 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
8850 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008851 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008852 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008853 diag::err_explicit_instantiation_out_of_scope :
8854 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008855 << D << NS;
8856 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008857 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008858 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008859 diag::err_explicit_instantiation_unqualified_wrong_namespace :
8860 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
8861 << D << NS;
8862 } else
8863 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008864 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008865 diag::err_explicit_instantiation_must_be_global :
8866 diag::warn_explicit_instantiation_must_be_global_0x)
8867 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00008868 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008869 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00008870}
8871
Richard Smith0d923af2019-04-26 01:51:07 +00008872/// Common checks for whether an explicit instantiation of \p D is valid.
8873static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D,
8874 SourceLocation InstLoc,
8875 bool WasQualifiedName,
8876 TemplateSpecializationKind TSK) {
8877 // C++ [temp.explicit]p13:
8878 // An explicit instantiation declaration shall not name a specialization of
8879 // a template with internal linkage.
8880 if (TSK == TSK_ExplicitInstantiationDeclaration &&
8881 D->getFormalLinkage() == InternalLinkage) {
8882 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
8883 return true;
8884 }
8885
8886 // C++11 [temp.explicit]p3: [DR 275]
8887 // An explicit instantiation shall appear in an enclosing namespace of its
8888 // template.
8889 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
8890 return true;
8891
8892 return false;
8893}
8894
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008895/// Determine whether the given scope specifier has a template-id in it.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008896static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
8897 if (!SS.isSet())
8898 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008899
Richard Smith050d2612011-10-18 02:28:33 +00008900 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008901 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008902 // or a static data member of a class template specialization, the name of
8903 // the class template specialization in the qualified-id for the member
8904 // name shall be a simple-template-id.
8905 //
8906 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00008907 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
8908 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00008909 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00008910 if (isa<TemplateSpecializationType>(T))
8911 return true;
8912
8913 return false;
8914}
8915
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008916/// Make a dllexport or dllimport attr on a class template specialization take
8917/// effect.
8918static void dllExportImportClassTemplateSpecialization(
8919 Sema &S, ClassTemplateSpecializationDecl *Def) {
8920 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
8921 assert(A && "dllExportImportClassTemplateSpecialization called "
8922 "on Def without dllexport or dllimport");
8923
8924 // We reject explicit instantiations in class scope, so there should
8925 // never be any delayed exported classes to worry about.
8926 assert(S.DelayedDllExportClasses.empty() &&
8927 "delayed exports present at explicit instantiation");
8928 S.checkClassLevelDLLAttribute(Def);
8929
8930 // Propagate attribute to base class templates.
8931 for (auto &B : Def->bases()) {
8932 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
8933 B.getType()->getAsCXXRecordDecl()))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008934 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getBeginLoc());
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008935 }
8936
8937 S.referenceDLLExportedClassMethods();
8938}
8939
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008940// Explicit instantiation of a class template specialization
Erich Keanec480f302018-07-12 21:09:05 +00008941DeclResult Sema::ActOnExplicitInstantiation(
8942 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
8943 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
8944 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
8945 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
8946 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
Douglas Gregora1f49972009-05-13 00:25:59 +00008947 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00008948 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00008949 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00008950 // Check that the specialization uses the same tag kind as the
8951 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00008952 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8953 assert(Kind != TTK_Enum &&
8954 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00008955
Richard Trieu265c3442016-04-05 21:13:54 +00008956 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
8957
8958 if (!ClassTemplate) {
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00008959 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
8960 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
Richard Trieu265c3442016-04-05 21:13:54 +00008961 Diag(TD->getLocation(), diag::note_previous_use);
Richard Smith392497b2013-06-22 22:03:31 +00008962 return true;
8963 }
8964
Douglas Gregord9034f02009-05-14 16:41:31 +00008965 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00008966 Kind, /*isDefinition*/false, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00008967 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00008968 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00008969 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00008970 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00008971 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00008972 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00008973 diag::note_previous_use);
8974 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8975 }
8976
Douglas Gregore47f5a72009-10-14 23:41:34 +00008977 // C++0x [temp.explicit]p2:
8978 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008979 // definition and an explicit instantiation declaration. An explicit
8980 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00008981 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
8982 ? TSK_ExplicitInstantiationDefinition
8983 : TSK_ExplicitInstantiationDeclaration;
8984
Martin Storsjo5be69bc2019-04-26 08:09:51 +00008985 if (TSK == TSK_ExplicitInstantiationDeclaration &&
8986 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
8987 // Check for dllexport class template instantiation declarations,
8988 // except for MinGW mode.
Erich Keanee891aa92018-07-13 15:07:47 +00008989 for (const ParsedAttr &AL : Attr) {
8990 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
Hans Wennborgfd76d912015-01-15 21:18:30 +00008991 Diag(ExternLoc,
8992 diag::warn_attribute_dllexport_explicit_instantiation_decl);
Erich Keanec480f302018-07-12 21:09:05 +00008993 Diag(AL.getLoc(), diag::note_attribute);
Hans Wennborgfd76d912015-01-15 21:18:30 +00008994 break;
8995 }
8996 }
8997
8998 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
8999 Diag(ExternLoc,
9000 diag::warn_attribute_dllexport_explicit_instantiation_decl);
9001 Diag(A->getLocation(), diag::note_attribute);
9002 }
9003 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009004
Hans Wennborga86a83b2016-05-26 19:42:56 +00009005 // In MSVC mode, dllimported explicit instantiation definitions are treated as
9006 // instantiation declarations for most purposes.
9007 bool DLLImportExplicitInstantiationDef = false;
9008 if (TSK == TSK_ExplicitInstantiationDefinition &&
9009 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9010 // Check for dllimport class template instantiation definitions.
9011 bool DLLImport =
9012 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
Erich Keanee891aa92018-07-13 15:07:47 +00009013 for (const ParsedAttr &AL : Attr) {
9014 if (AL.getKind() == ParsedAttr::AT_DLLImport)
Hans Wennborga86a83b2016-05-26 19:42:56 +00009015 DLLImport = true;
Erich Keanee891aa92018-07-13 15:07:47 +00009016 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
Hans Wennborga86a83b2016-05-26 19:42:56 +00009017 // dllexport trumps dllimport here.
9018 DLLImport = false;
9019 break;
9020 }
9021 }
9022 if (DLLImport) {
9023 TSK = TSK_ExplicitInstantiationDeclaration;
9024 DLLImportExplicitInstantiationDef = true;
9025 }
9026 }
9027
Douglas Gregora1f49972009-05-13 00:25:59 +00009028 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00009029 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00009030 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00009031
9032 // Check that the template argument list is well-formed for this
9033 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009034 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00009035 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
Saar Razfdf80e82019-12-06 01:30:21 +02009036 TemplateArgs, false, Converted,
9037 /*UpdateArgsWithConversion=*/true))
Douglas Gregora1f49972009-05-13 00:25:59 +00009038 return true;
9039
Douglas Gregora1f49972009-05-13 00:25:59 +00009040 // Find the class template specialization declaration that
9041 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00009042 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00009043 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00009044 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00009045
Abramo Bagnara8075c852010-06-12 07:44:57 +00009046 TemplateSpecializationKind PrevDecl_TSK
9047 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
9048
Martin Storsjo5be69bc2019-04-26 08:09:51 +00009049 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
9050 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
9051 // Check for dllexport class template instantiation definitions in MinGW
9052 // mode, if a previous declaration of the instantiation was seen.
9053 for (const ParsedAttr &AL : Attr) {
9054 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9055 Diag(AL.getLoc(),
9056 diag::warn_attribute_dllexport_explicit_instantiation_def);
9057 break;
9058 }
9059 }
9060 }
9061
Richard Smith0d923af2019-04-26 01:51:07 +00009062 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
9063 SS.isSet(), TSK))
Douglas Gregor6cc1df52010-07-13 00:10:04 +00009064 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009065
Craig Topperc3ec1492014-05-26 06:22:03 +00009066 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00009067
Abramo Bagnara8075c852010-06-12 07:44:57 +00009068 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00009069 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00009070 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00009071 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00009072 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00009073 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00009074 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00009075
Abramo Bagnara8075c852010-06-12 07:44:57 +00009076 // Even though HasNoEffect == true means that this explicit instantiation
9077 // has no effect on semantics, we go on to put its syntax in the AST.
9078
9079 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
9080 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00009081 // Since the only prior class template specialization with these
9082 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00009083 // declaration node as our own, updating the source location
9084 // for the template name to reflect our new declaration.
9085 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00009086 Specialization = PrevDecl;
9087 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00009088 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00009089 }
Hans Wennborga86a83b2016-05-26 19:42:56 +00009090
9091 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
9092 DLLImportExplicitInstantiationDef) {
9093 // The new specialization might add a dllimport attribute.
9094 HasNoEffect = false;
9095 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00009096 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00009097
Douglas Gregor4aa04b12009-09-11 21:19:12 +00009098 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00009099 // Create a new class template specialization declaration node for
9100 // this explicit specialization.
9101 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00009102 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00009103 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00009104 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00009105 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00009106 Converted,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009107 PrevDecl);
Bruno Ricci4224c872018-12-21 14:35:24 +00009108 SetNestedNameSpecifier(*this, Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00009109
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00009110 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00009111 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00009112 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00009113 }
Douglas Gregora1f49972009-05-13 00:25:59 +00009114 }
9115
9116 // Build the fully-sugared type for this explicit instantiation as
9117 // the user wrote in the explicit instantiation itself. This means
9118 // that we'll pretty-print the type retrieved from the
9119 // specialization's declaration the way that the user actually wrote
9120 // the explicit instantiation, rather than formatting the name based
9121 // on the "canonical" representation used to store the template
9122 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00009123 TypeSourceInfo *WrittenTy
9124 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
9125 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00009126 Context.getTypeDeclType(Specialization));
9127 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00009128
Abramo Bagnara8075c852010-06-12 07:44:57 +00009129 // Set source locations for keywords.
9130 Specialization->setExternLoc(ExternLoc);
9131 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00009132 Specialization->setBraceRange(SourceRange());
Abramo Bagnara8075c852010-06-12 07:44:57 +00009133
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00009134 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
Erich Keanec480f302018-07-12 21:09:05 +00009135 ProcessDeclAttributeList(S, Specialization, Attr);
Rafael Espindola0b062072012-01-03 06:04:21 +00009136
Abramo Bagnara8075c852010-06-12 07:44:57 +00009137 // Add the explicit instantiation into its lexical context. However,
9138 // since explicit instantiations are never found by name lookup, we
9139 // just put it into the declaration context directly.
9140 Specialization->setLexicalDeclContext(CurContext);
9141 CurContext->addDecl(Specialization);
9142
9143 // Syntax is now OK, so return if it has no other effect on semantics.
9144 if (HasNoEffect) {
9145 // Set the template specialization kind.
9146 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00009147 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00009148 }
Douglas Gregora1f49972009-05-13 00:25:59 +00009149
9150 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00009151 // A definition of a class template or class member template
9152 // shall be in scope at the point of the explicit instantiation of
9153 // the class template or class member template.
9154 //
9155 // This check comes when we actually try to perform the
9156 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00009157 ClassTemplateSpecializationDecl *Def
9158 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009159 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00009160 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00009161 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00009162 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00009163 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00009164 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
9165 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00009166
Douglas Gregor1d957a32009-10-27 18:42:08 +00009167 // Instantiate the members of this class template specialization.
9168 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009169 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00009170 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00009171 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00009172 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
9173 // TSK_ExplicitInstantiationDefinition
9174 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborga86a83b2016-05-26 19:42:56 +00009175 (TSK == TSK_ExplicitInstantiationDefinition ||
9176 DLLImportExplicitInstantiationDef)) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00009177 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00009178 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00009179
Hans Wennborgc0875502015-06-09 00:39:05 +00009180 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
Shoaib Meenaiab3f96c2016-11-09 23:52:20 +00009181 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
9182 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
Hans Wennborgc0875502015-06-09 00:39:05 +00009183 // In the MS ABI, an explicit instantiation definition can add a dll
9184 // attribute to a template with a previous instantiation declaration.
9185 // MinGW doesn't allow this.
Hans Wennborg17f9b442015-05-27 00:06:45 +00009186 auto *A = cast<InheritableAttr>(
9187 getDLLAttr(Specialization)->clone(getASTContext()));
9188 A->setInherited(true);
9189 Def->addAttr(A);
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00009190 dllExportImportClassTemplateSpecialization(*this, Def);
Hans Wennborg17f9b442015-05-27 00:06:45 +00009191 }
9192 }
9193
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00009194 // Fix a TSK_ImplicitInstantiation followed by a
9195 // TSK_ExplicitInstantiationDefinition
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00009196 bool NewlyDLLExported =
9197 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
9198 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00009199 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
9200 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
9201 // In the MS ABI, an explicit instantiation definition can add a dll
9202 // attribute to a template with a previous implicit instantiation.
9203 // MinGW doesn't allow this. We limit clang to only adding dllexport, to
9204 // avoid potentially strange codegen behavior. For example, if we extend
9205 // this conditional to dllimport, and we have a source file calling a
9206 // method on an implicitly instantiated template class instance and then
9207 // declaring a dllimport explicit instantiation definition for the same
9208 // template class, the codegen for the method call will not respect the
9209 // dllimport, while it will with cl. The Def will already have the DLL
9210 // attribute, since the Def and Specialization will be the same in the
9211 // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
9212 // attribute to the Specialization; we just need to make it take effect.
9213 assert(Def == Specialization &&
9214 "Def and Specialization should match for implicit instantiation");
9215 dllExportImportClassTemplateSpecialization(*this, Def);
9216 }
9217
Martin Storsjo5be69bc2019-04-26 08:09:51 +00009218 // In MinGW mode, export the template instantiation if the declaration
9219 // was marked dllexport.
9220 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
9221 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
9222 PrevDecl->hasAttr<DLLExportAttr>()) {
9223 dllExportImportClassTemplateSpecialization(*this, Def);
9224 }
9225
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00009226 // Set the template specialization kind. Make sure it is set before
9227 // instantiating the members which will trigger ASTConsumer callbacks.
9228 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregor12e49d32009-10-15 22:53:21 +00009229 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00009230 } else {
9231
9232 // Set the template specialization kind.
9233 Specialization->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00009234 }
Douglas Gregora1f49972009-05-13 00:25:59 +00009235
John McCall48871652010-08-21 09:40:31 +00009236 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00009237}
9238
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009239// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00009240DeclResult
Erich Keanec480f302018-07-12 21:09:05 +00009241Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
9242 SourceLocation TemplateLoc, unsigned TagSpec,
9243 SourceLocation KWLoc, CXXScopeSpec &SS,
9244 IdentifierInfo *Name, SourceLocation NameLoc,
9245 const ParsedAttributesView &Attr) {
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009246
Douglas Gregord6ab8742009-05-28 23:31:59 +00009247 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00009248 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00009249 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00009250 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00009251 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00009252 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00009253 SourceLocation(), false, TypeResult(),
Akira Hatanaka12ddcee2017-06-26 18:46:12 +00009254 /*IsTypeSpecifier*/false,
9255 /*IsTemplateParamOrArg*/false);
John McCall7f41d982009-09-11 04:59:25 +00009256 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
9257
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009258 if (!TagD)
9259 return true;
9260
John McCall48871652010-08-21 09:40:31 +00009261 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00009262 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009263
Douglas Gregorb8006faf2009-05-27 17:30:49 +00009264 if (Tag->isInvalidDecl())
9265 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009266
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009267 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
9268 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
9269 if (!Pattern) {
9270 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
9271 << Context.getTypeDeclType(Record);
9272 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
9273 return true;
9274 }
9275
Douglas Gregore47f5a72009-10-14 23:41:34 +00009276 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009277 // If the explicit instantiation is for a class or member class, the
9278 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00009279 // simple-template-id.
9280 //
9281 // C++98 has the same restriction, just worded differently.
9282 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00009283 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00009284 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009285
Douglas Gregore47f5a72009-10-14 23:41:34 +00009286 // C++0x [temp.explicit]p2:
9287 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009288 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00009289 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00009290 TemplateSpecializationKind TSK
9291 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
9292 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009293
Richard Smith0d923af2019-04-26 01:51:07 +00009294 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009295
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009296 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009297 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00009298 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009299 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00009300 PrevDecl = Record;
9301 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009302 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00009303 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009304 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009305 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009306 PrevDecl,
9307 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009308 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00009309 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009310 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00009311 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009312 return TagD;
9313 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009314
Douglas Gregor12e49d32009-10-15 22:53:21 +00009315 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009316 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00009317 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00009318 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009319 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00009320 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009321 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009322 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00009323 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00009324 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
9325 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00009326 Diag(Pattern->getLocation(), diag::note_forward_declaration)
9327 << Pattern;
9328 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00009329 } else {
9330 if (InstantiateClass(NameLoc, Record, Def,
9331 getTemplateInstantiationArgs(Record),
9332 TSK))
9333 return true;
9334
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009335 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00009336 if (!RecordDef)
9337 return true;
9338 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009339 }
9340
Douglas Gregor1d957a32009-10-27 18:42:08 +00009341 // Instantiate all of the members of the class.
9342 InstantiateClassMembers(NameLoc, RecordDef,
9343 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009344
Douglas Gregor88d292c2010-05-13 16:44:06 +00009345 if (TSK == TSK_ExplicitInstantiationDefinition)
9346 MarkVTableUsed(NameLoc, RecordDef, true);
9347
Mike Stump87c57ac2009-05-16 07:39:55 +00009348 // FIXME: We don't have any representation for explicit instantiations of
9349 // member classes. Such a representation is not needed for compilation, but it
9350 // should be available for clients that want to see all of the declarations in
9351 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009352 return TagD;
9353}
9354
John McCallfaf5fb42010-08-26 23:41:50 +00009355DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
9356 SourceLocation ExternLoc,
9357 SourceLocation TemplateLoc,
9358 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00009359 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009360 // TODO: check if/when DNInfo should replace Name.
9361 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9362 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00009363 if (!Name) {
9364 if (!D.isInvalidType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009365 Diag(D.getDeclSpec().getBeginLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00009366 diag::err_explicit_instantiation_requires_name)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009367 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009368
Douglas Gregor450f00842009-09-25 18:43:00 +00009369 return true;
9370 }
9371
9372 // The scope passed in may not be a decl scope. Zip up the scope tree until
9373 // we find one that is.
9374 while ((S->getFlags() & Scope::DeclScope) == 0 ||
9375 (S->getFlags() & Scope::TemplateParamScope) != 0)
9376 S = S->getParent();
9377
9378 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00009379 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
9380 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00009381 if (R.isNull())
9382 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009383
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009384 // C++ [dcl.stc]p1:
Simon Pilgrim6905d222016-12-30 22:55:33 +00009385 // A storage-class-specifier shall not be specified in [...] an explicit
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009386 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00009387 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00009388 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
9389 << Name;
9390 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009391 } else if (D.getDeclSpec().getStorageClassSpec()
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009392 != DeclSpec::SCS_unspecified) {
9393 // Complain about then remove the storage class specifier.
9394 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
9395 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009396
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009397 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00009398 }
9399
Douglas Gregor3c74d412009-10-14 20:14:33 +00009400 // C++0x [temp.explicit]p1:
9401 // [...] An explicit instantiation of a function template shall not use the
9402 // inline or constexpr specifiers.
9403 // Presumably, this also applies to member functions of class templates as
9404 // well.
Richard Smith83c19292011-10-18 03:44:03 +00009405 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009406 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009407 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00009408 diag::err_explicit_instantiation_inline :
9409 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00009410 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Gauthier Harnisch796ed032019-06-14 08:56:20 +00009411 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00009412 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
9413 // not already specified.
9414 Diag(D.getDeclSpec().getConstexprSpecLoc(),
9415 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009416
Richard Smith19a311a2017-02-09 22:47:51 +00009417 // A deduction guide is not on the list of entities that can be explicitly
9418 // instantiated.
9419 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009420 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
9421 << /*explicit instantiation*/ 0;
Richard Smith19a311a2017-02-09 22:47:51 +00009422 return true;
9423 }
9424
Douglas Gregore47f5a72009-10-14 23:41:34 +00009425 // C++0x [temp.explicit]p2:
9426 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009427 // definition and an explicit instantiation declaration. An explicit
9428 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00009429 TemplateSpecializationKind TSK
9430 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
9431 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009432
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009433 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00009434 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00009435
9436 if (!R->isFunctionType()) {
9437 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009438 // A [...] static data member of a class template can be explicitly
9439 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00009440 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00009441 // C++1y [temp.explicit]p1:
9442 // A [...] variable [...] template specialization can be explicitly
9443 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00009444 if (Previous.isAmbiguous())
9445 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009446
John McCall67c00872009-12-02 08:25:40 +00009447 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00009448 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009449
Larisse Voufo39a1e502013-08-06 01:03:05 +00009450 if (!PrevTemplate) {
9451 if (!Prev || !Prev->isStaticDataMember()) {
Richard Smitha6b41d72019-05-03 23:51:38 +00009452 // We expect to see a static data member here.
Larisse Voufo39a1e502013-08-06 01:03:05 +00009453 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
9454 << Name;
9455 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9456 P != PEnd; ++P)
9457 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
9458 return true;
9459 }
9460
9461 if (!Prev->getInstantiatedFromStaticDataMember()) {
9462 // FIXME: Check for explicit specialization?
9463 Diag(D.getIdentifierLoc(),
9464 diag::err_explicit_instantiation_data_member_not_instantiated)
9465 << Prev;
9466 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
9467 // FIXME: Can we provide a note showing where this was declared?
9468 return true;
9469 }
9470 } else {
9471 // Explicitly instantiate a variable template.
9472
9473 // C++1y [dcl.spec.auto]p6:
9474 // ... A program that uses auto or decltype(auto) in a context not
9475 // explicitly allowed in this section is ill-formed.
9476 //
9477 // This includes auto-typed variable template instantiations.
9478 if (R->isUndeducedType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009479 Diag(T->getTypeLoc().getBeginLoc(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00009480 diag::err_auto_not_allowed_var_inst);
9481 return true;
9482 }
9483
Faisal Vali2ab8c152017-12-30 04:15:27 +00009484 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
Richard Smithef985ac2013-09-18 02:10:12 +00009485 // C++1y [temp.explicit]p3:
9486 // If the explicit instantiation is for a variable, the unqualified-id
9487 // in the declaration shall be a template-id.
9488 Diag(D.getIdentifierLoc(),
9489 diag::err_explicit_instantiation_without_template_id)
9490 << PrevTemplate;
9491 Diag(PrevTemplate->getLocation(),
9492 diag::note_explicit_instantiation_here);
9493 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00009494 }
9495
Richard Smithef985ac2013-09-18 02:10:12 +00009496 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00009497 TemplateArgumentListInfo TemplateArgs =
9498 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00009499
Larisse Voufo39a1e502013-08-06 01:03:05 +00009500 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
9501 D.getIdentifierLoc(), TemplateArgs);
9502 if (Res.isInvalid())
9503 return true;
9504
9505 // Ignore access control bits, we don't need them for redeclaration
9506 // checking.
9507 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00009508 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009509
Douglas Gregore47f5a72009-10-14 23:41:34 +00009510 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009511 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00009512 // or a static data member of a class template specialization, the name of
9513 // the class template specialization in the qualified-id for the member
9514 // name shall be a simple-template-id.
9515 //
9516 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00009517 //
Richard Smith5977d872013-09-18 21:55:14 +00009518 // This does not apply to variable template specializations, where the
9519 // template-id is in the unqualified-id instead.
9520 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009521 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00009522 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00009523 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009524
Richard Smith0d923af2019-04-26 01:51:07 +00009525 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009526
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009527 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00009528 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
9529 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00009530 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00009531 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00009532 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009533 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009534
Larisse Voufo39a1e502013-08-06 01:03:05 +00009535 if (!HasNoEffect) {
9536 // Instantiate static data member or variable template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00009537 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Louis Dionnee6e81752018-10-10 15:32:29 +00009538 // Merge attributes.
9539 ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
Larisse Voufo39a1e502013-08-06 01:03:05 +00009540 if (TSK == TSK_ExplicitInstantiationDefinition)
9541 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
9542 }
9543
9544 // Check the new variable specialization against the parsed input.
9545 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009546 Diag(T->getTypeLoc().getBeginLoc(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00009547 diag::err_invalid_var_template_spec_type)
9548 << 0 << PrevTemplate << R << Prev->getType();
9549 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
9550 << 2 << PrevTemplate->getDeclName();
9551 return true;
9552 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009553
Douglas Gregor450f00842009-09-25 18:43:00 +00009554 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00009555 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009556 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009557
9558 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00009559 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00009560 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00009561 TemplateArgumentListInfo TemplateArgs;
Faisal Vali2ab8c152017-12-30 04:15:27 +00009562 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00009563 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00009564 HasExplicitTemplateArgs = true;
9565 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009566
Douglas Gregor450f00842009-09-25 18:43:00 +00009567 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009568 // A [...] function [...] can be explicitly instantiated from its template.
9569 // A member function [...] of a class template can be explicitly
9570 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00009571 // template.
John McCall27c11dd2017-06-07 23:00:05 +00009572 UnresolvedSet<8> TemplateMatches;
9573 FunctionDecl *NonTemplateMatch = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009574 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00009575 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9576 P != PEnd; ++P) {
9577 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00009578 if (!HasExplicitTemplateArgs) {
9579 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Richard Smithbaa47832016-12-01 02:11:49 +00009580 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
9581 /*AdjustExceptionSpec*/true);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00009582 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
John McCall27c11dd2017-06-07 23:00:05 +00009583 if (Method->getPrimaryTemplate()) {
9584 TemplateMatches.addDecl(Method, P.getAccess());
9585 } else {
9586 // FIXME: Can this assert ever happen? Needs a test.
9587 assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
9588 NonTemplateMatch = Method;
9589 }
Douglas Gregord90fd522009-09-25 21:45:23 +00009590 }
Douglas Gregor450f00842009-09-25 18:43:00 +00009591 }
9592 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009593
Douglas Gregor450f00842009-09-25 18:43:00 +00009594 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
9595 if (!FunTmpl)
9596 continue;
9597
Larisse Voufo98b20f12013-07-19 23:00:19 +00009598 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00009599 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009600 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009601 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00009602 (HasExplicitTemplateArgs ? &TemplateArgs
9603 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00009604 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009605 // Keep track of almost-matches.
9606 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +00009607 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +00009608 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00009609 (void)TDK;
9610 continue;
9611 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009612
Artem Belevich64135c32016-12-08 19:38:13 +00009613 // Target attributes are part of the cuda function signature, so
9614 // the cuda target of the instantiated function must match that of its
9615 // template. Given that C++ template deduction does not take
9616 // target attributes into account, we reject candidates here that
9617 // have a different target.
9618 if (LangOpts.CUDA &&
9619 IdentifyCUDATarget(Specialization,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00009620 /* IgnoreImplicitHDAttr = */ true) !=
Erich Keanec480f302018-07-12 21:09:05 +00009621 IdentifyCUDATarget(D.getDeclSpec().getAttributes())) {
Artem Belevich64135c32016-12-08 19:38:13 +00009622 FailedCandidates.addCandidate().set(
9623 P.getPair(), FunTmpl->getTemplatedDecl(),
9624 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
9625 continue;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00009626 }
9627
John McCall27c11dd2017-06-07 23:00:05 +00009628 TemplateMatches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00009629 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009630
John McCall27c11dd2017-06-07 23:00:05 +00009631 FunctionDecl *Specialization = NonTemplateMatch;
9632 if (!Specialization) {
9633 // Find the most specialized function template specialization.
9634 UnresolvedSetIterator Result = getMostSpecialized(
9635 TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
9636 D.getIdentifierLoc(),
9637 PDiag(diag::err_explicit_instantiation_not_known) << Name,
9638 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
9639 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00009640
John McCall27c11dd2017-06-07 23:00:05 +00009641 if (Result == TemplateMatches.end())
9642 return true;
John McCall58cc69d2010-01-27 01:50:18 +00009643
John McCall27c11dd2017-06-07 23:00:05 +00009644 // Ignore access control bits, we don't need them for redeclaration checking.
9645 Specialization = cast<FunctionDecl>(*Result);
9646 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009647
Alexey Bataev73983912014-11-06 10:10:50 +00009648 // C++11 [except.spec]p4
9649 // In an explicit instantiation an exception-specification may be specified,
9650 // but is not required.
9651 // If an exception-specification is specified in an explicit instantiation
9652 // directive, it shall be compatible with the exception-specifications of
9653 // other declarations of that function.
9654 if (auto *FPT = R->getAs<FunctionProtoType>())
9655 if (FPT->hasExceptionSpec()) {
9656 unsigned DiagID =
9657 diag::err_mismatched_exception_spec_explicit_instantiation;
9658 if (getLangOpts().MicrosoftExt)
9659 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
9660 bool Result = CheckEquivalentExceptionSpec(
9661 PDiag(DiagID) << Specialization->getType(),
9662 PDiag(diag::note_explicit_instantiation_here),
9663 Specialization->getType()->getAs<FunctionProtoType>(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009664 Specialization->getLocation(), FPT, D.getBeginLoc());
Alexey Bataev73983912014-11-06 10:10:50 +00009665 // In Microsoft mode, mismatching exception specifications just cause a
9666 // warning.
9667 if (!getLangOpts().MicrosoftExt && Result)
9668 return true;
9669 }
9670
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009671 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009672 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00009673 diag::err_explicit_instantiation_member_function_not_instantiated)
9674 << Specialization
9675 << (Specialization->getTemplateSpecializationKind() ==
9676 TSK_ExplicitSpecialization);
9677 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
9678 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009679 }
9680
Douglas Gregorec9fd132012-01-14 16:38:05 +00009681 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00009682 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
9683 PrevDecl = Specialization;
9684
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009685 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00009686 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00009687 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009688 PrevDecl,
9689 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009690 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00009691 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009692 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009693
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009694 // FIXME: We may still want to build some representation of this
9695 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00009696 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00009697 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009698 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00009699
Richard Smith0d923af2019-04-26 01:51:07 +00009700 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
9701 // functions
9702 // valarray<size_t>::valarray(size_t) and
9703 // valarray<size_t>::~valarray()
9704 // that it declared to have internal linkage with the internal_linkage
9705 // attribute. Ignore the explicit instantiation declaration in this case.
9706 if (Specialization->hasAttr<InternalLinkageAttr>() &&
9707 TSK == TSK_ExplicitInstantiationDeclaration) {
9708 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
9709 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
9710 RD->isInStdNamespace())
9711 return (Decl*) nullptr;
9712 }
9713
Erich Keanec480f302018-07-12 21:09:05 +00009714 ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009715
Hans Wennborgb8304a62017-11-29 23:44:11 +00009716 // In MSVC mode, dllimported explicit instantiation definitions are treated as
9717 // instantiation declarations.
9718 if (TSK == TSK_ExplicitInstantiationDefinition &&
9719 Specialization->hasAttr<DLLImportAttr>() &&
9720 Context.getTargetInfo().getCXXABI().isMicrosoft())
9721 TSK = TSK_ExplicitInstantiationDeclaration;
9722
9723 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9724
Richard Smitheb36ddf2014-04-24 22:45:46 +00009725 if (Specialization->isDefined()) {
9726 // Let the ASTConsumer know that this function has been explicitly
9727 // instantiated now, and its linkage might have changed.
9728 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
9729 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00009730 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009731
Douglas Gregore47f5a72009-10-14 23:41:34 +00009732 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009733 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00009734 // or a static data member of a class template specialization, the name of
9735 // the class template specialization in the qualified-id for the member
9736 // name shall be a simple-template-id.
9737 //
9738 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009739 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Faisal Vali2ab8c152017-12-30 04:15:27 +00009740 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009741 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00009742 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009743 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00009744 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00009745 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009746
Richard Smith0d923af2019-04-26 01:51:07 +00009747 CheckExplicitInstantiation(
9748 *this,
9749 FunTmpl ? (NamedDecl *)FunTmpl
9750 : Specialization->getInstantiatedFromMemberFunction(),
9751 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009752
Douglas Gregor450f00842009-09-25 18:43:00 +00009753 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00009754 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009755}
9756
John McCallfaf5fb42010-08-26 23:41:50 +00009757TypeResult
Faisal Vali090da2d2018-01-01 18:23:28 +00009758Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
John McCall7f41d982009-09-11 04:59:25 +00009759 const CXXScopeSpec &SS, IdentifierInfo *Name,
9760 SourceLocation TagLoc, SourceLocation NameLoc) {
9761 // This has to hold, because SS is expected to be defined.
9762 assert(Name && "Expected a name in a dependent tag");
9763
Aaron Ballman4a979672014-01-03 13:56:08 +00009764 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00009765 if (!NNS)
9766 return true;
9767
Abramo Bagnara6150c882010-05-11 21:36:43 +00009768 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00009769
Douglas Gregorba41d012010-04-24 16:38:41 +00009770 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
9771 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00009772 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00009773 return true;
9774 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00009775
Douglas Gregore7c20652011-03-02 00:47:37 +00009776 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00009777 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00009778 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009779
Douglas Gregore7c20652011-03-02 00:47:37 +00009780 // Create type-source location information for this type.
9781 TypeLocBuilder TLB;
9782 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009783 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00009784 TL.setQualifierLoc(SS.getWithLocInContext(Context));
9785 TL.setNameLoc(NameLoc);
9786 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00009787}
9788
John McCallfaf5fb42010-08-26 23:41:50 +00009789TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009790Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
9791 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00009792 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009793 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00009794 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009795
Richard Smith0bf8a4922011-10-18 20:49:44 +00009796 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9797 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009798 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00009799 diag::warn_cxx98_compat_typename_outside_of_template :
9800 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009801 << FixItHint::CreateRemoval(TypenameLoc);
9802
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009803 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00009804 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
9805 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00009806 if (T.isNull())
9807 return true;
John McCall99b2fe52010-04-29 23:50:39 +00009808
9809 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9810 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00009811 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009812 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009813 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00009814 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00009815 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00009816 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009817 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009818 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00009819 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00009820 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009821
John McCallba7bf592010-08-24 05:47:05 +00009822 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00009823}
9824
John McCallfaf5fb42010-08-26 23:41:50 +00009825TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009826Sema::ActOnTypenameType(Scope *S,
9827 SourceLocation TypenameLoc,
9828 const CXXScopeSpec &SS,
9829 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00009830 TemplateTy TemplateIn,
Richard Smith74f02342017-01-19 21:00:13 +00009831 IdentifierInfo *TemplateII,
9832 SourceLocation TemplateIILoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00009833 SourceLocation LAngleLoc,
9834 ASTTemplateArgsPtr TemplateArgsIn,
9835 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00009836 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9837 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009838 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00009839 diag::warn_cxx98_compat_typename_outside_of_template :
9840 diag::ext_typename_outside_of_template)
9841 << FixItHint::CreateRemoval(TypenameLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009842
Richard Smith74f02342017-01-19 21:00:13 +00009843 // Strangely, non-type results are not ignored by this lookup, so the
9844 // program is ill-formed if it finds an injected-class-name.
Richard Smith62559bd2017-02-01 21:36:38 +00009845 if (TypenameLoc.isValid()) {
9846 auto *LookupRD =
9847 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
9848 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
9849 Diag(TemplateIILoc,
9850 diag::ext_out_of_line_qualified_id_type_names_constructor)
9851 << TemplateII << 0 /*injected-class-name used as template name*/
9852 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
9853 }
Richard Smith74f02342017-01-19 21:00:13 +00009854 }
9855
Douglas Gregorb09518c2011-02-27 22:46:49 +00009856 // Translate the parser's template argument list in our AST format.
9857 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9858 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009859
Douglas Gregorb09518c2011-02-27 22:46:49 +00009860 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009861 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
9862 // Construct a dependent template specialization type.
9863 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00009864 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009865 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
9866 DTN->getQualifier(),
9867 DTN->getIdentifier(),
9868 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009869
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009870 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00009871 TypeLocBuilder Builder;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009872 DependentTemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009873 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009874 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
9875 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00009876 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00009877 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009878 SpecTL.setLAngleLoc(LAngleLoc);
9879 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009880 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9881 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009882 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00009883 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009884
Richard Smith74f02342017-01-19 21:00:13 +00009885 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009886 if (T.isNull())
9887 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009888
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009889 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00009890 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009891 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009892 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009893 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00009894 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009895 SpecTL.setLAngleLoc(LAngleLoc);
9896 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009897 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9898 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009899
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009900 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
9901 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009902 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009903 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Simon Pilgrim6905d222016-12-30 22:55:33 +00009904
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009905 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
9906 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00009907}
9908
Douglas Gregorb09518c2011-02-27 22:46:49 +00009909
Richard Smith6f8d2c62012-05-09 05:17:00 +00009910/// Determine whether this failed name lookup should be treated as being
9911/// disabled by a usage of std::enable_if.
9912static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009913 SourceRange &CondRange, Expr *&Cond) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00009914 // We must be looking for a ::type...
9915 if (!II.isStr("type"))
9916 return false;
9917
9918 // ... within an explicitly-written template specialization...
9919 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
9920 return false;
9921 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00009922 TemplateSpecializationTypeLoc EnableIfTSTLoc =
9923 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
9924 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00009925 return false;
George Burgess IV00f70bd2018-03-01 05:43:23 +00009926 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009927
9928 // ... which names a complete class template declaration...
9929 const TemplateDecl *EnableIfDecl =
9930 EnableIfTST->getTemplateName().getAsTemplateDecl();
9931 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
9932 return false;
9933
9934 // ... called "enable_if".
9935 const IdentifierInfo *EnableIfII =
9936 EnableIfDecl->getDeclName().getAsIdentifierInfo();
9937 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
9938 return false;
9939
9940 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00009941 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009942
9943 // Dig out the condition.
9944 Cond = nullptr;
9945 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
9946 != TemplateArgument::Expression)
9947 return true;
9948
9949 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
9950
9951 // Ignore Boolean literals; they add no value.
9952 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
9953 Cond = nullptr;
9954
Richard Smith6f8d2c62012-05-09 05:17:00 +00009955 return true;
9956}
9957
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009958/// Build the type that describes a C++ typename specifier,
Douglas Gregor333489b2009-03-27 23:10:48 +00009959/// e.g., "typename T::type".
9960QualType
Simon Pilgrim6905d222016-12-30 22:55:33 +00009961Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009962 SourceLocation KeywordLoc,
Simon Pilgrim6905d222016-12-30 22:55:33 +00009963 NestedNameSpecifierLoc QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009964 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00009965 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00009966 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009967 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00009968
John McCall0b66eb32010-05-01 00:40:08 +00009969 DeclContext *Ctx = computeDeclContext(SS);
9970 if (!Ctx) {
9971 // If the nested-name-specifier is dependent and couldn't be
9972 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009973 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009974 return Context.getDependentNameType(Keyword,
9975 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009976 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00009977 }
Douglas Gregor333489b2009-03-27 23:10:48 +00009978
John McCall0b66eb32010-05-01 00:40:08 +00009979 // If the nested-name-specifier refers to the current instantiation,
9980 // the "typename" keyword itself is superfluous. In C++03, the
9981 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
9982 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00009983 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00009984
John McCall0b66eb32010-05-01 00:40:08 +00009985 if (RequireCompleteDeclContext(SS, Ctx))
9986 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00009987
9988 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00009989 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00009990 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00009991 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00009992 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00009993 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00009994 case LookupResult::NotFound: {
9995 // If we're looking up 'type' within a template named 'enable_if', produce
9996 // a more specific diagnostic.
9997 SourceRange CondRange;
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009998 Expr *Cond = nullptr;
9999 if (isEnableIf(QualifierLoc, II, CondRange, Cond)) {
10000 // If we have a condition, narrow it down to the specific failed
10001 // condition.
10002 if (Cond) {
10003 Expr *FailedCond;
10004 std::string FailedDescription;
10005 std::tie(FailedCond, FailedDescription) =
Clement Courbetf44c6f42018-12-11 08:39:11 +000010006 findFailedBooleanCondition(Cond);
Douglas Gregor00fa10b2017-07-05 20:20:14 +000010007
10008 Diag(FailedCond->getExprLoc(),
10009 diag::err_typename_nested_not_found_requirement)
10010 << FailedDescription
10011 << FailedCond->getSourceRange();
10012 return QualType();
10013 }
10014
Richard Smith6f8d2c62012-05-09 05:17:00 +000010015 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
Douglas Gregor00fa10b2017-07-05 20:20:14 +000010016 << Ctx << CondRange;
Richard Smith6f8d2c62012-05-09 05:17:00 +000010017 return QualType();
10018 }
10019
Douglas Gregore40876a2009-10-13 21:16:44 +000010020 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +000010021 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +000010022 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +000010023
10024 case LookupResult::FoundUnresolvedValue: {
10025 // We found a using declaration that is a value. Most likely, the using
10026 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000010027 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +000010028 IILoc);
10029 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
10030 << Name << Ctx << FullRange;
10031 if (UnresolvedUsingValueDecl *Using
10032 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +000010033 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +000010034 Diag(Loc, diag::note_using_value_decl_missing_typename)
10035 << FixItHint::CreateInsertion(Loc, "typename ");
10036 }
10037 }
10038 // Fall through to create a dependent typename type, from which we can recover
10039 // better.
Galina Kistanova3779cb32017-06-07 06:25:05 +000010040 LLVM_FALLTHROUGH;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010041
Douglas Gregord0d2ee02010-01-15 01:44:47 +000010042 case LookupResult::NotFoundInCurrentInstantiation:
10043 // Okay, it's a member of an unknown instantiation.
Simon Pilgrim6905d222016-12-30 22:55:33 +000010044 return Context.getDependentNameType(Keyword,
10045 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000010046 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +000010047
10048 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010049 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Richard Smith74f02342017-01-19 21:00:13 +000010050 // C++ [class.qual]p2:
10051 // In a lookup in which function names are not ignored and the
10052 // nested-name-specifier nominates a class C, if the name specified
10053 // after the nested-name-specifier, when looked up in C, is the
10054 // injected-class-name of C [...] then the name is instead considered
10055 // to name the constructor of class C.
10056 //
10057 // Unlike in an elaborated-type-specifier, function names are not ignored
10058 // in typename-specifier lookup. However, they are ignored in all the
10059 // contexts where we form a typename type with no keyword (that is, in
10060 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
10061 //
10062 // FIXME: That's not strictly true: mem-initializer-id lookup does not
10063 // ignore functions, but that appears to be an oversight.
10064 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
10065 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
10066 if (Keyword == ETK_Typename && LookupRD && FoundRD &&
10067 FoundRD->isInjectedClassName() &&
10068 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
10069 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
10070 << &II << 1 << 0 /*'typename' keyword used*/;
10071
Abramo Bagnara6150c882010-05-11 21:36:43 +000010072 // We found a type. Build an ElaboratedType, since the
10073 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +000010074 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Richard Smith74f02342017-01-19 21:00:13 +000010075 return Context.getElaboratedType(Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000010076 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +000010077 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +000010078 }
10079
Richard Smithee579842017-01-30 20:39:26 +000010080 // C++ [dcl.type.simple]p2:
10081 // A type-specifier of the form
10082 // typename[opt] nested-name-specifier[opt] template-name
10083 // is a placeholder for a deduced class type [...].
Aaron Ballmanc351fba2017-12-04 20:27:34 +000010084 if (getLangOpts().CPlusPlus17) {
Richard Smithee579842017-01-30 20:39:26 +000010085 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
10086 return Context.getElaboratedType(
10087 Keyword, QualifierLoc.getNestedNameSpecifier(),
10088 Context.getDeducedTemplateSpecializationType(TemplateName(TD),
10089 QualType(), false));
10090 }
10091 }
Richard Smith600b5262017-01-26 20:40:47 +000010092
Douglas Gregor333489b2009-03-27 23:10:48 +000010093 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +000010094 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +000010095 break;
10096
10097 case LookupResult::FoundOverloaded:
10098 DiagID = diag::err_typename_nested_not_type;
10099 Referenced = *Result.begin();
10100 break;
10101
John McCall6538c932009-10-10 05:48:19 +000010102 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +000010103 return QualType();
10104 }
10105
10106 // If we get here, it's because name lookup did not find a
10107 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000010108 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +000010109 IILoc);
10110 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +000010111 if (Referenced)
10112 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
10113 << Name;
10114 return QualType();
10115}
Douglas Gregor15acfb92009-08-06 16:20:37 +000010116
10117namespace {
10118 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +000010119 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +000010120 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +000010121 SourceLocation Loc;
10122 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +000010123
Douglas Gregor15acfb92009-08-06 16:20:37 +000010124 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +000010125 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010126
Mike Stump11289f42009-09-09 15:08:12 +000010127 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +000010128 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +000010129 DeclarationName Entity)
10130 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +000010131 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +000010132
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010133 /// Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +000010134 /// transformed.
10135 ///
10136 /// For the purposes of type reconstruction, a type has already been
10137 /// transformed if it is NULL or if it is not dependent.
10138 bool AlreadyTransformed(QualType T) {
10139 return T.isNull() || !T->isDependentType();
10140 }
Mike Stump11289f42009-09-09 15:08:12 +000010141
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010142 /// Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +000010143 /// rebuilt.
10144 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +000010145
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010146 /// Returns the name of the entity whose type is being rebuilt.
Douglas Gregor15acfb92009-08-06 16:20:37 +000010147 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +000010148
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010149 /// Sets the "base" location and entity when that
Douglas Gregoref6ab412009-10-27 06:26:26 +000010150 /// information is known based on another transformation.
10151 void setBase(SourceLocation Loc, DeclarationName Entity) {
10152 this->Loc = Loc;
10153 this->Entity = Entity;
10154 }
Simon Pilgrim6905d222016-12-30 22:55:33 +000010155
Douglas Gregor0c46b2b2012-02-13 22:00:16 +000010156 ExprResult TransformLambdaExpr(LambdaExpr *E) {
10157 // Lambdas never need to be transformed.
10158 return E;
10159 }
Douglas Gregor15acfb92009-08-06 16:20:37 +000010160 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010161} // end anonymous namespace
Douglas Gregor15acfb92009-08-06 16:20:37 +000010162
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010163/// Rebuilds a type within the context of the current instantiation.
Douglas Gregor15acfb92009-08-06 16:20:37 +000010164///
Mike Stump11289f42009-09-09 15:08:12 +000010165/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +000010166/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +000010167/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +000010168/// partial specialization thereof). This routine will rebuild that type now
10169/// that we have entered the declarator's scope, which may produce different
10170/// canonical types, e.g.,
10171///
10172/// \code
10173/// template<typename T>
10174/// struct X {
10175/// typedef T* pointer;
10176/// pointer data();
10177/// };
10178///
10179/// template<typename T>
10180/// typename X<T>::pointer X<T>::data() { ... }
10181/// \endcode
10182///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +000010183/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +000010184/// since we do not know that we can look into X<T> when we parsed the type.
10185/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +000010186/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +000010187/// as the canonical type of T*, allowing the return types of the out-of-line
10188/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +000010189TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
10190 SourceLocation Loc,
10191 DeclarationName Name) {
10192 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +000010193 return T;
Mike Stump11289f42009-09-09 15:08:12 +000010194
Douglas Gregor15acfb92009-08-06 16:20:37 +000010195 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
10196 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +000010197}
Douglas Gregorbe999392009-09-15 16:23:51 +000010198
John McCalldadc5752010-08-24 06:29:42 +000010199ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +000010200 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
10201 DeclarationName());
10202 return Rebuilder.TransformExpr(E);
10203}
10204
John McCall99b2fe52010-04-29 23:50:39 +000010205bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Simon Pilgrim6905d222016-12-30 22:55:33 +000010206 if (SS.isInvalid())
Douglas Gregor10176412011-02-25 16:07:42 +000010207 return true;
John McCall2408e322010-04-27 00:57:59 +000010208
Douglas Gregor10176412011-02-25 16:07:42 +000010209 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +000010210 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
10211 DeclarationName());
Simon Pilgrim6905d222016-12-30 22:55:33 +000010212 NestedNameSpecifierLoc Rebuilt
Douglas Gregor10176412011-02-25 16:07:42 +000010213 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +000010214 if (!Rebuilt)
Douglas Gregor10176412011-02-25 16:07:42 +000010215 return true;
John McCall99b2fe52010-04-29 23:50:39 +000010216
Douglas Gregor10176412011-02-25 16:07:42 +000010217 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +000010218 return false;
John McCall2408e322010-04-27 00:57:59 +000010219}
10220
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010221/// Rebuild the template parameters now that we know we're in a current
Douglas Gregor041b0842011-10-14 15:31:12 +000010222/// instantiation.
10223bool Sema::RebuildTemplateParamsInCurrentInstantiation(
10224 TemplateParameterList *Params) {
10225 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
10226 Decl *Param = Params->getParam(I);
Simon Pilgrim6905d222016-12-30 22:55:33 +000010227
Douglas Gregor041b0842011-10-14 15:31:12 +000010228 // There is nothing to rebuild in a type parameter.
10229 if (isa<TemplateTypeParmDecl>(Param))
10230 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +000010231
Douglas Gregor041b0842011-10-14 15:31:12 +000010232 // Rebuild the template parameter list of a template template parameter.
Simon Pilgrim6905d222016-12-30 22:55:33 +000010233 if (TemplateTemplateParmDecl *TTP
Douglas Gregor041b0842011-10-14 15:31:12 +000010234 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
10235 if (RebuildTemplateParamsInCurrentInstantiation(
10236 TTP->getTemplateParameters()))
10237 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +000010238
Douglas Gregor041b0842011-10-14 15:31:12 +000010239 continue;
10240 }
Simon Pilgrim6905d222016-12-30 22:55:33 +000010241
Douglas Gregor041b0842011-10-14 15:31:12 +000010242 // Rebuild the type of a non-type template parameter.
10243 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
Simon Pilgrim6905d222016-12-30 22:55:33 +000010244 TypeSourceInfo *NewTSI
10245 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
10246 NTTP->getLocation(),
Douglas Gregor041b0842011-10-14 15:31:12 +000010247 NTTP->getDeclName());
10248 if (!NewTSI)
10249 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +000010250
Erik Pilkington9f9462a2018-08-07 22:59:02 +000010251 if (NewTSI->getType()->isUndeducedType()) {
10252 // C++17 [temp.dep.expr]p3:
10253 // An id-expression is type-dependent if it contains
10254 // - an identifier associated by name lookup with a non-type
10255 // template-parameter declared with a type that contains a
10256 // placeholder type (7.1.7.4),
10257 NewTSI = SubstAutoTypeSourceInfo(NewTSI, Context.DependentTy);
10258 }
10259
Douglas Gregor041b0842011-10-14 15:31:12 +000010260 if (NewTSI != NTTP->getTypeSourceInfo()) {
10261 NTTP->setTypeSourceInfo(NewTSI);
10262 NTTP->setType(NewTSI->getType());
10263 }
10264 }
Simon Pilgrim6905d222016-12-30 22:55:33 +000010265
Douglas Gregor041b0842011-10-14 15:31:12 +000010266 return false;
10267}
10268
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010269/// Produces a formatted string that describes the binding of
Douglas Gregorbe999392009-09-15 16:23:51 +000010270/// template parameters to template arguments.
10271std::string
10272Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
10273 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +000010274 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +000010275}
10276
10277std::string
10278Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
10279 const TemplateArgument *Args,
10280 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000010281 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +000010282 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +000010283
Douglas Gregore62e6a02009-11-11 19:13:48 +000010284 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +000010285 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010286
Douglas Gregorbe999392009-09-15 16:23:51 +000010287 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +000010288 if (I >= NumArgs)
10289 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010290
Douglas Gregorbe999392009-09-15 16:23:51 +000010291 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +000010292 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +000010293 else
Douglas Gregor0192c232010-12-20 16:52:59 +000010294 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010295
Douglas Gregorbe999392009-09-15 16:23:51 +000010296 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +000010297 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +000010298 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +000010299 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +000010300 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010301
Douglas Gregor0192c232010-12-20 16:52:59 +000010302 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +000010303 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +000010304 }
Douglas Gregor0192c232010-12-20 16:52:59 +000010305
10306 Out << ']';
10307 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +000010308}
Francois Pichet1c229c02011-04-22 22:18:13 +000010309
Richard Smithe40f2ba2013-08-07 21:41:30 +000010310void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
10311 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +000010312 if (!FD)
10313 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +000010314
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +000010315 auto LPT = std::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +000010316
10317 // Take tokens to avoid allocations
10318 LPT->Toks.swap(Toks);
10319 LPT->D = FnD;
Justin Lebar28f09c52016-10-10 16:26:08 +000010320 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +000010321
10322 FD->setLateTemplateParsed(true);
10323}
10324
10325void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
10326 if (!FD)
10327 return;
10328 FD->setLateTemplateParsed(false);
10329}
Francois Pichet1c229c02011-04-22 22:18:13 +000010330
10331bool Sema::IsInsideALocalClassWithinATemplateFunction() {
10332 DeclContext *DC = CurContext;
10333
10334 while (DC) {
10335 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
10336 const FunctionDecl *FD = RD->isLocalClass();
10337 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
10338 } else if (DC->isTranslationUnit() || DC->isNamespace())
10339 return false;
10340
10341 DC = DC->getParent();
10342 }
10343 return false;
10344}
Richard Smith6739a102016-05-05 00:56:12 +000010345
Benjamin Kramera0a13c32016-08-06 11:21:04 +000010346namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010347/// Walk the path from which a declaration was instantiated, and check
Richard Smith6739a102016-05-05 00:56:12 +000010348/// that every explicit specialization along that path is visible. This enforces
10349/// C++ [temp.expl.spec]/6:
10350///
10351/// If a template, a member template or a member of a class template is
10352/// explicitly specialized then that specialization shall be declared before
10353/// the first use of that specialization that would cause an implicit
10354/// instantiation to take place, in every translation unit in which such a
10355/// use occurs; no diagnostic is required.
10356///
10357/// and also C++ [temp.class.spec]/1:
10358///
10359/// A partial specialization shall be declared before the first use of a
10360/// class template specialization that would make use of the partial
10361/// specialization as the result of an implicit or explicit instantiation
10362/// in every translation unit in which such a use occurs; no diagnostic is
10363/// required.
10364class ExplicitSpecializationVisibilityChecker {
10365 Sema &S;
10366 SourceLocation Loc;
10367 llvm::SmallVector<Module *, 8> Modules;
10368
10369public:
10370 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
10371 : S(S), Loc(Loc) {}
10372
10373 void check(NamedDecl *ND) {
10374 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10375 return checkImpl(FD);
10376 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
10377 return checkImpl(RD);
10378 if (auto *VD = dyn_cast<VarDecl>(ND))
10379 return checkImpl(VD);
10380 if (auto *ED = dyn_cast<EnumDecl>(ND))
10381 return checkImpl(ED);
10382 }
10383
10384private:
10385 void diagnose(NamedDecl *D, bool IsPartialSpec) {
10386 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
10387 : Sema::MissingImportKind::ExplicitSpecialization;
10388 const bool Recover = true;
10389
10390 // If we got a custom set of modules (because only a subset of the
10391 // declarations are interesting), use them, otherwise let
10392 // diagnoseMissingImport intelligently pick some.
10393 if (Modules.empty())
10394 S.diagnoseMissingImport(Loc, D, Kind, Recover);
10395 else
10396 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
10397 }
10398
10399 // Check a specific declaration. There are three problematic cases:
10400 //
10401 // 1) The declaration is an explicit specialization of a template
10402 // specialization.
10403 // 2) The declaration is an explicit specialization of a member of an
10404 // templated class.
10405 // 3) The declaration is an instantiation of a template, and that template
10406 // is an explicit specialization of a member of a templated class.
10407 //
10408 // We don't need to go any deeper than that, as the instantiation of the
10409 // surrounding class / etc is not triggered by whatever triggered this
10410 // instantiation, and thus should be checked elsewhere.
10411 template<typename SpecDecl>
10412 void checkImpl(SpecDecl *Spec) {
10413 bool IsHiddenExplicitSpecialization = false;
10414 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
10415 IsHiddenExplicitSpecialization =
10416 Spec->getMemberSpecializationInfo()
10417 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
Richard Smith54f04402017-05-18 02:29:20 +000010418 : !S.hasVisibleExplicitSpecialization(Spec, &Modules);
Richard Smith6739a102016-05-05 00:56:12 +000010419 } else {
10420 checkInstantiated(Spec);
10421 }
10422
10423 if (IsHiddenExplicitSpecialization)
10424 diagnose(Spec->getMostRecentDecl(), false);
10425 }
10426
10427 void checkInstantiated(FunctionDecl *FD) {
10428 if (auto *TD = FD->getPrimaryTemplate())
10429 checkTemplate(TD);
10430 }
10431
10432 void checkInstantiated(CXXRecordDecl *RD) {
10433 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
10434 if (!SD)
10435 return;
10436
10437 auto From = SD->getSpecializedTemplateOrPartial();
10438 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
10439 checkTemplate(TD);
10440 else if (auto *TD =
10441 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
10442 if (!S.hasVisibleDeclaration(TD))
10443 diagnose(TD, true);
10444 checkTemplate(TD);
10445 }
10446 }
10447
10448 void checkInstantiated(VarDecl *RD) {
10449 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
10450 if (!SD)
10451 return;
10452
10453 auto From = SD->getSpecializedTemplateOrPartial();
10454 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
10455 checkTemplate(TD);
10456 else if (auto *TD =
10457 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
10458 if (!S.hasVisibleDeclaration(TD))
10459 diagnose(TD, true);
10460 checkTemplate(TD);
10461 }
10462 }
10463
10464 void checkInstantiated(EnumDecl *FD) {}
10465
10466 template<typename TemplDecl>
10467 void checkTemplate(TemplDecl *TD) {
10468 if (TD->isMemberSpecialization()) {
10469 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
10470 diagnose(TD->getMostRecentDecl(), false);
10471 }
10472 }
10473};
Benjamin Kramera0a13c32016-08-06 11:21:04 +000010474} // end anonymous namespace
Richard Smith6739a102016-05-05 00:56:12 +000010475
10476void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
10477 if (!getLangOpts().Modules)
10478 return;
10479
10480 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
10481}
10482
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010483/// Check whether a template partial specialization that we've discovered
Richard Smith6739a102016-05-05 00:56:12 +000010484/// is hidden, and produce suitable diagnostics if so.
10485void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
10486 NamedDecl *Spec) {
10487 llvm::SmallVector<Module *, 8> Modules;
10488 if (!hasVisibleDeclaration(Spec, &Modules))
10489 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
10490 MissingImportKind::PartialSpecialization,
10491 /*Recover*/true);
10492}