blob: f7f3ccc3e2f644326f0168b77c625d1766a32c41 [file] [log] [blame]
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
Douglas Gregor5101c242008-12-05 18:15:24 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006//===----------------------------------------------------------------------===//
Douglas Gregor5101c242008-12-05 18:15:24 +00007//
8// This file implements semantic analysis for C++ templates.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009//===----------------------------------------------------------------------===//
Douglas Gregor5101c242008-12-05 18:15:24 +000010
Douglas Gregor15acfb92009-08-06 16:20:37 +000011#include "TreeTransform.h"
Larisse Voufo39a1e502013-08-06 01:03:05 +000012#include "clang/AST/ASTConsumer.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000013#include "clang/AST/ASTContext.h"
John McCallbbbbe4e2010-03-11 07:50:04 +000014#include "clang/AST/DeclFriend.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000015#include "clang/AST/DeclTemplate.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "clang/AST/Expr.h"
17#include "clang/AST/ExprCXX.h"
John McCalla020a012010-10-20 05:44:58 +000018#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor7731d3f2010-10-13 00:27:52 +000019#include "clang/AST/TypeVisitor.h"
David Majnemerd9b1a4f2015-11-04 03:40:30 +000020#include "clang/Basic/Builtins.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000021#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000022#include "clang/Basic/PartialDiagnostic.h"
David Majnemer763584d2014-02-06 10:59:19 +000023#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Sema/DeclSpec.h"
25#include "clang/Sema/Lookup.h"
26#include "clang/Sema/ParsedTemplate.h"
27#include "clang/Sema/Scope.h"
28#include "clang/Sema/SemaInternal.h"
29#include "clang/Sema/Template.h"
30#include "clang/Sema/TemplateDeduction.h"
Benjamin Kramere0513cb2012-01-30 16:17:39 +000031#include "llvm/ADT/SmallBitVector.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000032#include "llvm/ADT/SmallString.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000033#include "llvm/ADT/StringExtras.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000034
Eric Fiselier6ad68552016-07-01 01:24:09 +000035#include <iterator>
Douglas Gregor5101c242008-12-05 18:15:24 +000036using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000037using namespace sema;
Douglas Gregor5101c242008-12-05 18:15:24 +000038
John McCall9b72f892010-11-10 02:40:36 +000039// Exported for use by Parser.
40SourceRange
41clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
42 unsigned N) {
43 if (!N) return SourceRange();
44 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
45}
46
Hubert Tong5a8ec4e2017-02-10 02:46:19 +000047namespace clang {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000048/// [temp.constr.decl]p2: A template's associated constraints are
Hubert Tong5a8ec4e2017-02-10 02:46:19 +000049/// defined as a single constraint-expression derived from the introduced
50/// constraint-expressions [ ... ].
51///
52/// \param Params The template parameter list and optional requires-clause.
53///
54/// \param FD The underlying templated function declaration for a function
55/// template.
56static Expr *formAssociatedConstraints(TemplateParameterList *Params,
57 FunctionDecl *FD);
58}
59
60static Expr *clang::formAssociatedConstraints(TemplateParameterList *Params,
61 FunctionDecl *FD) {
62 // FIXME: Concepts: collect additional introduced constraint-expressions
63 assert(!FD && "Cannot collect constraints from function declaration yet.");
64 return Params->getRequiresClause();
65}
66
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000067/// Determine whether the declaration found is acceptable as the name
Douglas Gregorb7bfe792009-09-02 22:59:36 +000068/// of a template and, if so, return that template declaration. Otherwise,
Richard Smithafcfb6b2019-02-15 21:53:07 +000069/// returns null.
70///
71/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
72/// is true. In all other cases it will return a TemplateDecl (or null).
73NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D,
74 bool AllowFunctionTemplates,
75 bool AllowDependent) {
76 D = D->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +000077
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000078 if (isa<TemplateDecl>(D)) {
79 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +000080 return nullptr;
81
Richard Smithafcfb6b2019-02-15 21:53:07 +000082 return D;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000083 }
Mike Stump11289f42009-09-09 15:08:12 +000084
Douglas Gregorb7bfe792009-09-02 22:59:36 +000085 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
86 // C++ [temp.local]p1:
87 // Like normal (non-template) classes, class templates have an
88 // injected-class-name (Clause 9). The injected-class-name
89 // can be used with or without a template-argument-list. When
90 // it is used without a template-argument-list, it is
91 // equivalent to the injected-class-name followed by the
92 // template-parameters of the class template enclosed in
93 // <>. When it is used with a template-argument-list, it
94 // refers to the specified class template specialization,
95 // which could be the current specialization or another
96 // specialization.
97 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000098 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000099 if (Record->getDescribedClassTemplate())
100 return Record->getDescribedClassTemplate();
101
102 if (ClassTemplateSpecializationDecl *Spec
103 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
104 return Spec->getSpecializedTemplate();
105 }
Mike Stump11289f42009-09-09 15:08:12 +0000106
Craig Topperc3ec1492014-05-26 06:22:03 +0000107 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000108 }
Mike Stump11289f42009-09-09 15:08:12 +0000109
Richard Smithcbebd622018-05-14 20:52:48 +0000110 // 'using Dependent::foo;' can resolve to a template name.
111 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
112 // injected-class-name).
Richard Smithafcfb6b2019-02-15 21:53:07 +0000113 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
Richard Smithcbebd622018-05-14 20:52:48 +0000114 return D;
115
Craig Topperc3ec1492014-05-26 06:22:03 +0000116 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000117}
118
Simon Pilgrim6905d222016-12-30 22:55:33 +0000119void Sema::FilterAcceptableTemplateNames(LookupResult &R,
Richard Smithafcfb6b2019-02-15 21:53:07 +0000120 bool AllowFunctionTemplates,
121 bool AllowDependent) {
John McCalle66edc12009-11-24 19:00:30 +0000122 LookupResult::Filter filter = R.makeFilter();
123 while (filter.hasNext()) {
124 NamedDecl *Orig = filter.next();
Richard Smithafcfb6b2019-02-15 21:53:07 +0000125 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
John McCalle66edc12009-11-24 19:00:30 +0000126 filter.erase();
John McCalle66edc12009-11-24 19:00:30 +0000127 }
128 filter.done();
129}
130
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000131bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
Richard Smithafcfb6b2019-02-15 21:53:07 +0000132 bool AllowFunctionTemplates,
Richard Smithb23c5e82019-05-09 03:31:27 +0000133 bool AllowDependent,
134 bool AllowNonTemplateFunctions) {
135 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
Richard Smithafcfb6b2019-02-15 21:53:07 +0000136 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000137 return true;
Richard Smithb23c5e82019-05-09 03:31:27 +0000138 if (AllowNonTemplateFunctions &&
139 isa<FunctionDecl>((*I)->getUnderlyingDecl()))
140 return true;
141 }
Simon Pilgrim6905d222016-12-30 22:55:33 +0000142
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000143 return false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000144}
145
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000146TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000147 CXXScopeSpec &SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000148 bool hasTemplateKeyword,
Richard Smithc08b6932018-04-27 02:00:13 +0000149 const UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +0000150 ParsedType ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000151 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000152 TemplateTy &TemplateResult,
153 bool &MemberOfUnknownSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000154 assert(getLangOpts().CPlusPlus && "No template names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000155
Douglas Gregor3cf81312009-11-03 23:16:33 +0000156 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000157 MemberOfUnknownSpecialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000158
Douglas Gregor3cf81312009-11-03 23:16:33 +0000159 switch (Name.getKind()) {
Faisal Vali2ab8c152017-12-30 04:15:27 +0000160 case UnqualifiedIdKind::IK_Identifier:
Douglas Gregor3cf81312009-11-03 23:16:33 +0000161 TName = DeclarationName(Name.Identifier);
162 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000163
Faisal Vali2ab8c152017-12-30 04:15:27 +0000164 case UnqualifiedIdKind::IK_OperatorFunctionId:
Douglas Gregor3cf81312009-11-03 23:16:33 +0000165 TName = Context.DeclarationNames.getCXXOperatorName(
166 Name.OperatorFunctionId.Operator);
167 break;
168
Faisal Vali2ab8c152017-12-30 04:15:27 +0000169 case UnqualifiedIdKind::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000170 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
171 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000172
Douglas Gregor3cf81312009-11-03 23:16:33 +0000173 default:
174 return TNK_Non_template;
175 }
Mike Stump11289f42009-09-09 15:08:12 +0000176
John McCallba7bf592010-08-24 05:47:05 +0000177 QualType ObjectType = ObjectTypePtr.get();
Mike Stump11289f42009-09-09 15:08:12 +0000178
Richard Smithb23c5e82019-05-09 03:31:27 +0000179 AssumedTemplateKind AssumedTemplate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000180 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
Richard Smith79810042018-05-11 02:43:08 +0000181 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
Richard Smithb23c5e82019-05-09 03:31:27 +0000182 MemberOfUnknownSpecialization, SourceLocation(),
183 &AssumedTemplate))
Richard Smith79810042018-05-11 02:43:08 +0000184 return TNK_Non_template;
Richard Smithb23c5e82019-05-09 03:31:27 +0000185
186 if (AssumedTemplate != AssumedTemplateKind::None) {
187 TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
188 // Let the parser know whether we found nothing or found functions; if we
189 // found nothing, we want to more carefully check whether this is actually
190 // a function template name versus some other kind of undeclared identifier.
191 return AssumedTemplate == AssumedTemplateKind::FoundNothing
192 ? TNK_Undeclared_template
193 : TNK_Function_template;
194 }
195
196 if (R.empty())
197 return TNK_Non_template;
Richard Smith40bd10b2019-02-15 00:29:04 +0000198
Richard Smithafcfb6b2019-02-15 21:53:07 +0000199 NamedDecl *D = nullptr;
200 if (R.isAmbiguous()) {
201 // If we got an ambiguity involving a non-function template, treat this
202 // as a template name, and pick an arbitrary template for error recovery.
203 bool AnyFunctionTemplates = false;
204 for (NamedDecl *FoundD : R) {
205 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
206 if (isa<FunctionTemplateDecl>(FoundTemplate))
207 AnyFunctionTemplates = true;
208 else {
209 D = FoundTemplate;
210 break;
211 }
212 }
213 }
214
215 // If we didn't find any templates at all, this isn't a template name.
216 // Leave the ambiguity for a later lookup to diagnose.
217 if (!D && !AnyFunctionTemplates) {
218 R.suppressDiagnostics();
219 return TNK_Non_template;
220 }
221
222 // If the only templates were function templates, filter out the rest.
223 // We'll diagnose the ambiguity later.
224 if (!D)
225 FilterAcceptableTemplateNames(R);
John McCalldcc71402010-08-13 02:23:42 +0000226 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000227
Richard Smithafcfb6b2019-02-15 21:53:07 +0000228 // At this point, we have either picked a single template name declaration D
229 // or we have a non-empty set of results R containing either one template name
230 // declaration or a set of function templates.
231
John McCalld28ae272009-12-02 08:04:21 +0000232 TemplateName Template;
233 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000234
John McCalld28ae272009-12-02 08:04:21 +0000235 unsigned ResultCount = R.end() - R.begin();
Richard Smithafcfb6b2019-02-15 21:53:07 +0000236 if (!D && ResultCount > 1) {
John McCalld28ae272009-12-02 08:04:21 +0000237 // We assume that we'll preserve the qualifier from a function
238 // template name in other ways.
239 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
240 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000241
242 // We'll do this lookup again later.
243 R.suppressDiagnostics();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000244 } else {
Richard Smithafcfb6b2019-02-15 21:53:07 +0000245 if (!D) {
246 D = getAsTemplateNameDecl(*R.begin());
247 assert(D && "unambiguous result is not a template name");
248 }
249
250 if (isa<UnresolvedUsingValueDecl>(D)) {
251 // We don't yet know whether this is a template-name or not.
252 MemberOfUnknownSpecialization = true;
253 return TNK_Non_template;
254 }
255
256 TemplateDecl *TD = cast<TemplateDecl>(D);
John McCalld28ae272009-12-02 08:04:21 +0000257
258 if (SS.isSet() && !SS.isInvalid()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000259 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000260 Template = Context.getQualifiedTemplateName(Qualifier,
261 hasTemplateKeyword, TD);
John McCalld28ae272009-12-02 08:04:21 +0000262 } else {
263 Template = TemplateName(TD);
264 }
265
John McCalldcc71402010-08-13 02:23:42 +0000266 if (isa<FunctionTemplateDecl>(TD)) {
John McCalld28ae272009-12-02 08:04:21 +0000267 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000268
269 // We'll do this lookup again later.
270 R.suppressDiagnostics();
271 } else {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000272 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000273 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
Faisal Valia534f072018-04-26 00:42:40 +0000274 isa<BuiltinTemplateDecl>(TD));
Larisse Voufo39a1e502013-08-06 01:03:05 +0000275 TemplateKind =
Faisal Valia534f072018-04-26 00:42:40 +0000276 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
John McCalld28ae272009-12-02 08:04:21 +0000277 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000278 }
Mike Stump11289f42009-09-09 15:08:12 +0000279
John McCalld28ae272009-12-02 08:04:21 +0000280 TemplateResult = TemplateTy::make(Template);
281 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000282}
283
Richard Smith278890f2017-02-10 20:39:58 +0000284bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
285 SourceLocation NameLoc,
286 ParsedTemplateTy *Template) {
287 CXXScopeSpec SS;
288 bool MemberOfUnknownSpecialization = false;
289
290 // We could use redeclaration lookup here, but we don't need to: the
291 // syntactic form of a deduction guide is enough to identify it even
292 // if we can't look up the template name at all.
293 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
Richard Smith79810042018-05-11 02:43:08 +0000294 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
295 /*EnteringContext*/ false,
296 MemberOfUnknownSpecialization))
297 return false;
Richard Smith278890f2017-02-10 20:39:58 +0000298
299 if (R.empty()) return false;
300 if (R.isAmbiguous()) {
301 // FIXME: Diagnose an ambiguity if we find at least one template.
302 R.suppressDiagnostics();
303 return false;
304 }
305
306 // We only treat template-names that name type templates as valid deduction
307 // guide names.
308 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
309 if (!TD || !getAsTypeTemplateDecl(TD))
310 return false;
311
312 if (Template)
313 *Template = TemplateTy::make(TemplateName(TD));
314 return true;
315}
316
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000317bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
Douglas Gregor18473f32010-01-12 21:28:44 +0000318 SourceLocation IILoc,
319 Scope *S,
320 const CXXScopeSpec *SS,
321 TemplateTy &SuggestedTemplate,
322 TemplateNameKind &SuggestedKind) {
323 // We can't recover unless there's a dependent scope specifier preceding the
324 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000325 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000326 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
327 computeDeclContext(*SS))
328 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000329
Douglas Gregor18473f32010-01-12 21:28:44 +0000330 // The code is missing a 'template' keyword prior to the dependent template
331 // name.
332 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
333 Diag(IILoc, diag::err_template_kw_missing)
334 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000335 << FixItHint::CreateInsertion(IILoc, "template ");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000336 SuggestedTemplate
Douglas Gregor18473f32010-01-12 21:28:44 +0000337 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
338 SuggestedKind = TNK_Dependent_template_name;
339 return true;
340}
341
Richard Smith79810042018-05-11 02:43:08 +0000342bool Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000343 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000344 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000345 bool EnteringContext,
Richard Smith79810042018-05-11 02:43:08 +0000346 bool &MemberOfUnknownSpecialization,
Richard Smithb23c5e82019-05-09 03:31:27 +0000347 SourceLocation TemplateKWLoc,
348 AssumedTemplateKind *ATK) {
349 if (ATK)
350 *ATK = AssumedTemplateKind::None;
351
Richard Smithafcfb6b2019-02-15 21:53:07 +0000352 Found.setTemplateNameLookup(true);
353
John McCalle66edc12009-11-24 19:00:30 +0000354 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000355 MemberOfUnknownSpecialization = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000356 DeclContext *LookupCtx = nullptr;
Richard Smith79810042018-05-11 02:43:08 +0000357 bool IsDependent = false;
John McCalle66edc12009-11-24 19:00:30 +0000358 if (!ObjectType.isNull()) {
359 // This nested-name-specifier occurs in a member access expression, e.g.,
360 // x->B::f, and we are looking into the type of the object.
361 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
362 LookupCtx = computeDeclContext(ObjectType);
Richard Smith79810042018-05-11 02:43:08 +0000363 IsDependent = !LookupCtx;
364 assert((IsDependent || !ObjectType->isIncompleteType() ||
Richard Smith5ed79562013-06-07 20:03:01 +0000365 ObjectType->castAs<TagType>()->isBeingDefined()) &&
John McCalle66edc12009-11-24 19:00:30 +0000366 "Caller should have completed object type");
Simon Pilgrim6905d222016-12-30 22:55:33 +0000367
Douglas Gregorbf3a8262012-01-12 16:11:24 +0000368 // Template names cannot appear inside an Objective-C class or object type.
369 if (ObjectType->isObjCObjectOrInterfaceType()) {
370 Found.clear();
Richard Smith79810042018-05-11 02:43:08 +0000371 return false;
Douglas Gregorbf3a8262012-01-12 16:11:24 +0000372 }
John McCalle66edc12009-11-24 19:00:30 +0000373 } else if (SS.isSet()) {
374 // This nested-name-specifier occurs after another nested-name-specifier,
375 // so long into the context associated with the prior nested-name-specifier.
376 LookupCtx = computeDeclContext(SS, EnteringContext);
Richard Smith79810042018-05-11 02:43:08 +0000377 IsDependent = !LookupCtx;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000378
John McCalle66edc12009-11-24 19:00:30 +0000379 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000380 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
Richard Smith79810042018-05-11 02:43:08 +0000381 return true;
John McCalle66edc12009-11-24 19:00:30 +0000382 }
383
384 bool ObjectTypeSearchedInScope = false;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000385 bool AllowFunctionTemplatesInLookup = true;
John McCalle66edc12009-11-24 19:00:30 +0000386 if (LookupCtx) {
387 // Perform "qualified" name lookup into the declaration context we
388 // computed, which is either the type of the base of a member access
389 // expression or the declaration context associated with a prior
390 // nested-name-specifier.
391 LookupQualifiedName(Found, LookupCtx);
Simon Pilgrim6905d222016-12-30 22:55:33 +0000392
Richard Smith79810042018-05-11 02:43:08 +0000393 // FIXME: The C++ standard does not clearly specify what happens in the
394 // case where the object type is dependent, and implementations vary. In
395 // Clang, we treat a name after a . or -> as a template-name if lookup
396 // finds a non-dependent member or member of the current instantiation that
397 // is a type template, or finds no such members and lookup in the context
398 // of the postfix-expression finds a type template. In the latter case, the
399 // name is nonetheless dependent, and we may resolve it to a member of an
400 // unknown specialization when we come to instantiate the template.
401 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
John McCalle66edc12009-11-24 19:00:30 +0000402 }
403
Richard Smith79810042018-05-11 02:43:08 +0000404 if (!SS.isSet() && (ObjectType.isNull() || Found.empty())) {
405 // C++ [basic.lookup.classref]p1:
406 // In a class member access expression (5.2.5), if the . or -> token is
407 // immediately followed by an identifier followed by a <, the
408 // identifier must be looked up to determine whether the < is the
409 // beginning of a template argument list (14.2) or a less-than operator.
410 // The identifier is first looked up in the class of the object
411 // expression. If the identifier is not found, it is then looked up in
412 // the context of the entire postfix-expression and shall name a class
413 // template.
414 if (S)
415 LookupName(Found, S);
416
417 if (!ObjectType.isNull()) {
418 // FIXME: We should filter out all non-type templates here, particularly
419 // variable templates and concepts. But the exclusion of alias templates
420 // and template template parameters is a wording defect.
421 AllowFunctionTemplatesInLookup = false;
422 ObjectTypeSearchedInScope = true;
423 }
424
425 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
426 }
427
Richard Smithafcfb6b2019-02-15 21:53:07 +0000428 if (Found.isAmbiguous())
429 return false;
430
Richard Smithb23c5e82019-05-09 03:31:27 +0000431 if (ATK && !SS.isSet() && ObjectType.isNull() && TemplateKWLoc.isInvalid()) {
432 // C++2a [temp.names]p2:
433 // A name is also considered to refer to a template if it is an
434 // unqualified-id followed by a < and name lookup finds either one or more
435 // functions or finds nothing.
436 //
437 // To keep our behavior consistent, we apply the "finds nothing" part in
438 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
439 // successfully form a call to an undeclared template-id.
440 bool AllFunctions =
441 getLangOpts().CPlusPlus2a &&
442 std::all_of(Found.begin(), Found.end(), [](NamedDecl *ND) {
443 return isa<FunctionDecl>(ND->getUnderlyingDecl());
444 });
445 if (AllFunctions || (Found.empty() && !IsDependent)) {
446 // If lookup found any functions, or if this is a name that can only be
447 // used for a function, then strongly assume this is a function
448 // template-id.
449 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
450 ? AssumedTemplateKind::FoundNothing
451 : AssumedTemplateKind::FoundFunctions;
452 Found.clear();
453 return false;
454 }
455 }
456
Richard Smith79810042018-05-11 02:43:08 +0000457 if (Found.empty() && !IsDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000458 // If we did not find any names, attempt to correct any typos.
459 DeclarationName Name = Found.getLookupName();
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000460 Found.clear();
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000461 // Simple filter callback that, for keywords, only accepts the C++ *_cast
Bruno Ricci70ad3962019-03-25 17:08:51 +0000462 DefaultFilterCCC FilterCCC{};
463 FilterCCC.WantTypeSpecifiers = false;
464 FilterCCC.WantExpressionKeywords = false;
465 FilterCCC.WantRemainingKeywords = false;
466 FilterCCC.WantCXXNamedCasts = true;
467 if (TypoCorrection Corrected =
468 CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S,
469 &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) {
Richard Smithde6d6c42015-12-29 19:43:10 +0000470 if (auto *ND = Corrected.getFoundDecl())
471 Found.addDecl(ND);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000472 FilterAcceptableTemplateNames(Found);
Richard Smithafcfb6b2019-02-15 21:53:07 +0000473 if (Found.isAmbiguous()) {
474 Found.clear();
475 } else if (!Found.empty()) {
Richard Smithb23c5e82019-05-09 03:31:27 +0000476 Found.setLookupName(Corrected.getCorrection());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000477 if (LookupCtx) {
Richard Smithf9b15102013-08-17 00:46:16 +0000478 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
479 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000480 Name.getAsString() == CorrectedStr;
Richard Smithf9b15102013-08-17 00:46:16 +0000481 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
482 << Name << LookupCtx << DroppedSpecifier
483 << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000484 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000485 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000486 }
John McCalle9cccd82010-06-16 08:42:20 +0000487 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000488 }
489 }
490
Richard Smith79810042018-05-11 02:43:08 +0000491 NamedDecl *ExampleLookupResult =
492 Found.empty() ? nullptr : Found.getRepresentativeDecl();
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000493 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000494 if (Found.empty()) {
Richard Smith79810042018-05-11 02:43:08 +0000495 if (IsDependent) {
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000496 MemberOfUnknownSpecialization = true;
Richard Smith79810042018-05-11 02:43:08 +0000497 return false;
498 }
499
500 // If a 'template' keyword was used, a lookup that finds only non-template
501 // names is an error.
502 if (ExampleLookupResult && TemplateKWLoc.isValid()) {
503 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
504 << Found.getLookupName() << SS.getRange();
Richard Smithcbebd622018-05-14 20:52:48 +0000505 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
Richard Smith79810042018-05-11 02:43:08 +0000506 diag::note_template_kw_refers_to_non_template)
507 << Found.getLookupName();
508 return true;
509 }
510
511 return false;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000512 }
John McCalle66edc12009-11-24 19:00:30 +0000513
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000514 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
Richard Smithe7d67f22013-09-03 21:22:41 +0000515 !getLangOpts().CPlusPlus11) {
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000516 // C++03 [basic.lookup.classref]p1:
John McCalle66edc12009-11-24 19:00:30 +0000517 // [...] If the lookup in the class of the object expression finds a
518 // template, the name is also looked up in the context of the entire
519 // postfix-expression and [...]
520 //
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000521 // Note: C++11 does not perform this second lookup.
John McCalle66edc12009-11-24 19:00:30 +0000522 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
523 LookupOrdinaryName);
Richard Smithafcfb6b2019-02-15 21:53:07 +0000524 FoundOuter.setTemplateNameLookup(true);
John McCalle66edc12009-11-24 19:00:30 +0000525 LookupName(FoundOuter, S);
Richard Smithafcfb6b2019-02-15 21:53:07 +0000526 // FIXME: We silently accept an ambiguous lookup here, in violation of
527 // [basic.lookup]/1.
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000528 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000529
Richard Smithafcfb6b2019-02-15 21:53:07 +0000530 NamedDecl *OuterTemplate;
John McCalle66edc12009-11-24 19:00:30 +0000531 if (FoundOuter.empty()) {
532 // - if the name is not found, the name found in the class of the
533 // object expression is used, otherwise
Richard Smithafcfb6b2019-02-15 21:53:07 +0000534 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
535 !(OuterTemplate =
536 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
John McCalle66edc12009-11-24 19:00:30 +0000537 // - if the name is found in the context of the entire
538 // postfix-expression and does not name a class template, the name
539 // found in the class of the object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000540 FoundOuter.clear();
John McCalle9cccd82010-06-16 08:42:20 +0000541 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000542 // - if the name found is a class template, it must refer to the same
543 // entity as the one found in the class of the object expression,
544 // otherwise the program is ill-formed.
545 if (!Found.isSingleResult() ||
Richard Smithafcfb6b2019-02-15 21:53:07 +0000546 getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
547 OuterTemplate->getCanonicalDecl()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000548 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000549 diag::ext_nested_name_member_ref_lookup_ambiguous)
550 << Found.getLookupName()
551 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000552 Diag(Found.getRepresentativeDecl()->getLocation(),
553 diag::note_ambig_member_ref_object_type)
554 << ObjectType;
555 Diag(FoundOuter.getFoundDecl()->getLocation(),
556 diag::note_ambig_member_ref_scope);
557
558 // Recover by taking the template that we found in the object
559 // expression's type.
560 }
561 }
562 }
Richard Smith79810042018-05-11 02:43:08 +0000563
564 return false;
John McCalle66edc12009-11-24 19:00:30 +0000565}
566
Richard Smith42bc73a2017-05-10 02:30:28 +0000567void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
568 SourceLocation Less,
569 SourceLocation Greater) {
570 if (TemplateName.isInvalid())
571 return;
572
573 DeclarationNameInfo NameInfo;
574 CXXScopeSpec SS;
575 LookupNameKind LookupKind;
576
577 DeclContext *LookupCtx = nullptr;
578 NamedDecl *Found = nullptr;
Richard Smithbf5bcf22018-06-26 23:20:26 +0000579 bool MissingTemplateKeyword = false;
Richard Smith42bc73a2017-05-10 02:30:28 +0000580
581 // Figure out what name we looked up.
Richard Smithbf5bcf22018-06-26 23:20:26 +0000582 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
583 NameInfo = DRE->getNameInfo();
584 SS.Adopt(DRE->getQualifierLoc());
585 LookupKind = LookupOrdinaryName;
586 Found = DRE->getFoundDecl();
587 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
Richard Smith42bc73a2017-05-10 02:30:28 +0000588 NameInfo = ME->getMemberNameInfo();
589 SS.Adopt(ME->getQualifierLoc());
590 LookupKind = LookupMemberName;
591 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
592 Found = ME->getMemberDecl();
Richard Smithbf5bcf22018-06-26 23:20:26 +0000593 } else if (auto *DSDRE =
594 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
595 NameInfo = DSDRE->getNameInfo();
596 SS.Adopt(DSDRE->getQualifierLoc());
597 MissingTemplateKeyword = true;
598 } else if (auto *DSME =
599 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
600 NameInfo = DSME->getMemberNameInfo();
601 SS.Adopt(DSME->getQualifierLoc());
602 MissingTemplateKeyword = true;
Richard Smith42bc73a2017-05-10 02:30:28 +0000603 } else {
Richard Smithbf5bcf22018-06-26 23:20:26 +0000604 llvm_unreachable("unexpected kind of potential template name");
605 }
606
607 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
608 // was missing.
609 if (MissingTemplateKeyword) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000610 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
611 << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
Richard Smithbf5bcf22018-06-26 23:20:26 +0000612 return;
Richard Smith42bc73a2017-05-10 02:30:28 +0000613 }
614
615 // Try to correct the name by looking for templates and C++ named casts.
616 struct TemplateCandidateFilter : CorrectionCandidateCallback {
Richard Smithafcfb6b2019-02-15 21:53:07 +0000617 Sema &S;
618 TemplateCandidateFilter(Sema &S) : S(S) {
Richard Smith42bc73a2017-05-10 02:30:28 +0000619 WantTypeSpecifiers = false;
620 WantExpressionKeywords = false;
621 WantRemainingKeywords = false;
622 WantCXXNamedCasts = true;
623 };
624 bool ValidateCandidate(const TypoCorrection &Candidate) override {
625 if (auto *ND = Candidate.getCorrectionDecl())
Richard Smithafcfb6b2019-02-15 21:53:07 +0000626 return S.getAsTemplateNameDecl(ND);
Richard Smith42bc73a2017-05-10 02:30:28 +0000627 return Candidate.isKeyword();
628 }
Bruno Ricci70ad3962019-03-25 17:08:51 +0000629
630 std::unique_ptr<CorrectionCandidateCallback> clone() override {
631 return llvm::make_unique<TemplateCandidateFilter>(*this);
632 }
Richard Smith42bc73a2017-05-10 02:30:28 +0000633 };
634
635 DeclarationName Name = NameInfo.getName();
Bruno Ricci70ad3962019-03-25 17:08:51 +0000636 TemplateCandidateFilter CCC(*this);
637 if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
638 CTK_ErrorRecovery, LookupCtx)) {
Richard Smith42bc73a2017-05-10 02:30:28 +0000639 auto *ND = Corrected.getFoundDecl();
640 if (ND)
Richard Smithafcfb6b2019-02-15 21:53:07 +0000641 ND = getAsTemplateNameDecl(ND);
Richard Smith42bc73a2017-05-10 02:30:28 +0000642 if (ND || Corrected.isKeyword()) {
643 if (LookupCtx) {
644 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
645 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
646 Name.getAsString() == CorrectedStr;
647 diagnoseTypo(Corrected,
648 PDiag(diag::err_non_template_in_member_template_id_suggest)
649 << Name << LookupCtx << DroppedSpecifier
Richard Smith52f8d192017-05-10 21:32:16 +0000650 << SS.getRange(), false);
Richard Smith42bc73a2017-05-10 02:30:28 +0000651 } else {
652 diagnoseTypo(Corrected,
653 PDiag(diag::err_non_template_in_template_id_suggest)
Richard Smith52f8d192017-05-10 21:32:16 +0000654 << Name, false);
Richard Smith42bc73a2017-05-10 02:30:28 +0000655 }
656 if (Found)
657 Diag(Found->getLocation(),
658 diag::note_non_template_in_template_id_found);
659 return;
660 }
661 }
662
663 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
664 << Name << SourceRange(Less, Greater);
665 if (Found)
666 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
667}
668
John McCallcd4b4772009-12-02 03:53:29 +0000669/// ActOnDependentIdExpression - Handle a dependent id-expression that
670/// was just parsed. This is only possible with an explicit scope
671/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000672ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000673Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000674 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000675 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000676 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000677 const TemplateArgumentListInfo *TemplateArgs) {
John McCall87fe5d52010-05-20 01:18:31 +0000678 DeclContext *DC = getFunctionLevelDeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000679
Reid Kleckner1af391df2016-03-11 18:59:12 +0000680 // C++11 [expr.prim.general]p12:
681 // An id-expression that denotes a non-static data member or non-static
682 // member function of a class can only be used:
683 // (...)
684 // - if that id-expression denotes a non-static data member and it
685 // appears in an unevaluated operand.
686 //
687 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
688 // CXXDependentScopeMemberExpr. The former can instantiate to either
689 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
690 // always a MemberExpr.
691 bool MightBeCxx11UnevalField =
692 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
693
Akira Hatanakad644e022016-12-16 03:19:41 +0000694 // Check if the nested name specifier is an enum type.
695 bool IsEnum = false;
696 if (NestedNameSpecifier *NNS = SS.getScopeRep())
697 IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
698
699 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
Reid Kleckner1af391df2016-03-11 18:59:12 +0000700 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
Brian Gesiak5488ab42019-01-11 01:54:53 +0000701 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000702
John McCalle66edc12009-11-24 19:00:30 +0000703 // Since the 'this' expression is synthesized, we don't need to
704 // perform the double-lookup check.
Craig Topperc3ec1492014-05-26 06:22:03 +0000705 NamedDecl *FirstQualifierInScope = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000706
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000707 return CXXDependentScopeMemberExpr::Create(
708 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
709 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
710 FirstQualifierInScope, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000711 }
712
Abramo Bagnara7945c982012-01-27 09:46:47 +0000713 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000714}
715
John McCalldadc5752010-08-24 06:29:42 +0000716ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000717Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000718 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000719 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000720 const TemplateArgumentListInfo *TemplateArgs) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000721 return DependentScopeDeclRefExpr::Create(
722 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
723 TemplateArgs);
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000724}
725
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000726
727/// Determine whether we would be unable to instantiate this template (because
728/// it either has no definition, or is in the process of being instantiated).
729bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
730 NamedDecl *Instantiation,
731 bool InstantiatedFromMember,
732 const NamedDecl *Pattern,
733 const NamedDecl *PatternDef,
734 TemplateSpecializationKind TSK,
735 bool Complain /*= true*/) {
Richard Smithedbc6e92016-10-14 21:41:24 +0000736 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
737 isa<VarDecl>(Instantiation));
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000738
Richard Smithedbc6e92016-10-14 21:41:24 +0000739 bool IsEntityBeingDefined = false;
740 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
741 IsEntityBeingDefined = TD->isBeingDefined();
742
743 if (PatternDef && !IsEntityBeingDefined) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000744 NamedDecl *SuggestedDef = nullptr;
745 if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
746 /*OnlyNeedComplete*/false)) {
747 // If we're allowed to diagnose this and recover, do so.
748 bool Recover = Complain && !isSFINAEContext();
749 if (Complain)
750 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
751 Sema::MissingImportKind::Definition, Recover);
752 return !Recover;
753 }
754 return false;
755 }
756
Richard Smith6f4e2e02016-08-23 19:41:39 +0000757 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
758 return true;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000759
Richard Smithedbc6e92016-10-14 21:41:24 +0000760 llvm::Optional<unsigned> Note;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000761 QualType InstantiationTy;
762 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
763 InstantiationTy = Context.getTypeDeclType(TD);
Richard Smith6f4e2e02016-08-23 19:41:39 +0000764 if (PatternDef) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000765 Diag(PointOfInstantiation,
766 diag::err_template_instantiate_within_definition)
Richard Smithedbc6e92016-10-14 21:41:24 +0000767 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000768 << InstantiationTy;
769 // Not much point in noting the template declaration here, since
770 // we're lexically inside it.
771 Instantiation->setInvalidDecl();
772 } else if (InstantiatedFromMember) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000773 if (isa<FunctionDecl>(Instantiation)) {
774 Diag(PointOfInstantiation,
775 diag::err_explicit_instantiation_undefined_member)
Richard Smithedbc6e92016-10-14 21:41:24 +0000776 << /*member function*/ 1 << Instantiation->getDeclName()
777 << Instantiation->getDeclContext();
778 Note = diag::note_explicit_instantiation_here;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000779 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000780 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
Richard Smith6f4e2e02016-08-23 19:41:39 +0000781 Diag(PointOfInstantiation,
782 diag::err_implicit_instantiate_member_undefined)
783 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000784 Note = diag::note_member_declared_at;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000785 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000786 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000787 if (isa<FunctionDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000788 Diag(PointOfInstantiation,
789 diag::err_explicit_instantiation_undefined_func_template)
790 << Pattern;
Richard Smithedbc6e92016-10-14 21:41:24 +0000791 Note = diag::note_explicit_instantiation_here;
792 } else if (isa<TagDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000793 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
794 << (TSK != TSK_ImplicitInstantiation)
795 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000796 Note = diag::note_template_decl_here;
797 } else {
798 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
799 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
800 Diag(PointOfInstantiation,
801 diag::err_explicit_instantiation_undefined_var_template)
802 << Instantiation;
803 Instantiation->setInvalidDecl();
804 } else
805 Diag(PointOfInstantiation,
806 diag::err_explicit_instantiation_undefined_member)
807 << /*static data member*/ 2 << Instantiation->getDeclName()
808 << Instantiation->getDeclContext();
809 Note = diag::note_explicit_instantiation_here;
810 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000811 }
Richard Smithedbc6e92016-10-14 21:41:24 +0000812 if (Note) // Diagnostics were emitted.
813 Diag(Pattern->getLocation(), Note.getValue());
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000814
815 // In general, Instantiation isn't marked invalid to get more than one
816 // error for multiple undefined instantiations. But the code that does
817 // explicit declaration -> explicit definition conversion can't handle
818 // invalid declarations, so mark as invalid in that case.
819 if (TSK == TSK_ExplicitInstantiationDeclaration)
820 Instantiation->setInvalidDecl();
821 return true;
822}
823
Douglas Gregor5101c242008-12-05 18:15:24 +0000824/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
825/// that the template parameter 'PrevDecl' is being shadowed by a new
826/// declaration at location Loc. Returns true to indicate that this is
827/// an error, and false otherwise.
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000828void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000829 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000830
831 // Microsoft Visual C++ permits template parameters to be shadowed.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000832 if (getLangOpts().MicrosoftExt)
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000833 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000834
835 // C++ [temp.local]p4:
836 // A template-parameter shall not be redeclared within its
837 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000838 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000839 << cast<NamedDecl>(PrevDecl)->getDeclName();
840 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregor5101c242008-12-05 18:15:24 +0000841}
842
Douglas Gregor463421d2009-03-03 04:44:36 +0000843/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000844/// the parameter D to reference the templated declaration and return a pointer
845/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000846TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
847 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
848 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000849 return Temp;
850 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000851 return nullptr;
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000852}
853
Douglas Gregoreb29d182011-01-05 17:40:24 +0000854ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
855 SourceLocation EllipsisLoc) const {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000856 assert(Kind == Template &&
Douglas Gregoreb29d182011-01-05 17:40:24 +0000857 "Only template template arguments can be pack expansions here");
858 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
859 "Template template argument pack expansion without packs");
860 ParsedTemplateArgument Result(*this);
861 Result.EllipsisLoc = EllipsisLoc;
862 return Result;
863}
864
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000865static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
866 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000867
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000868 switch (Arg.getKind()) {
869 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000870 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000871 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000872 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000873 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000874 return TemplateArgumentLoc(TemplateArgument(T), DI);
875 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000876
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000877 case ParsedTemplateArgument::NonType: {
878 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
879 return TemplateArgumentLoc(TemplateArgument(E), E);
880 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000881
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000882 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000883 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregore1d60df2011-01-14 23:41:42 +0000884 TemplateArgument TArg;
885 if (Arg.getEllipsisLoc().isValid())
David Blaikie05785d12013-02-20 22:23:23 +0000886 TArg = TemplateArgument(Template, Optional<unsigned int>());
Douglas Gregore1d60df2011-01-14 23:41:42 +0000887 else
888 TArg = Template;
889 return TemplateArgumentLoc(TArg,
Douglas Gregor9d802122011-03-02 17:09:35 +0000890 Arg.getScopeSpec().getWithLocInContext(
891 SemaRef.Context),
Douglas Gregoreb29d182011-01-05 17:40:24 +0000892 Arg.getLocation(),
893 Arg.getEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000894 }
895 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000896
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000897 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000898}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000899
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000900/// Translates template arguments as provided by the parser
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000901/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000902void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
903 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000904 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000905 TemplateArgs.addArgument(translateTemplateArgument(*this,
906 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000907}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000908
Richard Smithb80d5402013-06-25 22:21:36 +0000909static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
910 SourceLocation Loc,
911 IdentifierInfo *Name) {
912 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
Richard Smithbecb92d2017-10-10 22:33:17 +0000913 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
Richard Smithb80d5402013-06-25 22:21:36 +0000914 if (PrevDecl && PrevDecl->isTemplateParameter())
915 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
916}
917
Richard Smith77a9c602018-02-28 03:02:23 +0000918/// Convert a parsed type into a parsed template argument. This is mostly
919/// trivial, except that we may have parsed a C++17 deduced class template
920/// specialization type, in which case we should form a template template
921/// argument instead of a type template argument.
922ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
923 TypeSourceInfo *TInfo;
924 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
925 if (T.isNull())
926 return ParsedTemplateArgument();
927 assert(TInfo && "template argument with no location");
928
929 // If we might have formed a deduced template specialization type, convert
930 // it to a template template argument.
931 if (getLangOpts().CPlusPlus17) {
932 TypeLoc TL = TInfo->getTypeLoc();
933 SourceLocation EllipsisLoc;
934 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
935 EllipsisLoc = PET.getEllipsisLoc();
936 TL = PET.getPatternLoc();
937 }
938
939 CXXScopeSpec SS;
940 if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
941 SS.Adopt(ET.getQualifierLoc());
942 TL = ET.getNamedTypeLoc();
943 }
944
945 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
946 TemplateName Name = DTST.getTypePtr()->getTemplateName();
947 if (SS.isSet())
948 Name = Context.getQualifiedTemplateName(SS.getScopeRep(),
949 /*HasTemplateKeyword*/ false,
950 Name.getAsTemplateDecl());
951 ParsedTemplateArgument Result(SS, TemplateTy::make(Name),
952 DTST.getTemplateNameLoc());
953 if (EllipsisLoc.isValid())
954 Result = Result.getTemplatePackExpansion(EllipsisLoc);
955 return Result;
956 }
957 }
958
959 // This is a normal type template argument. Note, if the type template
960 // argument is an injected-class-name for a template, it has a dual nature
Fangrui Song6907ce22018-07-30 19:24:48 +0000961 // and can be used as either a type or a template. We handle that in
Richard Smith77a9c602018-02-28 03:02:23 +0000962 // convertTypeTemplateArgumentToTemplate.
963 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
964 ParsedType.get().getAsOpaquePtr(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000965 TInfo->getTypeLoc().getBeginLoc());
Richard Smith77a9c602018-02-28 03:02:23 +0000966}
967
Douglas Gregor5101c242008-12-05 18:15:24 +0000968/// ActOnTypeParameter - Called when a C++ template type parameter
969/// (e.g., "typename T") has been parsed. Typename specifies whether
970/// the keyword "typename" was used to declare the type parameter
971/// (otherwise, "class" was used), and KeyLoc is the location of the
972/// "class" or "typename" keyword. ParamName is the name of the
973/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth08836322011-05-01 00:51:33 +0000974/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000975/// If the type parameter has a default argument, it will be added
976/// later via ActOnTypeParameterDefault.
Faisal Valibe294032017-12-23 18:56:34 +0000977NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
John McCall48871652010-08-21 09:40:31 +0000978 SourceLocation EllipsisLoc,
979 SourceLocation KeyLoc,
980 IdentifierInfo *ParamName,
981 SourceLocation ParamNameLoc,
982 unsigned Depth, unsigned Position,
983 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000984 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000985 assert(S->isTemplateParamScope() &&
986 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000987
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000988 SourceLocation Loc = ParamNameLoc;
989 if (!ParamName)
990 Loc = KeyLoc;
991
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000992 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregor5101c242008-12-05 18:15:24 +0000993 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000994 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000995 KeyLoc, Loc, Depth, Position, ParamName,
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000996 Typename, IsParameterPack);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000997 Param->setAccess(AS_public);
Douglas Gregor5101c242008-12-05 18:15:24 +0000998
999 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.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001023 if (DiagnoseUnexpandedParameterPack(Loc, 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() ||
Douglas Gregor463421d2009-03-03 04:44:36 +00001083 // If T is a dependent type, we can't do the check now, so we
1084 // assume that it is well-formed.
Richard Smith5f274382016-09-28 23:55:27 +00001085 T->isDependentType() ||
1086 // Allow use of auto in template parameter declarations.
1087 T->isUndeducedType()) {
Richard Smithd0e1c952012-03-13 07:21:50 +00001088 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1089 // are ignored when determining its type.
1090 return T.getUnqualifiedType();
1091 }
1092
Douglas Gregor463421d2009-03-03 04:44:36 +00001093 // C++ [temp.param]p8:
1094 //
1095 // A non-type template-parameter of type "array of T" or
1096 // "function returning T" is adjusted to be of type "pointer to
1097 // T" or "pointer to function returning T", respectively.
Richard Smithd663fdd2014-12-17 20:42:37 +00001098 else if (T->isArrayType() || T->isFunctionType())
1099 return Context.getDecayedType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001100
Douglas Gregor463421d2009-03-03 04:44:36 +00001101 Diag(Loc, diag::err_template_nontype_parm_bad_type)
1102 << T;
1103
1104 return QualType();
1105}
1106
Faisal Valibe294032017-12-23 18:56:34 +00001107NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
John McCall48871652010-08-21 09:40:31 +00001108 unsigned Depth,
1109 unsigned Position,
1110 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +00001111 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +00001112 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Richard Smith15361a22016-12-28 06:27:18 +00001113
Faisal Valia223d1c2017-12-22 03:50:55 +00001114 // Check that we have valid decl-specifiers specified.
1115 auto CheckValidDeclSpecifiers = [this, &D] {
1116 // C++ [temp.param]
Fangrui Song6907ce22018-07-30 19:24:48 +00001117 // p1
Malcolm Parsonsfab36802018-04-16 08:31:08 +00001118 // template-parameter:
1119 // ...
1120 // parameter-declaration
Fangrui Song6907ce22018-07-30 19:24:48 +00001121 // p2
Faisal Valia223d1c2017-12-22 03:50:55 +00001122 // ... A storage class shall not be specified in a template-parameter
1123 // declaration.
Fangrui Song6907ce22018-07-30 19:24:48 +00001124 // [dcl.typedef]p1:
Faisal Valia223d1c2017-12-22 03:50:55 +00001125 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1126 // of a parameter-declaration
1127 const DeclSpec &DS = D.getDeclSpec();
1128 auto EmitDiag = [this](SourceLocation Loc) {
1129 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1130 << FixItHint::CreateRemoval(Loc);
1131 };
1132 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1133 EmitDiag(DS.getStorageClassSpecLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00001134
Sam McCall1371cba2017-12-22 07:09:51 +00001135 if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
Faisal Valia223d1c2017-12-22 03:50:55 +00001136 EmitDiag(DS.getThreadStorageClassSpecLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00001137
1138 // [dcl.inline]p1:
1139 // The inline specifier can be applied only to the declaration or
Faisal Valia223d1c2017-12-22 03:50:55 +00001140 // definition of a variable or function.
Fangrui Song6907ce22018-07-30 19:24:48 +00001141
Faisal Valia223d1c2017-12-22 03:50:55 +00001142 if (DS.isInlineSpecified())
1143 EmitDiag(DS.getInlineSpecLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00001144
Faisal Valia223d1c2017-12-22 03:50:55 +00001145 // [dcl.constexpr]p1:
Fangrui Song6907ce22018-07-30 19:24:48 +00001146 // The constexpr specifier shall be applied only to the definition of a
1147 // variable or variable template or the declaration of a function or
Faisal Valia223d1c2017-12-22 03:50:55 +00001148 // function template.
Fangrui Song6907ce22018-07-30 19:24:48 +00001149
Faisal Valia223d1c2017-12-22 03:50:55 +00001150 if (DS.isConstexprSpecified())
1151 EmitDiag(DS.getConstexprSpecLoc());
1152
1153 // [dcl.fct.spec]p1:
1154 // Function-specifiers can be used only in function declarations.
1155
1156 if (DS.isVirtualSpecified())
1157 EmitDiag(DS.getVirtualSpecLoc());
1158
Richard Smith76b90272019-05-09 03:59:21 +00001159 if (DS.hasExplicitSpecifier())
Faisal Valia223d1c2017-12-22 03:50:55 +00001160 EmitDiag(DS.getExplicitSpecLoc());
1161
1162 if (DS.isNoreturnSpecified())
1163 EmitDiag(DS.getNoreturnSpecLoc());
1164 };
1165
1166 CheckValidDeclSpecifiers();
Fangrui Song6907ce22018-07-30 19:24:48 +00001167
Richard Smith15361a22016-12-28 06:27:18 +00001168 if (TInfo->getType()->isUndeducedType()) {
1169 Diag(D.getIdentifierLoc(),
1170 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1171 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1172 }
Douglas Gregor5101c242008-12-05 18:15:24 +00001173
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001174 assert(S->isTemplateParamScope() &&
1175 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +00001176 bool Invalid = false;
1177
Richard Smith15361a22016-12-28 06:27:18 +00001178 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001179 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001180 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +00001181 Invalid = true;
1182 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001183
Richard Smithb80d5402013-06-25 22:21:36 +00001184 IdentifierInfo *ParamName = D.getIdentifier();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +00001185 bool IsParameterPack = D.hasEllipsis();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001186 NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
1187 Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1188 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1189 TInfo);
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001190 Param->setAccess(AS_public);
Richard Smithb80d5402013-06-25 22:21:36 +00001191
Douglas Gregor5101c242008-12-05 18:15:24 +00001192 if (Invalid)
1193 Param->setInvalidDecl();
1194
Richard Smithb80d5402013-06-25 22:21:36 +00001195 if (ParamName) {
1196 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1197 ParamName);
1198
Douglas Gregor5101c242008-12-05 18:15:24 +00001199 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +00001200 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +00001201 IdResolver.AddDecl(Param);
1202 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001203
Douglas Gregorf5500772011-01-05 15:48:55 +00001204 // C++0x [temp.param]p9:
1205 // A default template-argument may be specified for any kind of
1206 // template-parameter that is not a template parameter pack.
1207 if (Default && IsParameterPack) {
1208 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
Craig Topperc3ec1492014-05-26 06:22:03 +00001209 Default = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +00001210 }
1211
Douglas Gregordc13ded2010-07-01 00:00:45 +00001212 // Check the well-formedness of the default template argument, if provided.
Douglas Gregorda3cc0d2010-12-23 23:51:58 +00001213 if (Default) {
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001214 // Check for unexpanded parameter packs.
1215 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
1216 return Param;
1217
Douglas Gregordc13ded2010-07-01 00:00:45 +00001218 TemplateArgument Converted;
Richard Smithd663fdd2014-12-17 20:42:37 +00001219 ExprResult DefaultRes =
1220 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
John Wiegley01296292011-04-08 18:41:53 +00001221 if (DefaultRes.isInvalid()) {
Douglas Gregordc13ded2010-07-01 00:00:45 +00001222 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +00001223 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +00001224 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001225 Default = DefaultRes.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001226
Richard Smith1469b912015-06-10 00:29:03 +00001227 Param->setDefaultArgument(Default);
Douglas Gregordc13ded2010-07-01 00:00:45 +00001228 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001229
John McCall48871652010-08-21 09:40:31 +00001230 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +00001231}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001232
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001233/// ActOnTemplateTemplateParameter - Called when a C++ template template
James Dennett2a4d13c2012-06-15 07:13:21 +00001234/// parameter (e.g. T in template <template \<typename> class T> class array)
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001235/// has been parsed. S is the current scope.
Faisal Valibe294032017-12-23 18:56:34 +00001236NamedDecl *Sema::ActOnTemplateTemplateParameter(Scope* S,
John McCall48871652010-08-21 09:40:31 +00001237 SourceLocation TmpLoc,
Richard Trieu9becef62011-09-09 03:18:59 +00001238 TemplateParameterList *Params,
Douglas Gregorf5500772011-01-05 15:48:55 +00001239 SourceLocation EllipsisLoc,
John McCall48871652010-08-21 09:40:31 +00001240 IdentifierInfo *Name,
1241 SourceLocation NameLoc,
1242 unsigned Depth,
1243 unsigned Position,
1244 SourceLocation EqualLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +00001245 ParsedTemplateArgument Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001246 assert(S->isTemplateParamScope() &&
1247 "Template template parameter not in template parameter scope!");
1248
1249 // Construct the parameter object.
Douglas Gregorf5500772011-01-05 15:48:55 +00001250 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001251 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +00001252 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001253 NameLoc.isInvalid()? TmpLoc : NameLoc,
1254 Depth, Position, IsParameterPack,
Douglas Gregorf5500772011-01-05 15:48:55 +00001255 Name, Params);
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001256 Param->setAccess(AS_public);
Simon Pilgrim6905d222016-12-30 22:55:33 +00001257
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001258 // If the template template parameter has a name, then link the identifier
Douglas Gregordc13ded2010-07-01 00:00:45 +00001259 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001260 if (Name) {
Richard Smithb80d5402013-06-25 22:21:36 +00001261 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1262
John McCall48871652010-08-21 09:40:31 +00001263 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001264 IdResolver.AddDecl(Param);
1265 }
1266
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001267 if (Params->size() == 0) {
1268 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1269 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1270 Param->setInvalidDecl();
1271 }
1272
Douglas Gregorf5500772011-01-05 15:48:55 +00001273 // C++0x [temp.param]p9:
1274 // A default template-argument may be specified for any kind of
1275 // template-parameter that is not a template parameter pack.
1276 if (IsParameterPack && !Default.isInvalid()) {
1277 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1278 Default = ParsedTemplateArgument();
1279 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001280
Douglas Gregordc13ded2010-07-01 00:00:45 +00001281 if (!Default.isInvalid()) {
1282 // Check only that we have a template template argument. We don't want to
1283 // try to check well-formedness now, because our template template parameter
1284 // might have dependent types in its template parameters, which we wouldn't
1285 // be able to match now.
1286 //
1287 // If none of the template template parameter's template arguments mention
1288 // other template parameters, we could actually perform more checking here.
1289 // However, it isn't worth doing.
1290 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1291 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
Faisal Valib8b04f82016-03-26 20:46:45 +00001292 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
Douglas Gregordc13ded2010-07-01 00:00:45 +00001293 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00001294 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +00001295 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001296
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001297 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001298 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +00001299 DefaultArg.getArgument().getAsTemplate(),
1300 UPPC_DefaultArgument))
1301 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001302
Richard Smith1469b912015-06-10 00:29:03 +00001303 Param->setDefaultArgument(Context, DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +00001304 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001305
John McCall48871652010-08-21 09:40:31 +00001306 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +00001307}
1308
Hubert Tongf608c052016-04-29 18:05:37 +00001309/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1310/// constrained by RequiresClause, that contains the template parameters in
1311/// Params.
Richard Trieu9becef62011-09-09 03:18:59 +00001312TemplateParameterList *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001313Sema::ActOnTemplateParameterList(unsigned Depth,
1314 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001315 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001316 SourceLocation LAngleLoc,
Faisal Valif241b0d2017-08-25 18:24:20 +00001317 ArrayRef<NamedDecl *> Params,
Hubert Tongf608c052016-04-29 18:05:37 +00001318 SourceLocation RAngleLoc,
1319 Expr *RequiresClause) {
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001320 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001321 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001322
David Majnemer902f8c62015-12-27 07:16:27 +00001323 return TemplateParameterList::Create(
1324 Context, TemplateLoc, LAngleLoc,
Faisal Valif241b0d2017-08-25 18:24:20 +00001325 llvm::makeArrayRef(Params.data(), Params.size()),
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00001326 RAngleLoc, RequiresClause);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +00001327}
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001328
Bruno Ricci4224c872018-12-21 14:35:24 +00001329static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
1330 const CXXScopeSpec &SS) {
John McCall3e11ebe2010-03-15 10:12:16 +00001331 if (SS.isSet())
Bruno Ricci4224c872018-12-21 14:35:24 +00001332 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
John McCall3e11ebe2010-03-15 10:12:16 +00001333}
1334
Erich Keanec480f302018-07-12 21:09:05 +00001335DeclResult Sema::CheckClassTemplate(
1336 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1337 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1338 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1339 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1340 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1341 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
Mike Stump11289f42009-09-09 15:08:12 +00001342 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001343 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +00001344 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +00001345 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001346
1347 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001348 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001349 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001350
Abramo Bagnara6150c882010-05-11 21:36:43 +00001351 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1352 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001353
1354 // There is no such thing as an unnamed class template.
1355 if (!Name) {
1356 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001357 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001358 }
1359
Richard Smith6483d222012-04-21 01:27:54 +00001360 // Find any previous declaration with this name. For a friend with no
1361 // scope explicitly specified, we only look for tag declarations (per
1362 // C++11 [basic.lookup.elab]p2).
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001363 DeclContext *SemanticContext;
Richard Smith6483d222012-04-21 01:27:54 +00001364 LookupResult Previous(*this, Name, NameLoc,
1365 (SS.isEmpty() && TUK == TUK_Friend)
1366 ? LookupTagName : LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00001367 forRedeclarationInCurContext());
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001368 if (SS.isNotEmpty() && !SS.isInvalid()) {
1369 SemanticContext = computeDeclContext(SS, true);
1370 if (!SemanticContext) {
Douglas Gregor67daacb2012-03-30 16:20:47 +00001371 // FIXME: Horrible, horrible hack! We can't currently represent this
1372 // in the AST, and historically we have just ignored such friend
1373 // class templates, so don't complain here.
Richard Smithcd556eb2013-11-08 18:59:56 +00001374 Diag(NameLoc, TUK == TUK_Friend
1375 ? diag::warn_template_qualified_friend_ignored
1376 : diag::err_template_qualified_declarator_no_match)
Douglas Gregor67daacb2012-03-30 16:20:47 +00001377 << SS.getScopeRep() << SS.getRange();
Richard Smithcd556eb2013-11-08 18:59:56 +00001378 return TUK != TUK_Friend;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001379 }
Mike Stump11289f42009-09-09 15:08:12 +00001380
John McCall0b66eb32010-05-01 00:40:08 +00001381 if (RequireCompleteDeclContext(SS, SemanticContext))
1382 return true;
1383
Simon Pilgrim6905d222016-12-30 22:55:33 +00001384 // If we're adding a template to a dependent context, we may need to
1385 // rebuilding some of the types used within the template parameter list,
Douglas Gregor041b0842011-10-14 15:31:12 +00001386 // now that we know what the current instantiation is.
1387 if (SemanticContext->isDependentContext()) {
1388 ContextRAII SavedContext(*this, SemanticContext);
1389 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1390 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00001391 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
Richard Smithc660c8f2018-03-16 13:36:56 +00001392 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc, false);
Richard Smith6483d222012-04-21 01:27:54 +00001393
John McCall27b18f82009-11-17 02:14:36 +00001394 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001395 } else {
1396 SemanticContext = CurContext;
Richard Smith88fe69c2015-07-06 01:45:27 +00001397
1398 // C++14 [class.mem]p14:
1399 // If T is the name of a class, then each of the following shall have a
1400 // name different from T:
1401 // -- every member template of class T
1402 if (TUK != TUK_Friend &&
1403 DiagnoseClassNameShadow(SemanticContext,
1404 DeclarationNameInfo(Name, NameLoc)))
1405 return true;
1406
John McCall27b18f82009-11-17 02:14:36 +00001407 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001408 }
Mike Stump11289f42009-09-09 15:08:12 +00001409
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001410 if (Previous.isAmbiguous())
1411 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001412
Craig Topperc3ec1492014-05-26 06:22:03 +00001413 NamedDecl *PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001414 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001415 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001416
Serge Pavlove50bf752016-06-10 04:39:07 +00001417 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1418 // Maybe we will complain about the shadowed template parameter.
1419 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1420 // Just pretend that we didn't see the previous declaration.
1421 PrevDecl = nullptr;
1422 }
1423
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001424 // If there is a previous declaration with the same name, check
1425 // whether this is a valid redeclaration.
Richard Smithbecb92d2017-10-10 22:33:17 +00001426 ClassTemplateDecl *PrevClassTemplate =
1427 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001428
1429 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001430 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001431 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001432 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001433 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1434 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001435 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001436 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1437 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1438 PrevClassTemplate
1439 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1440 ->getSpecializedTemplate();
1441 }
1442 }
1443
John McCalld43784f2009-12-18 11:25:59 +00001444 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +00001445 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001446 // [...] When looking for a prior declaration of a class or a function
1447 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +00001448 // function is neither a qualified name nor a template-id, scopes outside
1449 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +00001450 if (!SS.isSet()) {
1451 DeclContext *OutermostContext = CurContext;
1452 while (!OutermostContext->isFileContext())
1453 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +00001454
Richard Smith61e582f2012-04-20 07:12:26 +00001455 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +00001456 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1457 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1458 SemanticContext = PrevDecl->getDeclContext();
1459 } else {
1460 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001461 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +00001462 // declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00001463 PrevDecl = PrevClassTemplate = nullptr;
Douglas Gregorb74b1032010-04-18 17:37:40 +00001464 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +00001465
1466 // Check that the chosen semantic context doesn't already contain a
1467 // declaration of this name as a non-tag type.
Richard Smithfc805ca2015-07-06 04:43:58 +00001468 Previous.clear(LookupOrdinaryName);
Richard Smith6483d222012-04-21 01:27:54 +00001469 DeclContext *LookupContext = SemanticContext;
1470 while (LookupContext->isTransparentContext())
1471 LookupContext = LookupContext->getLookupParent();
1472 LookupQualifiedName(Previous, LookupContext);
1473
1474 if (Previous.isAmbiguous())
1475 return true;
1476
1477 if (Previous.begin() != Previous.end())
1478 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +00001479 }
John McCall90d3bb92009-12-17 23:21:11 +00001480 }
Richard Smith72bcaec2013-12-05 04:30:04 +00001481 } else if (PrevDecl &&
Richard Smithfc805ca2015-07-06 04:43:58 +00001482 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1483 S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +00001484 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001485
Richard Smithfc805ca2015-07-06 04:43:58 +00001486 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1487 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1488 if (SS.isEmpty() &&
1489 !(PrevClassTemplate &&
1490 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1491 SemanticContext->getRedeclContext()))) {
1492 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1493 Diag(Shadow->getTargetDecl()->getLocation(),
1494 diag::note_using_decl_target);
1495 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1496 // Recover by ignoring the old declaration.
1497 PrevDecl = PrevClassTemplate = nullptr;
1498 }
1499 }
1500
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001501 // TODO Memory management; associated constraints are not always stored.
1502 Expr *const CurAC = formAssociatedConstraints(TemplateParams, nullptr);
1503
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001504 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +00001505 // Ensure that the template parameter lists are compatible. Skip this check
1506 // for a friend in a dependent context: the template parameter list itself
1507 // could be dependent.
1508 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1509 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001510 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001511 /*Complain=*/true,
1512 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001513 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001514
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001515 // Check for matching associated constraints on redeclarations.
1516 const Expr *const PrevAC = PrevClassTemplate->getAssociatedConstraints();
1517 const bool RedeclACMismatch = [&] {
1518 if (!(CurAC || PrevAC))
1519 return false; // Nothing to check; no mismatch.
1520 if (CurAC && PrevAC) {
1521 llvm::FoldingSetNodeID CurACInfo, PrevACInfo;
1522 CurAC->Profile(CurACInfo, Context, /*Canonical=*/true);
1523 PrevAC->Profile(PrevACInfo, Context, /*Canonical=*/true);
1524 if (CurACInfo == PrevACInfo)
1525 return false; // All good; no mismatch.
1526 }
1527 return true;
1528 }();
1529
1530 if (RedeclACMismatch) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001531 Diag(CurAC ? CurAC->getBeginLoc() : NameLoc,
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001532 diag::err_template_different_associated_constraints);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001533 Diag(PrevAC ? PrevAC->getBeginLoc() : PrevClassTemplate->getLocation(),
1534 diag::note_template_prev_declaration)
1535 << /*declaration*/ 0;
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001536 return true;
1537 }
1538
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001539 // C++ [temp.class]p4:
1540 // In a redeclaration, partial specialization, explicit
1541 // specialization or explicit instantiation of a class template,
1542 // the class-key shall agree in kind with the original class
1543 // template declaration (7.1.5.3).
1544 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +00001545 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001546 TUK == TUK_Definition, KWLoc, Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00001547 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00001548 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00001549 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001550 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00001551 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001552 }
1553
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001554 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +00001555 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001556 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001557 // If we have a prior definition that is not visible, treat this as
1558 // simply making that previous definition visible.
1559 NamedDecl *Hidden = nullptr;
1560 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
Richard Smithd9ba2242015-05-07 03:54:19 +00001561 SkipBody->ShouldSkip = true;
Richard Smithc4577662018-09-12 02:13:47 +00001562 SkipBody->Previous = Def;
Richard Smithbe3980b2015-03-27 00:41:57 +00001563 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1564 assert(Tmpl && "original definition of a class template is not a "
1565 "class template?");
Richard Smith858e0e02017-05-11 23:11:16 +00001566 makeMergedDefinitionVisible(Hidden);
1567 makeMergedDefinitionVisible(Tmpl);
Richard Smithc4577662018-09-12 02:13:47 +00001568 } else {
1569 Diag(NameLoc, diag::err_redefinition) << Name;
1570 Diag(Def->getLocation(), diag::note_previous_definition);
1571 // FIXME: Would it make sense to try to "forget" the previous
1572 // definition, as part of error recovery?
1573 return true;
Richard Smithbe3980b2015-03-27 00:41:57 +00001574 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001575 }
Serge Pavlove50bf752016-06-10 04:39:07 +00001576 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001577 } else if (PrevDecl) {
1578 // C++ [temp]p5:
1579 // A class template shall not have the same name as any other
1580 // template, class, function, object, enumeration, enumerator,
1581 // namespace, or type in the same scope (3.3), except as specified
1582 // in (14.5.4).
1583 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1584 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001585 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001586 }
1587
Douglas Gregordba32632009-02-10 19:49:53 +00001588 // Check the template parameter list of this declaration, possibly
1589 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001590 // template declaration. Skip this check for a friend in a dependent
1591 // context, because the template parameter list might be dependent.
1592 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001593 CheckTemplateParameterList(
1594 TemplateParams,
Richard Smithc4577662018-09-12 02:13:47 +00001595 PrevClassTemplate
1596 ? PrevClassTemplate->getMostRecentDecl()->getTemplateParameters()
1597 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001598 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1599 SemanticContext->isDependentContext())
1600 ? TPC_ClassTemplateMember
Richard Smithc4577662018-09-12 02:13:47 +00001601 : TUK == TUK_Friend ? TPC_FriendClassTemplate : TPC_ClassTemplate,
1602 SkipBody))
Douglas Gregordba32632009-02-10 19:49:53 +00001603 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001604
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001605 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001606 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001607 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001608 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1609 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001610 : diag::err_member_decl_does_not_match)
1611 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001612 Invalid = true;
1613 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001614 }
1615
Vassil Vassilev352e4412017-01-12 09:16:26 +00001616 // If this is a templated friend in a dependent context we should not put it
1617 // on the redecl chain. In some cases, the templated friend can be the most
1618 // recent declaration tricking the template instantiator to make substitutions
1619 // there.
1620 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1621 bool ShouldAddRedecl
1622 = !(TUK == TUK_Friend && CurContext->isDependentContext());
1623
Mike Stump11289f42009-09-09 15:08:12 +00001624 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001625 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Vassil Vassilev352e4412017-01-12 09:16:26 +00001626 PrevClassTemplate && ShouldAddRedecl ?
Craig Topperc3ec1492014-05-26 06:22:03 +00001627 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001628 /*DelayTypeCreation=*/true);
Bruno Ricci4224c872018-12-21 14:35:24 +00001629 SetNestedNameSpecifier(*this, NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001630 if (NumOuterTemplateParamLists > 0)
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001631 NewClass->setTemplateParameterListsInfo(
1632 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1633 NumOuterTemplateParamLists));
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001634
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001635 // Add alignment attributes if necessary; these attributes are checked when
1636 // the ASTContext lays out the structure.
Richard Smithc4577662018-09-12 02:13:47 +00001637 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
Eli Friedman0415f3e12012-08-08 21:08:34 +00001638 AddAlignmentAttributesForRecord(NewClass);
1639 AddMsStructLayoutForRecord(NewClass);
1640 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001641
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001642 // Attach the associated constraints when the declaration will not be part of
1643 // a decl chain.
1644 Expr *const ACtoAttach =
1645 PrevClassTemplate && ShouldAddRedecl ? nullptr : CurAC;
1646
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001647 ClassTemplateDecl *NewTemplate
1648 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1649 DeclarationName(Name), TemplateParams,
Hubert Tong5a8ec4e2017-02-10 02:46:19 +00001650 NewClass, ACtoAttach);
Vassil Vassilev352e4412017-01-12 09:16:26 +00001651
1652 if (ShouldAddRedecl)
1653 NewTemplate->setPreviousDecl(PrevClassTemplate);
1654
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001655 NewClass->setDescribedClassTemplate(NewTemplate);
Simon Pilgrim6905d222016-12-30 22:55:33 +00001656
Douglas Gregor21823bf2011-12-20 18:11:52 +00001657 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001658 NewTemplate->setModulePrivate();
Simon Pilgrim6905d222016-12-30 22:55:33 +00001659
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001660 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001661 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001662 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001663 assert(T->isDependentType() && "Class template type is not dependent?");
1664 (void)T;
1665
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001666 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001667 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001668 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001669 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1670 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001671
Anders Carlsson137108d2009-03-26 01:24:28 +00001672 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001673 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001674 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001675
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001676 // Set the lexical context of these templates
1677 NewClass->setLexicalDeclContext(CurContext);
1678 NewTemplate->setLexicalDeclContext(CurContext);
1679
Richard Smithc4577662018-09-12 02:13:47 +00001680 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001681 NewClass->startDefinition();
1682
Erich Keanec480f302018-07-12 21:09:05 +00001683 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001684
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001685 if (PrevClassTemplate)
1686 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1687
Rafael Espindola385c0422012-07-13 18:04:45 +00001688 AddPushedVisibilityAttribute(NewClass);
1689
Richard Smith234ff472014-08-23 00:49:01 +00001690 if (TUK != TUK_Friend) {
1691 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1692 Scope *Outer = S;
1693 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1694 Outer = Outer->getParent();
1695 PushOnScopeChains(NewTemplate, Outer);
1696 } else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001697 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001698 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001699 NewClass->setAccess(PrevClassTemplate->getAccess());
1700 }
John McCall27b5c252009-09-14 21:59:20 +00001701
Richard Smith64017682013-07-17 23:53:16 +00001702 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001703
John McCall27b5c252009-09-14 21:59:20 +00001704 // Friend templates are visible in fairly strange ways.
1705 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001706 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001707 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001708 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1709 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001710 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001711 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001712
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001713 FriendDecl *Friend = FriendDecl::Create(
1714 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
Douglas Gregor3dad8422009-09-26 06:47:28 +00001715 Friend->setAccess(AS_public);
1716 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001717 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001718
Richard Smithbecb92d2017-10-10 22:33:17 +00001719 if (PrevClassTemplate)
1720 CheckRedeclarationModuleOwnership(NewTemplate, PrevClassTemplate);
1721
Douglas Gregordba32632009-02-10 19:49:53 +00001722 if (Invalid) {
1723 NewTemplate->setInvalidDecl();
1724 NewClass->setInvalidDecl();
1725 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001726
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001727 ActOnDocumentableDecl(NewTemplate);
1728
Richard Smithc4577662018-09-12 02:13:47 +00001729 if (SkipBody && SkipBody->ShouldSkip)
1730 return SkipBody->Previous;
1731
John McCall48871652010-08-21 09:40:31 +00001732 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001733}
1734
Richard Smith32918772017-02-14 00:25:28 +00001735namespace {
Erik Pilkington69770d32018-07-27 21:23:48 +00001736/// Tree transform to "extract" a transformed type from a class template's
1737/// constructor to a deduction guide.
1738class ExtractTypeForDeductionGuide
1739 : public TreeTransform<ExtractTypeForDeductionGuide> {
1740public:
1741 typedef TreeTransform<ExtractTypeForDeductionGuide> Base;
1742 ExtractTypeForDeductionGuide(Sema &SemaRef) : Base(SemaRef) {}
1743
1744 TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); }
1745
1746 QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) {
1747 return TransformType(
1748 TLB,
1749 TL.getTypedefNameDecl()->getTypeSourceInfo()->getTypeLoc());
1750 }
1751};
1752
Richard Smith32918772017-02-14 00:25:28 +00001753/// Transform to convert portions of a constructor declaration into the
1754/// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
1755struct ConvertConstructorToDeductionGuideTransform {
1756 ConvertConstructorToDeductionGuideTransform(Sema &S,
1757 ClassTemplateDecl *Template)
1758 : SemaRef(S), Template(Template) {}
1759
1760 Sema &SemaRef;
1761 ClassTemplateDecl *Template;
1762
1763 DeclContext *DC = Template->getDeclContext();
1764 CXXRecordDecl *Primary = Template->getTemplatedDecl();
1765 DeclarationName DeductionGuideName =
1766 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
1767
1768 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
1769
1770 // Index adjustment to apply to convert depth-1 template parameters into
1771 // depth-0 template parameters.
1772 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
1773
1774 /// Transform a constructor declaration into a deduction guide.
Richard Smithbc491202017-02-17 20:05:37 +00001775 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
1776 CXXConstructorDecl *CD) {
Richard Smith32918772017-02-14 00:25:28 +00001777 SmallVector<TemplateArgument, 16> SubstArgs;
1778
Richard Smithb4f96252017-02-21 06:30:38 +00001779 LocalInstantiationScope Scope(SemaRef);
1780
Richard Smith32918772017-02-14 00:25:28 +00001781 // C++ [over.match.class.deduct]p1:
1782 // -- For each constructor of the class template designated by the
1783 // template-name, a function template with the following properties:
1784
1785 // -- The template parameters are the template parameters of the class
1786 // template followed by the template parameters (including default
1787 // template arguments) of the constructor, if any.
1788 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
1789 if (FTD) {
1790 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
1791 SmallVector<NamedDecl *, 16> AllParams;
1792 AllParams.reserve(TemplateParams->size() + InnerParams->size());
1793 AllParams.insert(AllParams.begin(),
1794 TemplateParams->begin(), TemplateParams->end());
1795 SubstArgs.reserve(InnerParams->size());
1796
1797 // Later template parameters could refer to earlier ones, so build up
1798 // a list of substituted template arguments as we go.
1799 for (NamedDecl *Param : *InnerParams) {
1800 MultiLevelTemplateArgumentList Args;
1801 Args.addOuterTemplateArguments(SubstArgs);
Richard Smithb4f96252017-02-21 06:30:38 +00001802 Args.addOuterRetainedLevel();
Richard Smith32918772017-02-14 00:25:28 +00001803 NamedDecl *NewParam = transformTemplateParameter(Param, Args);
1804 if (!NewParam)
1805 return nullptr;
1806 AllParams.push_back(NewParam);
1807 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
1808 SemaRef.Context.getInjectedTemplateArg(NewParam)));
1809 }
1810 TemplateParams = TemplateParameterList::Create(
1811 SemaRef.Context, InnerParams->getTemplateLoc(),
1812 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
1813 /*FIXME: RequiresClause*/ nullptr);
1814 }
1815
1816 // If we built a new template-parameter-list, track that we need to
1817 // substitute references to the old parameters into references to the
1818 // new ones.
1819 MultiLevelTemplateArgumentList Args;
1820 if (FTD) {
1821 Args.addOuterTemplateArguments(SubstArgs);
Richard Smithb4f96252017-02-21 06:30:38 +00001822 Args.addOuterRetainedLevel();
Richard Smith32918772017-02-14 00:25:28 +00001823 }
1824
Richard Smithbc491202017-02-17 20:05:37 +00001825 FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
Richard Smith32918772017-02-14 00:25:28 +00001826 .getAsAdjusted<FunctionProtoTypeLoc>();
1827 assert(FPTL && "no prototype for constructor declaration");
1828
1829 // Transform the type of the function, adjusting the return type and
1830 // replacing references to the old parameters with references to the
1831 // new ones.
1832 TypeLocBuilder TLB;
1833 SmallVector<ParmVarDecl*, 8> Params;
1834 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args);
1835 if (NewType.isNull())
1836 return nullptr;
1837 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
1838
Richard Smith76b90272019-05-09 03:59:21 +00001839 return buildDeductionGuide(TemplateParams, CD->getExplicitSpecifier(),
1840 NewTInfo, CD->getBeginLoc(), CD->getLocation(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001841 CD->getEndLoc());
Richard Smith32918772017-02-14 00:25:28 +00001842 }
1843
1844 /// Build a deduction guide with the specified parameter types.
1845 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
1846 SourceLocation Loc = Template->getLocation();
1847
1848 // Build the requested type.
1849 FunctionProtoType::ExtProtoInfo EPI;
1850 EPI.HasTrailingReturn = true;
1851 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
1852 DeductionGuideName, EPI);
1853 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
1854
1855 FunctionProtoTypeLoc FPTL =
1856 TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
1857
1858 // Build the parameters, needed during deduction / substitution.
1859 SmallVector<ParmVarDecl*, 4> Params;
1860 for (auto T : ParamTypes) {
1861 ParmVarDecl *NewParam = ParmVarDecl::Create(
1862 SemaRef.Context, DC, Loc, Loc, nullptr, T,
1863 SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
1864 NewParam->setScopeInfo(0, Params.size());
1865 FPTL.setParam(Params.size(), NewParam);
1866 Params.push_back(NewParam);
1867 }
1868
Richard Smith76b90272019-05-09 03:59:21 +00001869 return buildDeductionGuide(Template->getTemplateParameters(),
1870 ExplicitSpecifier(), TSI, Loc, Loc, Loc);
Richard Smith32918772017-02-14 00:25:28 +00001871 }
1872
1873private:
1874 /// Transform a constructor template parameter into a deduction guide template
1875 /// parameter, rebuilding any internal references to earlier parameters and
1876 /// renumbering as we go.
1877 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
1878 MultiLevelTemplateArgumentList &Args) {
1879 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
1880 // TemplateTypeParmDecl's index cannot be changed after creation, so
1881 // substitute it directly.
1882 auto *NewTTP = TemplateTypeParmDecl::Create(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001883 SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(),
1884 /*Depth*/ 0, Depth1IndexAdjustment + TTP->getIndex(),
Richard Smith32918772017-02-14 00:25:28 +00001885 TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
1886 TTP->isParameterPack());
1887 if (TTP->hasDefaultArgument()) {
1888 TypeSourceInfo *InstantiatedDefaultArg =
1889 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
1890 TTP->getDefaultArgumentLoc(), TTP->getDeclName());
1891 if (InstantiatedDefaultArg)
1892 NewTTP->setDefaultArgument(InstantiatedDefaultArg);
1893 }
Richard Smithb4f96252017-02-21 06:30:38 +00001894 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
1895 NewTTP);
Richard Smith32918772017-02-14 00:25:28 +00001896 return NewTTP;
1897 }
1898
1899 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
1900 return transformTemplateParameterImpl(TTP, Args);
1901
1902 return transformTemplateParameterImpl(
1903 cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
1904 }
1905 template<typename TemplateParmDecl>
1906 TemplateParmDecl *
1907 transformTemplateParameterImpl(TemplateParmDecl *OldParam,
1908 MultiLevelTemplateArgumentList &Args) {
1909 // Ask the template instantiator to do the heavy lifting for us, then adjust
1910 // the index of the parameter once it's done.
1911 auto *NewParam =
1912 cast_or_null<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
1913 assert(NewParam->getDepth() == 0 && "unexpected template param depth");
1914 NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
1915 return NewParam;
1916 }
1917
1918 QualType transformFunctionProtoType(TypeLocBuilder &TLB,
1919 FunctionProtoTypeLoc TL,
1920 SmallVectorImpl<ParmVarDecl*> &Params,
1921 MultiLevelTemplateArgumentList &Args) {
1922 SmallVector<QualType, 4> ParamTypes;
1923 const FunctionProtoType *T = TL.getTypePtr();
1924
1925 // -- The types of the function parameters are those of the constructor.
1926 for (auto *OldParam : TL.getParams()) {
Richard Smithc27b3d72017-02-14 01:49:59 +00001927 ParmVarDecl *NewParam = transformFunctionTypeParam(OldParam, Args);
Richard Smith32918772017-02-14 00:25:28 +00001928 if (!NewParam)
1929 return QualType();
1930 ParamTypes.push_back(NewParam->getType());
1931 Params.push_back(NewParam);
1932 }
1933
1934 // -- The return type is the class template specialization designated by
1935 // the template-name and template arguments corresponding to the
1936 // template parameters obtained from the class template.
1937 //
1938 // We use the injected-class-name type of the primary template instead.
1939 // This has the convenient property that it is different from any type that
1940 // the user can write in a deduction-guide (because they cannot enter the
1941 // context of the template), so implicit deduction guides can never collide
1942 // with explicit ones.
1943 QualType ReturnType = DeducedType;
1944 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
1945
1946 // Resolving a wording defect, we also inherit the variadicness of the
1947 // constructor.
1948 FunctionProtoType::ExtProtoInfo EPI;
1949 EPI.Variadic = T->isVariadic();
1950 EPI.HasTrailingReturn = true;
1951
1952 QualType Result = SemaRef.BuildFunctionType(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001953 ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI);
Richard Smith32918772017-02-14 00:25:28 +00001954 if (Result.isNull())
1955 return QualType();
1956
1957 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
1958 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
1959 NewTL.setLParenLoc(TL.getLParenLoc());
1960 NewTL.setRParenLoc(TL.getRParenLoc());
1961 NewTL.setExceptionSpecRange(SourceRange());
1962 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
1963 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
1964 NewTL.setParam(I, Params[I]);
1965
1966 return Result;
1967 }
1968
1969 ParmVarDecl *
1970 transformFunctionTypeParam(ParmVarDecl *OldParam,
1971 MultiLevelTemplateArgumentList &Args) {
1972 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
Richard Smith479ba8e2017-04-20 01:15:31 +00001973 TypeSourceInfo *NewDI;
Erik Pilkington69770d32018-07-27 21:23:48 +00001974 if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
Richard Smith479ba8e2017-04-20 01:15:31 +00001975 // Expand out the one and only element in each inner pack.
1976 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
1977 NewDI =
1978 SemaRef.SubstType(PackTL.getPatternLoc(), Args,
1979 OldParam->getLocation(), OldParam->getDeclName());
1980 if (!NewDI) return nullptr;
1981 NewDI =
1982 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
1983 PackTL.getTypePtr()->getNumExpansions());
1984 } else
1985 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
1986 OldParam->getDeclName());
Richard Smith32918772017-02-14 00:25:28 +00001987 if (!NewDI)
1988 return nullptr;
1989
Erik Pilkington69770d32018-07-27 21:23:48 +00001990 // Extract the type. This (for instance) replaces references to typedef
1991 // members of the current instantiations with the definitions of those
1992 // typedefs, avoiding triggering instantiation of the deduced type during
1993 // deduction.
1994 NewDI = ExtractTypeForDeductionGuide(SemaRef).transform(NewDI);
Richard Smithc27b3d72017-02-14 01:49:59 +00001995
Richard Smith32918772017-02-14 00:25:28 +00001996 // Resolving a wording defect, we also inherit default arguments from the
1997 // constructor.
1998 ExprResult NewDefArg;
1999 if (OldParam->hasDefaultArg()) {
Erik Pilkington69770d32018-07-27 21:23:48 +00002000 NewDefArg = SemaRef.SubstExpr(OldParam->getDefaultArg(), Args);
Richard Smith32918772017-02-14 00:25:28 +00002001 if (NewDefArg.isInvalid())
2002 return nullptr;
2003 }
2004
2005 ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
2006 OldParam->getInnerLocStart(),
2007 OldParam->getLocation(),
2008 OldParam->getIdentifier(),
2009 NewDI->getType(),
2010 NewDI,
2011 OldParam->getStorageClass(),
2012 NewDefArg.get());
2013 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
2014 OldParam->getFunctionScopeIndex());
Erik Pilkington69770d32018-07-27 21:23:48 +00002015 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);
Richard Smith32918772017-02-14 00:25:28 +00002016 return NewParam;
2017 }
2018
2019 NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams,
Richard Smith76b90272019-05-09 03:59:21 +00002020 ExplicitSpecifier ES, TypeSourceInfo *TInfo,
Richard Smith32918772017-02-14 00:25:28 +00002021 SourceLocation LocStart, SourceLocation Loc,
2022 SourceLocation LocEnd) {
Richard Smithbc491202017-02-17 20:05:37 +00002023 DeclarationNameInfo Name(DeductionGuideName, Loc);
Richard Smithefa919a2017-02-16 21:29:21 +00002024 ArrayRef<ParmVarDecl *> Params =
2025 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
2026
Richard Smith32918772017-02-14 00:25:28 +00002027 // Build the implicit deduction guide template.
Richard Smithbc491202017-02-17 20:05:37 +00002028 auto *Guide =
Richard Smith76b90272019-05-09 03:59:21 +00002029 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, ES, Name,
2030 TInfo->getType(), TInfo, LocEnd);
Richard Smith32918772017-02-14 00:25:28 +00002031 Guide->setImplicit();
Richard Smithefa919a2017-02-16 21:29:21 +00002032 Guide->setParams(Params);
2033
2034 for (auto *Param : Params)
2035 Param->setDeclContext(Guide);
Richard Smith32918772017-02-14 00:25:28 +00002036
2037 auto *GuideTemplate = FunctionTemplateDecl::Create(
2038 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
2039 GuideTemplate->setImplicit();
2040 Guide->setDescribedFunctionTemplate(GuideTemplate);
2041
2042 if (isa<CXXRecordDecl>(DC)) {
2043 Guide->setAccess(AS_public);
2044 GuideTemplate->setAccess(AS_public);
2045 }
2046
2047 DC->addDecl(GuideTemplate);
2048 return GuideTemplate;
2049 }
2050};
2051}
2052
2053void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
2054 SourceLocation Loc) {
Gauthier Harnischb63e5772019-06-14 08:40:04 +00002055 if (CXXRecordDecl *DefRecord =
2056 cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
2057 TemplateDecl *DescribedTemplate = DefRecord->getDescribedClassTemplate();
2058 Template = DescribedTemplate ? DescribedTemplate : Template;
2059 }
2060
Richard Smith32918772017-02-14 00:25:28 +00002061 DeclContext *DC = Template->getDeclContext();
2062 if (DC->isDependentContext())
2063 return;
2064
2065 ConvertConstructorToDeductionGuideTransform Transform(
2066 *this, cast<ClassTemplateDecl>(Template));
2067 if (!isCompleteType(Loc, Transform.DeducedType))
2068 return;
2069
2070 // Check whether we've already declared deduction guides for this template.
2071 // FIXME: Consider storing a flag on the template to indicate this.
2072 auto Existing = DC->lookup(Transform.DeductionGuideName);
2073 for (auto *D : Existing)
2074 if (D->isImplicit())
2075 return;
2076
2077 // In case we were expanding a pack when we attempted to declare deduction
2078 // guides, turn off pack expansion for everything we're about to do.
2079 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2080 // Create a template instantiation record to track the "instantiation" of
2081 // constructors into deduction guides.
2082 // FIXME: Add a kind for this to give more meaningful diagnostics. But can
2083 // this substitution process actually fail?
2084 InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
Volodymyr Sapsai2f649f32018-05-14 22:49:44 +00002085 if (BuildingDeductionGuides.isInvalid())
2086 return;
Richard Smith32918772017-02-14 00:25:28 +00002087
2088 // Convert declared constructors into deduction guide templates.
2089 // FIXME: Skip constructors for which deduction must necessarily fail (those
2090 // for which some class template parameter without a default argument never
2091 // appears in a deduced context).
2092 bool AddedAny = false;
Richard Smith32918772017-02-14 00:25:28 +00002093 for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
2094 D = D->getUnderlyingDecl();
2095 if (D->isInvalidDecl() || D->isImplicit())
2096 continue;
2097 D = cast<NamedDecl>(D->getCanonicalDecl());
2098
2099 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
Richard Smithbc491202017-02-17 20:05:37 +00002100 auto *CD =
2101 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
Richard Smith32918772017-02-14 00:25:28 +00002102 // Class-scope explicit specializations (MS extension) do not result in
2103 // deduction guides.
Richard Smithbc491202017-02-17 20:05:37 +00002104 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
Richard Smith32918772017-02-14 00:25:28 +00002105 continue;
2106
Richard Smithbc491202017-02-17 20:05:37 +00002107 Transform.transformConstructor(FTD, CD);
Richard Smith32918772017-02-14 00:25:28 +00002108 AddedAny = true;
Richard Smith32918772017-02-14 00:25:28 +00002109 }
2110
Faisal Vali81b756e2017-10-22 14:45:08 +00002111 // C++17 [over.match.class.deduct]
2112 // -- If C is not defined or does not declare any constructors, an
2113 // additional function template derived as above from a hypothetical
2114 // constructor C().
Richard Smith32918772017-02-14 00:25:28 +00002115 if (!AddedAny)
2116 Transform.buildSimpleDeductionGuide(None);
2117
Faisal Vali81b756e2017-10-22 14:45:08 +00002118 // -- An additional function template derived as above from a hypothetical
2119 // constructor C(C), called the copy deduction candidate.
2120 cast<CXXDeductionGuideDecl>(
2121 cast<FunctionTemplateDecl>(
2122 Transform.buildSimpleDeductionGuide(Transform.DeducedType))
2123 ->getTemplatedDecl())
2124 ->setIsCopyDeductionCandidate();
Richard Smith32918772017-02-14 00:25:28 +00002125}
2126
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002127/// Diagnose the presence of a default template argument on a
Douglas Gregored5731f2009-11-25 17:50:39 +00002128/// template parameter, which is ill-formed in certain contexts.
2129///
2130/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002131static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00002132 Sema::TemplateParamListContext TPC,
2133 SourceLocation ParamLoc,
2134 SourceRange DefArgRange) {
2135 switch (TPC) {
2136 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00002137 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00002138 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00002139 return false;
2140
2141 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00002142 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002143 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00002144 // A default template-argument shall not be specified in a
2145 // function template declaration or a function template
2146 // definition [...]
Simon Pilgrim6905d222016-12-30 22:55:33 +00002147 // If a friend function template declaration specifies a default
Douglas Gregora99fb4c2011-02-04 04:20:44 +00002148 // template-argument, that declaration shall be a definition and shall be
2149 // the only declaration of the function template in the translation unit.
2150 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002151 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002152 diag::warn_cxx98_compat_template_parameter_default_in_function_template
2153 : diag::ext_template_parameter_default_in_function_template)
2154 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00002155 return false;
2156
2157 case Sema::TPC_ClassTemplateMember:
2158 // C++0x [temp.param]p9:
2159 // A default template-argument shall not be specified in the
2160 // template-parameter-lists of the definition of a member of a
2161 // class template that appears outside of the member's class.
2162 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2163 << DefArgRange;
2164 return true;
2165
David Majnemerba8f17a2013-06-25 22:08:55 +00002166 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00002167 case Sema::TPC_FriendFunctionTemplate:
2168 // C++ [temp.param]p9:
2169 // A default template-argument shall not be specified in a
2170 // friend template declaration.
2171 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2172 << DefArgRange;
2173 return true;
2174
2175 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2176 // for friend function templates if there is only a single
2177 // declaration (and it is a definition). Strange!
2178 }
2179
David Blaikie8a40f702012-01-17 06:56:22 +00002180 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00002181}
2182
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002183/// Check for unexpanded parameter packs within the template parameters
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002184/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00002185static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2186 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00002187 // A template template parameter which is a parameter pack is also a pack
2188 // expansion.
2189 if (TTP->isParameterPack())
2190 return false;
2191
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002192 TemplateParameterList *Params = TTP->getTemplateParameters();
2193 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2194 NamedDecl *P = Params->getParam(I);
2195 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00002196 if (!NTTP->isParameterPack() &&
2197 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002198 NTTP->getTypeSourceInfo(),
2199 Sema::UPPC_NonTypeTemplateParameterType))
2200 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002201
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002202 continue;
2203 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002204
2205 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002206 = dyn_cast<TemplateTemplateParmDecl>(P))
2207 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2208 return true;
2209 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002210
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002211 return false;
2212}
2213
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002214/// Checks the validity of a template parameter list, possibly
Douglas Gregordba32632009-02-10 19:49:53 +00002215/// considering the template parameter list from a previous
2216/// declaration.
2217///
2218/// If an "old" template parameter list is provided, it must be
2219/// equivalent (per TemplateParameterListsAreEqual) to the "new"
2220/// template parameter list.
2221///
2222/// \param NewParams Template parameter list for a new template
2223/// declaration. This template parameter list will be updated with any
2224/// default arguments that are carried through from the previous
2225/// template parameter list.
2226///
2227/// \param OldParams If provided, template parameter list from a
2228/// previous declaration of the same template. Default template
2229/// arguments will be merged from the old template parameter list to
2230/// the new template parameter list.
2231///
Douglas Gregored5731f2009-11-25 17:50:39 +00002232/// \param TPC Describes the context in which we are checking the given
2233/// template parameter list.
2234///
Richard Smithc4577662018-09-12 02:13:47 +00002235/// \param SkipBody If we might have already made a prior merged definition
2236/// of this template visible, the corresponding body-skipping information.
2237/// Default argument redefinition is not an error when skipping such a body,
2238/// because (under the ODR) we can assume the default arguments are the same
2239/// as the prior merged definition.
2240///
Douglas Gregordba32632009-02-10 19:49:53 +00002241/// \returns true if an error occurred, false otherwise.
2242bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00002243 TemplateParameterList *OldParams,
Richard Smithc4577662018-09-12 02:13:47 +00002244 TemplateParamListContext TPC,
2245 SkipBodyInfo *SkipBody) {
Douglas Gregordba32632009-02-10 19:49:53 +00002246 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00002247
Douglas Gregordba32632009-02-10 19:49:53 +00002248 // C++ [temp.param]p10:
2249 // The set of default template-arguments available for use with a
2250 // template declaration or definition is obtained by merging the
2251 // default arguments from the definition (if in scope) and all
2252 // declarations in scope in the same way default function
2253 // arguments are (8.3.6).
2254 bool SawDefaultArgument = false;
2255 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00002256
Mike Stumpc89c8e32009-02-11 23:03:27 +00002257 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00002258 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00002259 if (OldParams)
2260 OldParam = OldParams->begin();
2261
Douglas Gregor0693def2011-01-27 01:40:17 +00002262 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00002263 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2264 NewParamEnd = NewParams->end();
2265 NewParam != NewParamEnd; ++NewParam) {
2266 // Variables used to diagnose redundant default arguments
2267 bool RedundantDefaultArg = false;
2268 SourceLocation OldDefaultLoc;
2269 SourceLocation NewDefaultLoc;
2270
David Blaikie651c73c2011-10-19 05:19:50 +00002271 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00002272 bool MissingDefaultArg = false;
2273
David Blaikie651c73c2011-10-19 05:19:50 +00002274 // Variable used to diagnose non-final parameter packs
2275 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00002276
Douglas Gregordba32632009-02-10 19:49:53 +00002277 if (TemplateTypeParmDecl *NewTypeParm
2278 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00002279 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002280 if (NewTypeParm->hasDefaultArgument() &&
2281 DiagnoseDefaultTemplateArgument(*this, TPC,
2282 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002283 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002284 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00002285 NewTypeParm->removeDefaultArgument();
2286
2287 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00002288 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002289 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Anders Carlsson327865d2009-06-12 23:20:15 +00002290 if (NewTypeParm->isParameterPack()) {
2291 assert(!NewTypeParm->hasDefaultArgument() &&
2292 "Parameter packs can't have a default argument!");
2293 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002294 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
Richard Smithc4577662018-09-12 02:13:47 +00002295 NewTypeParm->hasDefaultArgument() &&
2296 (!SkipBody || !SkipBody->ShouldSkip)) {
Douglas Gregordba32632009-02-10 19:49:53 +00002297 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2298 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2299 SawDefaultArgument = true;
2300 RedundantDefaultArg = true;
2301 PreviousDefaultArgLoc = NewDefaultLoc;
2302 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2303 // Merge the default argument from the old declaration to the
2304 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002305 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00002306 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2307 } else if (NewTypeParm->hasDefaultArgument()) {
2308 SawDefaultArgument = true;
2309 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2310 } else if (SawDefaultArgument)
2311 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00002312 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00002313 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002314 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002315 if (!NewNonTypeParm->isParameterPack() &&
2316 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002317 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002318 UPPC_NonTypeTemplateParameterType)) {
2319 Invalid = true;
2320 continue;
2321 }
2322
Douglas Gregored5731f2009-11-25 17:50:39 +00002323 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002324 if (NewNonTypeParm->hasDefaultArgument() &&
2325 DiagnoseDefaultTemplateArgument(*this, TPC,
2326 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002327 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00002328 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00002329 }
2330
Mike Stump12b8ce12009-08-04 21:02:39 +00002331 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00002332 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002333 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00002334 if (NewNonTypeParm->isParameterPack()) {
2335 assert(!NewNonTypeParm->hasDefaultArgument() &&
2336 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00002337 if (!NewNonTypeParm->isPackExpansion())
2338 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002339 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
Richard Smithc4577662018-09-12 02:13:47 +00002340 NewNonTypeParm->hasDefaultArgument() &&
2341 (!SkipBody || !SkipBody->ShouldSkip)) {
Douglas Gregordba32632009-02-10 19:49:53 +00002342 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2343 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2344 SawDefaultArgument = true;
2345 RedundantDefaultArg = true;
2346 PreviousDefaultArgLoc = NewDefaultLoc;
2347 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2348 // Merge the default argument from the old declaration to the
2349 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002350 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00002351 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2352 } else if (NewNonTypeParm->hasDefaultArgument()) {
2353 SawDefaultArgument = true;
2354 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2355 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002356 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00002357 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00002358 TemplateTemplateParmDecl *NewTemplateParm
2359 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002360
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002361 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00002362 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002363 Invalid = true;
2364 continue;
2365 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002366
David Blaikie651c73c2011-10-19 05:19:50 +00002367 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002368 if (NewTemplateParm->hasDefaultArgument() &&
2369 DiagnoseDefaultTemplateArgument(*this, TPC,
2370 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002371 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00002372 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00002373
2374 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00002375 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002376 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00002377 if (NewTemplateParm->isParameterPack()) {
2378 assert(!NewTemplateParm->hasDefaultArgument() &&
2379 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00002380 if (!NewTemplateParm->isPackExpansion())
2381 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002382 } else if (OldTemplateParm &&
2383 hasVisibleDefaultArgument(OldTemplateParm) &&
Richard Smithc4577662018-09-12 02:13:47 +00002384 NewTemplateParm->hasDefaultArgument() &&
2385 (!SkipBody || !SkipBody->ShouldSkip)) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002386 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2387 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002388 SawDefaultArgument = true;
2389 RedundantDefaultArg = true;
2390 PreviousDefaultArgLoc = NewDefaultLoc;
2391 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2392 // Merge the default argument from the old declaration to the
2393 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002394 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002395 PreviousDefaultArgLoc
2396 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002397 } else if (NewTemplateParm->hasDefaultArgument()) {
2398 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002399 PreviousDefaultArgLoc
2400 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002401 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002402 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00002403 }
2404
Richard Smith1fde8ec2012-09-07 02:06:42 +00002405 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00002406 // If a template parameter of a primary class template or alias template
2407 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002408 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00002409 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2410 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00002411 Diag((*NewParam)->getLocation(),
2412 diag::err_template_param_pack_must_be_last_template_parameter);
2413 Invalid = true;
2414 }
2415
Douglas Gregordba32632009-02-10 19:49:53 +00002416 if (RedundantDefaultArg) {
2417 // C++ [temp.param]p12:
2418 // A template-parameter shall not be given default arguments
2419 // by two different declarations in the same scope.
2420 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2421 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2422 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00002423 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00002424 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002425 // If a template-parameter of a class template has a default
2426 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00002427 // have a default template-argument supplied or be a template parameter
2428 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00002429 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00002430 diag::err_template_param_default_arg_missing);
2431 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2432 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00002433 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00002434 }
2435
2436 // If we have an old template parameter list that we're merging
2437 // in, move on to the next parameter.
2438 if (OldParams)
2439 ++OldParam;
2440 }
2441
Douglas Gregor0693def2011-01-27 01:40:17 +00002442 // We were missing some default arguments at the end of the list, so remove
2443 // all of the default arguments.
2444 if (RemoveDefaultArguments) {
2445 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2446 NewParamEnd = NewParams->end();
2447 NewParam != NewParamEnd; ++NewParam) {
2448 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2449 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002450 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00002451 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2452 NTTP->removeDefaultArgument();
2453 else
2454 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2455 }
2456 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002457
Douglas Gregordba32632009-02-10 19:49:53 +00002458 return Invalid;
2459}
Douglas Gregord32e0282009-02-09 23:23:08 +00002460
John McCalla020a012010-10-20 05:44:58 +00002461namespace {
2462
2463/// A class which looks for a use of a certain level of template
2464/// parameter.
2465struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2466 typedef RecursiveASTVisitor<DependencyChecker> super;
2467
2468 unsigned Depth;
Richard Smith57aae072016-12-28 02:37:25 +00002469
2470 // Whether we're looking for a use of a template parameter that makes the
2471 // overall construct type-dependent / a dependent type. This is strictly
2472 // best-effort for now; we may fail to match at all for a dependent type
2473 // in some cases if this is set.
2474 bool IgnoreNonTypeDependent;
2475
John McCalla020a012010-10-20 05:44:58 +00002476 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00002477 SourceLocation MatchLoc;
2478
Richard Smith13894182017-04-13 21:37:24 +00002479 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2480 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2481 Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00002482
Richard Smith57aae072016-12-28 02:37:25 +00002483 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
Richard Smith13894182017-04-13 21:37:24 +00002484 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2485 NamedDecl *ND = Params->getParam(0);
2486 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2487 Depth = PD->getDepth();
2488 } else if (NonTypeTemplateParmDecl *PD =
2489 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2490 Depth = PD->getDepth();
2491 } else {
2492 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2493 }
2494 }
John McCalla020a012010-10-20 05:44:58 +00002495
Richard Smith6056d5e2014-02-09 00:54:43 +00002496 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
Richard Smith13894182017-04-13 21:37:24 +00002497 if (ParmDepth >= Depth) {
John McCalla020a012010-10-20 05:44:58 +00002498 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00002499 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00002500 return true;
2501 }
2502 return false;
2503 }
2504
Richard Smith57aae072016-12-28 02:37:25 +00002505 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2506 // Prune out non-type-dependent expressions if requested. This can
2507 // sometimes result in us failing to find a template parameter reference
2508 // (if a value-dependent expression creates a dependent type), but this
2509 // mode is best-effort only.
2510 if (auto *E = dyn_cast_or_null<Expr>(S))
2511 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2512 return true;
2513 return super::TraverseStmt(S, Q);
2514 }
2515
2516 bool TraverseTypeLoc(TypeLoc TL) {
2517 if (IgnoreNonTypeDependent && !TL.isNull() &&
2518 !TL.getType()->isDependentType())
2519 return true;
2520 return super::TraverseTypeLoc(TL);
2521 }
2522
Richard Smith6056d5e2014-02-09 00:54:43 +00002523 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2524 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2525 }
2526
John McCalla020a012010-10-20 05:44:58 +00002527 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
Richard Smith57aae072016-12-28 02:37:25 +00002528 // For a best-effort search, keep looking until we find a location.
2529 return IgnoreNonTypeDependent || !Matches(T->getDepth());
John McCalla020a012010-10-20 05:44:58 +00002530 }
2531
2532 bool TraverseTemplateName(TemplateName N) {
2533 if (TemplateTemplateParmDecl *PD =
2534 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00002535 if (Matches(PD->getDepth()))
2536 return false;
John McCalla020a012010-10-20 05:44:58 +00002537 return super::TraverseTemplateName(N);
2538 }
2539
2540 bool VisitDeclRefExpr(DeclRefExpr *E) {
2541 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00002542 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2543 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00002544 return false;
John McCalla020a012010-10-20 05:44:58 +00002545 return super::VisitDeclRefExpr(E);
2546 }
Richard Smith6056d5e2014-02-09 00:54:43 +00002547
2548 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2549 return TraverseType(T->getReplacementType());
2550 }
2551
2552 bool
2553 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2554 return TraverseTemplateArgument(T->getArgumentPack());
2555 }
2556
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00002557 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2558 return TraverseType(T->getInjectedSpecializationType());
2559 }
John McCalla020a012010-10-20 05:44:58 +00002560};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002561} // end anonymous namespace
John McCalla020a012010-10-20 05:44:58 +00002562
Douglas Gregor972fe532011-05-10 18:27:06 +00002563/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00002564/// list.
2565static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00002566DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
Richard Smith57aae072016-12-28 02:37:25 +00002567 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
Douglas Gregor972fe532011-05-10 18:27:06 +00002568 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00002569 return Checker.Match;
2570}
2571
Douglas Gregor972fe532011-05-10 18:27:06 +00002572// Find the source range corresponding to the named type in the given
2573// nested-name-specifier, if any.
2574static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2575 QualType T,
2576 const CXXScopeSpec &SS) {
2577 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2578 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2579 if (const Type *CurType = NNS->getAsType()) {
2580 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2581 return NNSLoc.getTypeLoc().getSourceRange();
2582 } else
2583 break;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002584
Douglas Gregor972fe532011-05-10 18:27:06 +00002585 NNSLoc = NNSLoc.getPrefix();
2586 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002587
Douglas Gregor972fe532011-05-10 18:27:06 +00002588 return SourceRange();
2589}
2590
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002591/// Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00002592/// specifier, returning the template parameter list that applies to the
2593/// name.
2594///
2595/// \param DeclStartLoc the start of the declaration that has a scope
2596/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00002597///
Douglas Gregor972fe532011-05-10 18:27:06 +00002598/// \param DeclLoc The location of the declaration itself.
2599///
Douglas Gregord8d297c2009-07-21 23:53:31 +00002600/// \param SS the scope specifier that will be matched to the given template
2601/// parameter lists. This scope specifier precedes a qualified name that is
2602/// being declared.
2603///
Richard Smith4b55a9c2014-04-17 03:29:33 +00002604/// \param TemplateId The template-id following the scope specifier, if there
2605/// is one. Used to check for a missing 'template<>'.
2606///
Douglas Gregord8d297c2009-07-21 23:53:31 +00002607/// \param ParamLists the template parameter lists, from the outermost to the
2608/// innermost template parameter lists.
2609///
John McCalle820e5e2010-04-13 20:37:33 +00002610/// \param IsFriend Whether to apply the slightly different rules for
2611/// matching template parameters to scope specifiers in friend
2612/// declarations.
2613///
Richard Smithf445f192017-02-09 21:04:43 +00002614/// \param IsMemberSpecialization will be set true if the scope specifier
2615/// denotes a fully-specialized type, and therefore this is a declaration of
2616/// a member specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002617///
Mike Stump11289f42009-09-09 15:08:12 +00002618/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00002619/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00002620/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00002621/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00002622/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00002623/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002624TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2625 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00002626 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002627 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
Richard Smithf445f192017-02-09 21:04:43 +00002628 bool &IsMemberSpecialization, bool &Invalid) {
2629 IsMemberSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00002630 Invalid = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002631
Douglas Gregor972fe532011-05-10 18:27:06 +00002632 // The sequence of nested types to which we will match up the template
2633 // parameter lists. We first build this list by starting with the type named
2634 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002635 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00002636 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00002637 if (SS.getScopeRep()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002638 if (CXXRecordDecl *Record
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00002639 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2640 T = Context.getTypeDeclType(Record);
2641 else
2642 T = QualType(SS.getScopeRep()->getAsType(), 0);
2643 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002644
Douglas Gregor972fe532011-05-10 18:27:06 +00002645 // If we found an explicit specialization that prevents us from needing
2646 // 'template<>' headers, this will be set to the location of that
2647 // explicit specialization.
2648 SourceLocation ExplicitSpecLoc;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002649
Douglas Gregor972fe532011-05-10 18:27:06 +00002650 while (!T.isNull()) {
2651 NestedTypes.push_back(T);
Simon Pilgrim6905d222016-12-30 22:55:33 +00002652
Douglas Gregor972fe532011-05-10 18:27:06 +00002653 // Retrieve the parent of a record type.
2654 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2655 // If this type is an explicit specialization, we're done.
2656 if (ClassTemplateSpecializationDecl *Spec
2657 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002658 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002659 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2660 ExplicitSpecLoc = Spec->getLocation();
2661 break;
Douglas Gregor65911492009-11-23 12:11:45 +00002662 }
Douglas Gregor972fe532011-05-10 18:27:06 +00002663 } else if (Record->getTemplateSpecializationKind()
2664 == TSK_ExplicitSpecialization) {
2665 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00002666 break;
2667 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002668
Douglas Gregor972fe532011-05-10 18:27:06 +00002669 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2670 T = Context.getTypeDeclType(Parent);
2671 else
2672 T = QualType();
2673 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002674 }
2675
Douglas Gregor972fe532011-05-10 18:27:06 +00002676 if (const TemplateSpecializationType *TST
2677 = T->getAs<TemplateSpecializationType>()) {
2678 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2679 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2680 T = Context.getTypeDeclType(Parent);
2681 else
2682 T = QualType();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002683 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002684 }
Douglas Gregor972fe532011-05-10 18:27:06 +00002685 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002686
Douglas Gregor972fe532011-05-10 18:27:06 +00002687 // Look one step prior in a dependent template specialization type.
2688 if (const DependentTemplateSpecializationType *DependentTST
2689 = T->getAs<DependentTemplateSpecializationType>()) {
2690 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2691 T = QualType(NNS->getAsType(), 0);
2692 else
2693 T = QualType();
2694 continue;
2695 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002696
Douglas Gregor972fe532011-05-10 18:27:06 +00002697 // Look one step prior in a dependent name type.
2698 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2699 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2700 T = QualType(NNS->getAsType(), 0);
2701 else
2702 T = QualType();
2703 continue;
2704 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002705
Douglas Gregor972fe532011-05-10 18:27:06 +00002706 // Retrieve the parent of an enumeration type.
2707 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2708 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2709 // check here.
2710 EnumDecl *Enum = EnumT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002711
Douglas Gregor972fe532011-05-10 18:27:06 +00002712 // Get to the parent type.
2713 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2714 T = Context.getTypeDeclType(Parent);
2715 else
Simon Pilgrim6905d222016-12-30 22:55:33 +00002716 T = QualType();
Douglas Gregor972fe532011-05-10 18:27:06 +00002717 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002718 }
Mike Stump11289f42009-09-09 15:08:12 +00002719
Douglas Gregor972fe532011-05-10 18:27:06 +00002720 T = QualType();
2721 }
2722 // Reverse the nested types list, since we want to traverse from the outermost
2723 // to the innermost while checking template-parameter-lists.
2724 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00002725
Douglas Gregor972fe532011-05-10 18:27:06 +00002726 // C++0x [temp.expl.spec]p17:
2727 // A member or a member template may be nested within many
2728 // enclosing class templates. In an explicit specialization for
2729 // such a member, the member declaration shall be preceded by a
2730 // template<> for each enclosing class template that is
2731 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002732 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00002733
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002734 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00002735 if (SawNonEmptyTemplateParameterList) {
2736 Diag(DeclLoc, diag::err_specialize_member_of_template)
2737 << !Recovery << Range;
2738 Invalid = true;
Richard Smithf445f192017-02-09 21:04:43 +00002739 IsMemberSpecialization = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00002740 return true;
2741 }
2742
2743 return false;
2744 };
2745
2746 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2747 // Check that we can have an explicit specialization here.
2748 if (CheckExplicitSpecialization(Range, true))
2749 return true;
2750
2751 // We don't have a template header, but we should.
2752 SourceLocation ExpectedTemplateLoc;
2753 if (!ParamLists.empty())
2754 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2755 else
2756 ExpectedTemplateLoc = DeclStartLoc;
2757
2758 Diag(DeclLoc, diag::err_template_spec_needs_header)
2759 << Range
2760 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2761 return false;
2762 };
2763
Douglas Gregor972fe532011-05-10 18:27:06 +00002764 unsigned ParamIdx = 0;
2765 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2766 ++TypeIdx) {
2767 T = NestedTypes[TypeIdx];
Simon Pilgrim6905d222016-12-30 22:55:33 +00002768
Douglas Gregor972fe532011-05-10 18:27:06 +00002769 // Whether we expect a 'template<>' header.
2770 bool NeedEmptyTemplateHeader = false;
2771
2772 // Whether we expect a template header with parameters.
2773 bool NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002774
Douglas Gregor972fe532011-05-10 18:27:06 +00002775 // For a dependent type, the set of template parameters that we
2776 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00002777 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002778
Douglas Gregor373af9b2011-05-11 23:26:17 +00002779 // C++0x [temp.expl.spec]p15:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002780 // A member or a member template may be nested within many enclosing
2781 // class templates. In an explicit specialization for such a member, the
2782 // member declaration shall be preceded by a template<> for each
Douglas Gregor373af9b2011-05-11 23:26:17 +00002783 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00002784 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2785 if (ClassTemplatePartialSpecializationDecl *Partial
2786 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2787 ExpectedTemplateParams = Partial->getTemplateParameters();
2788 NeedNonemptyTemplateHeader = true;
2789 } else if (Record->isDependentType()) {
2790 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00002791 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00002792 ->getTemplateParameters();
2793 NeedNonemptyTemplateHeader = true;
2794 }
2795 } else if (ClassTemplateSpecializationDecl *Spec
2796 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2797 // C++0x [temp.expl.spec]p4:
2798 // Members of an explicitly specialized class template are defined
Simon Pilgrim6905d222016-12-30 22:55:33 +00002799 // in the same manner as members of normal classes, and not using
2800 // the template<> syntax.
Douglas Gregor972fe532011-05-10 18:27:06 +00002801 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2802 NeedEmptyTemplateHeader = true;
2803 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00002804 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002805 } else if (Record->getTemplateSpecializationKind()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002806 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00002807 != TSK_ExplicitSpecialization &&
2808 TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002809 IsMemberSpecialization = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002810
Douglas Gregor373af9b2011-05-11 23:26:17 +00002811 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002812 }
2813 } else if (const TemplateSpecializationType *TST
2814 = T->getAs<TemplateSpecializationType>()) {
Nico Weber28900612015-01-30 02:35:21 +00002815 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002816 ExpectedTemplateParams = Template->getTemplateParameters();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002817 NeedNonemptyTemplateHeader = true;
Douglas Gregor972fe532011-05-10 18:27:06 +00002818 }
2819 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2820 // FIXME: We actually could/should check the template arguments here
2821 // against the corresponding template parameter list.
2822 NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002823 }
2824
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002825 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002826 // In an explicit specialization declaration for a member of a class
2827 // template or a member template that ap- pears in namespace scope, the
2828 // member template and some of its enclosing class templates may remain
2829 // unspecialized, except that the declaration shall not explicitly
2830 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002831 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002832 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002833 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002834 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2835 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002836 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002837 } else
2838 SawNonEmptyTemplateParameterList = true;
2839 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002840
Douglas Gregor972fe532011-05-10 18:27:06 +00002841 if (NeedEmptyTemplateHeader) {
2842 // If we're on the last of the types, and we need a 'template<>' header
Richard Smithf445f192017-02-09 21:04:43 +00002843 // here, then it's a member specialization.
Douglas Gregor972fe532011-05-10 18:27:06 +00002844 if (TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002845 IsMemberSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002846
2847 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002848 if (ParamLists[ParamIdx]->size() > 0) {
2849 // The header has template parameters when it shouldn't. Complain.
Simon Pilgrim6905d222016-12-30 22:55:33 +00002850 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregor972fe532011-05-10 18:27:06 +00002851 diag::err_template_param_list_matches_nontemplate)
2852 << T
2853 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2854 ParamLists[ParamIdx]->getRAngleLoc())
2855 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2856 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002857 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002858 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002859
Douglas Gregor972fe532011-05-10 18:27:06 +00002860 // Consume this template header.
2861 ++ParamIdx;
2862 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002863 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002864
2865 if (!IsFriend)
2866 if (DiagnoseMissingExplicitSpecialization(
2867 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00002868 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002869
Douglas Gregor972fe532011-05-10 18:27:06 +00002870 continue;
2871 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002872
Douglas Gregor972fe532011-05-10 18:27:06 +00002873 if (NeedNonemptyTemplateHeader) {
2874 // In friend declarations we can have template-ids which don't
2875 // depend on the corresponding template parameter lists. But
2876 // assume that empty parameter lists are supposed to match this
2877 // template-id.
2878 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002879 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002880 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00002881 ExpectedTemplateParams = nullptr;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002882 else
Douglas Gregor972fe532011-05-10 18:27:06 +00002883 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002884 }
Douglas Gregored5731f2009-11-25 17:50:39 +00002885
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002886 if (ParamIdx < ParamLists.size()) {
2887 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00002888 if (ExpectedTemplateParams &&
2889 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2890 ExpectedTemplateParams,
2891 true, TPL_TemplateMatch))
2892 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002893
Douglas Gregor972fe532011-05-10 18:27:06 +00002894 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00002895 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00002896 TPC_ClassTemplateMember))
2897 Invalid = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002898
Douglas Gregor972fe532011-05-10 18:27:06 +00002899 ++ParamIdx;
2900 continue;
2901 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002902
Douglas Gregor972fe532011-05-10 18:27:06 +00002903 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2904 << T
2905 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2906 Invalid = true;
2907 continue;
2908 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00002909 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00002910
Douglas Gregord8d297c2009-07-21 23:53:31 +00002911 // If there were at least as many template-ids as there were template
2912 // parameter lists, then there are no template parameter lists remaining for
2913 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00002914 if (ParamIdx >= ParamLists.size()) {
2915 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00002916 // We don't have a template header for the declaration itself, but we
2917 // should.
Richard Smith11a80dc2014-04-17 03:52:20 +00002918 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2919 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00002920
2921 // Fabricate an empty template parameter list for the invented header.
2922 return TemplateParameterList::Create(Context, SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +00002923 SourceLocation(), None,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00002924 SourceLocation(), nullptr);
Richard Smith4b55a9c2014-04-17 03:29:33 +00002925 }
2926
Craig Topperc3ec1492014-05-26 06:22:03 +00002927 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002928 }
Mike Stump11289f42009-09-09 15:08:12 +00002929
Douglas Gregord8d297c2009-07-21 23:53:31 +00002930 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002931 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002932 bool HasAnyExplicitSpecHeader = false;
2933 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002934 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002935 if (ParamLists[I]->size() == 0)
2936 HasAnyExplicitSpecHeader = true;
2937 else
2938 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002939 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002940
Douglas Gregor972fe532011-05-10 18:27:06 +00002941 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002942 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2943 : diag::err_template_spec_extra_headers)
2944 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2945 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00002946
2947 // If there was a specialization somewhere, such that 'template<>' is
2948 // not required, and there were any 'template<>' headers, note where the
2949 // specialization occurred.
2950 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
Simon Pilgrim6905d222016-12-30 22:55:33 +00002951 Diag(ExplicitSpecLoc,
Douglas Gregor972fe532011-05-10 18:27:06 +00002952 diag::note_explicit_template_spec_does_not_need_header)
2953 << NestedTypes.back();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002954
Douglas Gregor972fe532011-05-10 18:27:06 +00002955 // We have a template parameter list with no corresponding scope, which
2956 // means that the resulting template declaration can't be instantiated
2957 // properly (we'll end up with dependent nodes when we shouldn't).
2958 if (!AllExplicitSpecHeaders)
2959 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002960 }
Mike Stump11289f42009-09-09 15:08:12 +00002961
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002962 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002963 // In an explicit specialization declaration for a member of a class
2964 // template or a member template that ap- pears in namespace scope, the
2965 // member template and some of its enclosing class templates may remain
2966 // unspecialized, except that the declaration shall not explicitly
2967 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002968 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00002969 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002970 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2971 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002972 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002973
Douglas Gregord8d297c2009-07-21 23:53:31 +00002974 // Return the last template parameter list, which corresponds to the
2975 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002976 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00002977}
2978
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002979void Sema::NoteAllFoundTemplates(TemplateName Name) {
2980 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2981 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002982 << (isa<FunctionTemplateDecl>(Template)
2983 ? 0
2984 : isa<ClassTemplateDecl>(Template)
2985 ? 1
2986 : isa<VarTemplateDecl>(Template)
2987 ? 2
2988 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2989 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002990 return;
2991 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002992
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002993 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002994 for (OverloadedTemplateStorage::iterator I = OST->begin(),
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002995 IEnd = OST->end();
2996 I != IEnd; ++I)
2997 Diag((*I)->getLocation(), diag::note_template_declared_here)
2998 << 0 << (*I)->getDeclName();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002999
Douglas Gregor8b6070b2011-03-04 21:37:14 +00003000 return;
3001 }
3002}
3003
David Majnemerd9b1a4f2015-11-04 03:40:30 +00003004static QualType
3005checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
3006 const SmallVectorImpl<TemplateArgument> &Converted,
3007 SourceLocation TemplateLoc,
3008 TemplateArgumentListInfo &TemplateArgs) {
3009 ASTContext &Context = SemaRef.getASTContext();
3010 switch (BTD->getBuiltinTemplateKind()) {
Eric Fiselier6ad68552016-07-01 01:24:09 +00003011 case BTK__make_integer_seq: {
David Majnemerd9b1a4f2015-11-04 03:40:30 +00003012 // Specializations of __make_integer_seq<S, T, N> are treated like
3013 // S<T, 0, ..., N-1>.
3014
3015 // C++14 [inteseq.intseq]p1:
3016 // T shall be an integer type.
3017 if (!Converted[1].getAsType()->isIntegralType(Context)) {
3018 SemaRef.Diag(TemplateArgs[1].getLocation(),
3019 diag::err_integer_sequence_integral_element_type);
3020 return QualType();
3021 }
3022
3023 // C++14 [inteseq.make]p1:
3024 // If N is negative the program is ill-formed.
3025 TemplateArgument NumArgsArg = Converted[2];
3026 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
3027 if (NumArgs < 0) {
3028 SemaRef.Diag(TemplateArgs[2].getLocation(),
3029 diag::err_integer_sequence_negative_length);
3030 return QualType();
3031 }
3032
3033 QualType ArgTy = NumArgsArg.getIntegralType();
3034 TemplateArgumentListInfo SyntheticTemplateArgs;
3035 // The type argument gets reused as the first template argument in the
3036 // synthetic template argument list.
3037 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
3038 // Expand N into 0 ... N-1.
3039 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3040 I < NumArgs; ++I) {
3041 TemplateArgument TA(Context, I, ArgTy);
Richard Smith7873de02016-08-11 22:25:46 +00003042 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3043 TA, ArgTy, TemplateArgs[2].getLocation()));
David Majnemerd9b1a4f2015-11-04 03:40:30 +00003044 }
3045 // The first template argument will be reused as the template decl that
3046 // our synthetic template arguments will be applied to.
3047 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
3048 TemplateLoc, SyntheticTemplateArgs);
3049 }
Eric Fiselier6ad68552016-07-01 01:24:09 +00003050
3051 case BTK__type_pack_element:
3052 // Specializations of
3053 // __type_pack_element<Index, T_1, ..., T_N>
3054 // are treated like T_Index.
3055 assert(Converted.size() == 2 &&
3056 "__type_pack_element should be given an index and a parameter pack");
3057
3058 // If the Index is out of bounds, the program is ill-formed.
3059 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3060 llvm::APSInt Index = IndexArg.getAsIntegral();
3061 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3062 "type std::size_t, and hence be non-negative");
3063 if (Index >= Ts.pack_size()) {
3064 SemaRef.Diag(TemplateArgs[0].getLocation(),
3065 diag::err_type_pack_element_out_of_bounds);
3066 return QualType();
3067 }
3068
3069 // We simply return the type at index `Index`.
3070 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
3071 return Nth->getAsType();
3072 }
David Majnemerd9b1a4f2015-11-04 03:40:30 +00003073 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3074}
3075
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003076/// Determine whether this alias template is "enable_if_t".
3077static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3078 return AliasTemplate->getName().equals("enable_if_t");
3079}
3080
3081/// Collect all of the separable terms in the given condition, which
3082/// might be a conjunction.
3083///
3084/// FIXME: The right answer is to convert the logical expression into
3085/// disjunctive normal form, so we can find the first failed term
3086/// within each possible clause.
3087static void collectConjunctionTerms(Expr *Clause,
3088 SmallVectorImpl<Expr *> &Terms) {
3089 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3090 if (BinOp->getOpcode() == BO_LAnd) {
3091 collectConjunctionTerms(BinOp->getLHS(), Terms);
3092 collectConjunctionTerms(BinOp->getRHS(), Terms);
3093 }
3094
3095 return;
3096 }
3097
3098 Terms.push_back(Clause);
3099}
3100
Douglas Gregorbb33f572017-07-05 20:20:15 +00003101// The ranges-v3 library uses an odd pattern of a top-level "||" with
3102// a left-hand side that is value-dependent but never true. Identify
3103// the idiom and ignore that term.
3104static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3105 // Top-level '||'.
3106 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3107 if (!BinOp) return Cond;
3108
3109 if (BinOp->getOpcode() != BO_LOr) return Cond;
3110
3111 // With an inner '==' that has a literal on the right-hand side.
3112 Expr *LHS = BinOp->getLHS();
Douglas Gregorc0fe1f22017-07-05 21:12:37 +00003113 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
Douglas Gregorbb33f572017-07-05 20:20:15 +00003114 if (!InnerBinOp) return Cond;
3115
3116 if (InnerBinOp->getOpcode() != BO_EQ ||
3117 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3118 return Cond;
3119
3120 // If the inner binary operation came from a macro expansion named
3121 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3122 // of the '||', which is the real, user-provided condition.
Douglas Gregorc0fe1f22017-07-05 21:12:37 +00003123 SourceLocation Loc = InnerBinOp->getExprLoc();
Douglas Gregorbb33f572017-07-05 20:20:15 +00003124 if (!Loc.isMacroID()) return Cond;
3125
3126 StringRef MacroName = PP.getImmediateMacroName(Loc);
3127 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3128 return BinOp->getRHS();
3129
3130 return Cond;
3131}
3132
Clement Courbetf44c6f42018-12-11 08:39:11 +00003133namespace {
3134
3135// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3136// within failing boolean expression, such as substituting template parameters
3137// for actual types.
3138class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3139public:
3140 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3141 : Policy(P) {}
3142
3143 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3144 const auto *DR = dyn_cast<DeclRefExpr>(E);
3145 if (DR && DR->getQualifier()) {
3146 // If this is a qualified name, expand the template arguments in nested
3147 // qualifiers.
3148 DR->getQualifier()->print(OS, Policy, true);
3149 // Then print the decl itself.
3150 const ValueDecl *VD = DR->getDecl();
3151 OS << VD->getName();
3152 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3153 // This is a template variable, print the expanded template arguments.
3154 printTemplateArgumentList(OS, IV->getTemplateArgs().asArray(), Policy);
3155 }
3156 return true;
Clement Courbet9d432e02018-12-04 07:59:57 +00003157 }
Clement Courbetf44c6f42018-12-11 08:39:11 +00003158 return false;
Clement Courbet9d432e02018-12-04 07:59:57 +00003159 }
Clement Courbetf44c6f42018-12-11 08:39:11 +00003160
3161private:
3162 const PrintingPolicy Policy;
3163};
3164
3165} // end anonymous namespace
Clement Courbet9d432e02018-12-04 07:59:57 +00003166
Douglas Gregor672281a2017-09-14 23:38:42 +00003167std::pair<Expr *, std::string>
Clement Courbetf44c6f42018-12-11 08:39:11 +00003168Sema::findFailedBooleanCondition(Expr *Cond) {
Douglas Gregor672281a2017-09-14 23:38:42 +00003169 Cond = lookThroughRangesV3Condition(PP, Cond);
Douglas Gregorbb33f572017-07-05 20:20:15 +00003170
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003171 // Separate out all of the terms in a conjunction.
3172 SmallVector<Expr *, 4> Terms;
3173 collectConjunctionTerms(Cond, Terms);
3174
3175 // Determine which term failed.
3176 Expr *FailedCond = nullptr;
3177 for (Expr *Term : Terms) {
Douglas Gregor672281a2017-09-14 23:38:42 +00003178 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3179
Clement Courbetd8720412018-12-10 08:53:17 +00003180 // Literals are uninteresting.
3181 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3182 isa<IntegerLiteral>(TermAsWritten))
3183 continue;
3184
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003185 // The initialization of the parameter from the argument is
3186 // a constant-evaluated context.
3187 EnterExpressionEvaluationContext ConstantEvaluated(
Douglas Gregor672281a2017-09-14 23:38:42 +00003188 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003189
3190 bool Succeeded;
Douglas Gregor672281a2017-09-14 23:38:42 +00003191 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003192 !Succeeded) {
Douglas Gregor672281a2017-09-14 23:38:42 +00003193 FailedCond = TermAsWritten;
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003194 break;
3195 }
3196 }
Clement Courbetf44c6f42018-12-11 08:39:11 +00003197 if (!FailedCond)
Clement Courbetd8720412018-12-10 08:53:17 +00003198 FailedCond = Cond->IgnoreParenImpCasts();
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003199
3200 std::string Description;
3201 {
3202 llvm::raw_string_ostream Out(Description);
Clement Courbetfb2c74d2018-12-20 09:05:15 +00003203 PrintingPolicy Policy = getPrintingPolicy();
3204 Policy.PrintCanonicalTypes = true;
3205 FailedBooleanConditionPrinterHelper Helper(Policy);
3206 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003207 }
3208 return { FailedCond, Description };
3209}
3210
Douglas Gregordc572a32009-03-30 22:58:21 +00003211QualType Sema::CheckTemplateIdType(TemplateName Name,
3212 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003213 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00003214 DependentTemplateName *DTN
3215 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00003216 if (DTN && DTN->isIdentifier())
3217 // When building a template-id where the template-name is dependent,
3218 // assume the template is a type template. Either our assumption is
3219 // correct, or the code is ill-formed and will be diagnosed when the
3220 // dependent name is substituted.
3221 return Context.getDependentTemplateSpecializationType(ETK_None,
3222 DTN->getQualifier(),
3223 DTN->getIdentifier(),
3224 TemplateArgs);
3225
Douglas Gregordc572a32009-03-30 22:58:21 +00003226 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00003227 if (!Template || isa<FunctionTemplateDecl>(Template) ||
Faisal Valia534f072018-04-26 00:42:40 +00003228 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00003229 // We might have a substituted template template parameter pack. If so,
3230 // build a template specialization type for it.
3231 if (Name.getAsSubstTemplateTemplateParmPack())
3232 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003233
Douglas Gregor8b6070b2011-03-04 21:37:14 +00003234 Diag(TemplateLoc, diag::err_template_id_not_a_type)
3235 << Name;
3236 NoteAllFoundTemplates(Name);
3237 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00003238 }
Douglas Gregordc572a32009-03-30 22:58:21 +00003239
Douglas Gregorc40290e2009-03-09 23:48:35 +00003240 // Check that the template argument list is well-formed for this
3241 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003242 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00003243 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00003244 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00003245 return QualType();
3246
Douglas Gregorc40290e2009-03-09 23:48:35 +00003247 QualType CanonType;
3248
Douglas Gregor678d76c2011-07-01 01:22:09 +00003249 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00003250 if (TypeAliasTemplateDecl *AliasTemplate =
3251 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00003252 // Find the canonical type for this type alias template specialization.
3253 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3254 if (Pattern->isInvalidDecl())
3255 return QualType();
3256
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003257 TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack,
3258 Converted);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003259
3260 // Only substitute for the innermost template argument list.
3261 MultiLevelTemplateArgumentList TemplateArgLists;
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003262 TemplateArgLists.addOuterTemplateArguments(&StackTemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00003263 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
3264 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00003265 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003266
Richard Smith802c4b72012-08-23 06:16:52 +00003267 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003268 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003269 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003270 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00003271
Richard Smith3f1b5d02011-05-05 21:57:07 +00003272 CanonType = SubstType(Pattern->getUnderlyingType(),
3273 TemplateArgLists, AliasTemplate->getLocation(),
3274 AliasTemplate->getDeclName());
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003275 if (CanonType.isNull()) {
3276 // If this was enable_if and we failed to find the nested type
3277 // within enable_if in a SFINAE context, dig out the specific
3278 // enable_if condition that failed and present that instead.
3279 if (isEnableIfAliasTemplate(AliasTemplate)) {
3280 if (auto DeductionInfo = isSFINAEContext()) {
3281 if (*DeductionInfo &&
3282 (*DeductionInfo)->hasSFINAEDiagnostic() &&
3283 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3284 diag::err_typename_nested_not_found_enable_if &&
3285 TemplateArgs[0].getArgument().getKind()
3286 == TemplateArgument::Expression) {
3287 Expr *FailedCond;
3288 std::string FailedDescription;
3289 std::tie(FailedCond, FailedDescription) =
Clement Courbetf44c6f42018-12-11 08:39:11 +00003290 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003291
3292 // Remove the old SFINAE diagnostic.
3293 PartialDiagnosticAt OldDiag =
3294 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3295 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3296
3297 // Add a new SFINAE diagnostic specifying which condition
3298 // failed.
3299 (*DeductionInfo)->addSFINAEDiagnostic(
3300 OldDiag.first,
3301 PDiag(diag::err_typename_nested_not_found_requirement)
3302 << FailedDescription
3303 << FailedCond->getSourceRange());
3304 }
3305 }
3306 }
3307
Richard Smith3f1b5d02011-05-05 21:57:07 +00003308 return QualType();
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003309 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00003310 } else if (Name.isDependent() ||
3311 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00003312 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00003313 // This class template specialization is a dependent
3314 // type. Therefore, its canonical type is another class template
3315 // specialization type that contains all of the converted
3316 // arguments in canonical form. This ensures that, e.g., A<T> and
3317 // A<T, T> have identical types when A is declared as:
3318 //
3319 // template<typename T, typename U = T> struct A;
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00003320 CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
John McCall2408e322010-04-27 00:57:59 +00003321
3322 // This might work out to be a current instantiation, in which
3323 // case the canonical type needs to be the InjectedClassNameType.
3324 //
3325 // TODO: in theory this could be a simple hashtable lookup; most
3326 // changes to CurContext don't change the set of current
3327 // instantiations.
3328 if (isa<ClassTemplateDecl>(Template)) {
3329 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3330 // If we get out to a namespace, we're done.
3331 if (Ctx->isFileContext()) break;
3332
3333 // If this isn't a record, keep looking.
3334 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3335 if (!Record) continue;
3336
3337 // Look for one of the two cases with InjectedClassNameTypes
3338 // and check whether it's the same template.
3339 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3340 !Record->getDescribedClassTemplate())
3341 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003342
John McCall2408e322010-04-27 00:57:59 +00003343 // Fetch the injected class name type and check whether its
3344 // injected type is equal to the type we just built.
3345 QualType ICNT = Context.getTypeDeclType(Record);
3346 QualType Injected = cast<InjectedClassNameType>(ICNT)
3347 ->getInjectedSpecializationType();
3348
3349 if (CanonType != Injected->getCanonicalTypeInternal())
3350 continue;
3351
3352 // If so, the canonical type of this TST is the injected
3353 // class name type of the record we just found.
3354 assert(ICNT.isCanonical());
3355 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00003356 break;
3357 }
3358 }
Mike Stump11289f42009-09-09 15:08:12 +00003359 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00003360 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00003361 // Find the class template specialization declaration that
3362 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00003363 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00003364 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00003365 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003366 if (!Decl) {
3367 // This is the first time we have referenced this class template
3368 // specialization. Create the canonical declaration and add it to
3369 // the set of specializations.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003370 Decl = ClassTemplateSpecializationDecl::Create(
3371 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3372 ClassTemplate->getDeclContext(),
3373 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3374 ClassTemplate->getLocation(), ClassTemplate, Converted, nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003375 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00003376 if (ClassTemplate->isOutOfLine())
3377 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00003378 }
3379
Erich Keanea32910d2017-03-23 18:51:54 +00003380 if (Decl->getSpecializationKind() == TSK_Undeclared) {
3381 MultiLevelTemplateArgumentList TemplateArgLists;
3382 TemplateArgLists.addOuterTemplateArguments(Converted);
3383 InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(),
3384 Decl);
3385 }
3386
Chandler Carruth2acfb222013-09-27 22:14:40 +00003387 // Diagnose uses of this specialization.
3388 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3389
Douglas Gregorc40290e2009-03-09 23:48:35 +00003390 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00003391 assert(isa<RecordType>(CanonType) &&
3392 "type of non-dependent specialization is not a RecordType");
David Majnemerd9b1a4f2015-11-04 03:40:30 +00003393 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3394 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
3395 TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003396 }
Mike Stump11289f42009-09-09 15:08:12 +00003397
Douglas Gregorc40290e2009-03-09 23:48:35 +00003398 // Build the fully-sugared type for this class template
3399 // specialization, which refers back to the class template
3400 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00003401 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003402}
3403
Richard Smithb23c5e82019-05-09 03:31:27 +00003404void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,
3405 TemplateNameKind &TNK,
3406 SourceLocation NameLoc,
3407 IdentifierInfo *&II) {
3408 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
3409
3410 TemplateName Name = ParsedName.get();
3411 auto *ATN = Name.getAsAssumedTemplateName();
3412 assert(ATN && "not an assumed template name");
3413 II = ATN->getDeclName().getAsIdentifierInfo();
3414
3415 if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
3416 // Resolved to a type template name.
3417 ParsedName = TemplateTy::make(Name);
3418 TNK = TNK_Type_template;
3419 }
3420}
3421
3422bool Sema::resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
3423 SourceLocation NameLoc,
3424 bool Diagnose) {
3425 // We assumed this undeclared identifier to be an (ADL-only) function
3426 // template name, but it was used in a context where a type was required.
3427 // Try to typo-correct it now.
3428 AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
3429 assert(ATN && "not an assumed template name");
3430
3431 LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
3432 struct CandidateCallback : CorrectionCandidateCallback {
3433 bool ValidateCandidate(const TypoCorrection &TC) override {
3434 return TC.getCorrectionDecl() &&
3435 getAsTypeTemplateDecl(TC.getCorrectionDecl());
3436 }
3437 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3438 return llvm::make_unique<CandidateCallback>(*this);
3439 }
3440 } FilterCCC;
3441
3442 TypoCorrection Corrected =
3443 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
3444 FilterCCC, CTK_ErrorRecovery);
3445 if (Corrected && Corrected.getFoundDecl()) {
3446 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
3447 << ATN->getDeclName());
3448 Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>());
3449 return false;
3450 }
3451
3452 if (Diagnose)
3453 Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
3454 return true;
3455}
3456
3457TypeResult Sema::ActOnTemplateIdType(
3458 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3459 TemplateTy TemplateD, IdentifierInfo *TemplateII,
3460 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
3461 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
3462 bool IsCtorOrDtorName, bool IsClassName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00003463 if (SS.isInvalid())
3464 return true;
3465
Richard Smith62559bd2017-02-01 21:36:38 +00003466 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3467 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3468
3469 // C++ [temp.res]p3:
3470 // A qualified-id that refers to a type and in which the
3471 // nested-name-specifier depends on a template-parameter (14.6.2)
3472 // shall be prefixed by the keyword typename to indicate that the
3473 // qualified-id denotes a type, forming an
3474 // elaborated-type-specifier (7.1.5.3).
3475 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
Richard Smith3411fbf2017-02-01 21:41:18 +00003476 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
Richard Smith62559bd2017-02-01 21:36:38 +00003477 << SS.getScopeRep() << TemplateII->getName();
3478 // Recover as if 'typename' were specified.
3479 // FIXME: This is not quite correct recovery as we don't transform SS
3480 // into the corresponding dependent form (and we don't diagnose missing
3481 // 'template' keywords within SS as a result).
3482 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3483 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3484 TemplateArgsIn, RAngleLoc);
3485 }
3486
3487 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3488 // it's not actually allowed to be used as a type in most cases. Because
3489 // we annotate it before we know whether it's valid, we have to check for
3490 // this case here.
3491 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
Richard Smith74f02342017-01-19 21:00:13 +00003492 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3493 Diag(TemplateIILoc,
3494 TemplateKWLoc.isInvalid()
3495 ? diag::err_out_of_line_qualified_id_type_names_constructor
3496 : diag::ext_out_of_line_qualified_id_type_names_constructor)
3497 << TemplateII << 0 /*injected-class-name used as template name*/
3498 << 1 /*if any keyword was present, it was 'template'*/;
3499 }
3500 }
3501
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003502 TemplateName Template = TemplateD.get();
Richard Smithb23c5e82019-05-09 03:31:27 +00003503 if (Template.getAsAssumedTemplateName() &&
3504 resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
3505 return true;
Douglas Gregor8bf42052009-02-09 18:46:07 +00003506
Douglas Gregorc40290e2009-03-09 23:48:35 +00003507 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003508 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003509 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00003510
Douglas Gregor5a064722011-02-28 17:23:35 +00003511 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00003512 QualType T
3513 = Context.getDependentTemplateSpecializationType(ETK_None,
3514 DTN->getQualifier(),
3515 DTN->getIdentifier(),
3516 TemplateArgs);
3517 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00003518 TypeLocBuilder TLB;
3519 DependentTemplateSpecializationTypeLoc SpecTL
3520 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003521 SpecTL.setElaboratedKeywordLoc(SourceLocation());
3522 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00003523 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00003524 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00003525 SpecTL.setLAngleLoc(LAngleLoc);
3526 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00003527 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3528 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3529 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3530 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003531
Richard Smith74f02342017-01-19 21:00:13 +00003532 QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003533 if (Result.isNull())
3534 return true;
3535
Douglas Gregore7c20652011-03-02 00:47:37 +00003536 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003537 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00003538 TemplateSpecializationTypeLoc SpecTL
3539 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003540 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00003541 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003542 SpecTL.setLAngleLoc(LAngleLoc);
3543 SpecTL.setRAngleLoc(RAngleLoc);
3544 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3545 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00003546
Abramo Bagnara4244b432012-01-27 08:46:19 +00003547 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
3548 // constructor or destructor name (in such a case, the scope specifier
3549 // will be attached to the enclosing Decl or Expr node).
3550 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00003551 // Create an elaborated-type-specifier containing the nested-name-specifier.
3552 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
3553 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00003554 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00003555 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3556 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003557
Douglas Gregore7c20652011-03-02 00:47:37 +00003558 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00003559}
John McCall06f6fe8d2009-09-04 01:14:41 +00003560
Douglas Gregore7c20652011-03-02 00:47:37 +00003561TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00003562 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00003563 SourceLocation TagLoc,
3564 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003565 SourceLocation TemplateKWLoc,
3566 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00003567 SourceLocation TemplateLoc,
3568 SourceLocation LAngleLoc,
3569 ASTTemplateArgsPtr TemplateArgsIn,
3570 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003571 TemplateName Template = TemplateD.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00003572
Douglas Gregore7c20652011-03-02 00:47:37 +00003573 // Translate the parser's template argument list in our AST format.
3574 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3575 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003576
Douglas Gregore7c20652011-03-02 00:47:37 +00003577 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00003578 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00003579 ElaboratedTypeKeyword Keyword
3580 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00003581
Douglas Gregore7c20652011-03-02 00:47:37 +00003582 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3583 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
Simon Pilgrim6905d222016-12-30 22:55:33 +00003584 DTN->getQualifier(),
3585 DTN->getIdentifier(),
Douglas Gregore7c20652011-03-02 00:47:37 +00003586 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003587
3588 // Build type-source information.
Douglas Gregore7c20652011-03-02 00:47:37 +00003589 TypeLocBuilder TLB;
3590 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003591 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3592 SpecTL.setElaboratedKeywordLoc(TagLoc);
3593 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00003594 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003595 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003596 SpecTL.setLAngleLoc(LAngleLoc);
3597 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003598 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3599 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3600 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3601 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00003602
3603 if (TypeAliasTemplateDecl *TAT =
3604 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3605 // C++0x [dcl.type.elab]p2:
3606 // If the identifier resolves to a typedef-name or the simple-template-id
3607 // resolves to an alias template specialization, the
3608 // elaborated-type-specifier is ill-formed.
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00003609 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3610 << TAT << NTK_TypeAliasTemplate << TagKind;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003611 Diag(TAT->getLocation(), diag::note_declared_at);
3612 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003613
Douglas Gregore7c20652011-03-02 00:47:37 +00003614 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3615 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00003616 return TypeResult(true);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003617
Douglas Gregore7c20652011-03-02 00:47:37 +00003618 // Check the tag kind
3619 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00003620 RecordDecl *D = RT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00003621
John McCalld8fe9af2009-09-08 17:47:29 +00003622 IdentifierInfo *Id = D->getIdentifier();
3623 assert(Id && "templated class must have an identifier");
Simon Pilgrim6905d222016-12-30 22:55:33 +00003624
Richard Trieucaa33d32011-06-10 03:11:26 +00003625 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00003626 TagLoc, Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00003627 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00003628 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00003629 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00003630 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00003631 }
3632 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003633
Douglas Gregore7c20652011-03-02 00:47:37 +00003634 // Provide source-location information for the template specialization.
3635 TypeLocBuilder TLB;
3636 TemplateSpecializationTypeLoc SpecTL
3637 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003638 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003639 SpecTL.setTemplateNameLoc(TemplateLoc);
3640 SpecTL.setLAngleLoc(LAngleLoc);
3641 SpecTL.setRAngleLoc(RAngleLoc);
3642 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3643 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00003644
Douglas Gregore7c20652011-03-02 00:47:37 +00003645 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003646 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00003647 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3648 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00003649 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003650 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3651 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003652}
3653
Larisse Voufo39a1e502013-08-06 01:03:05 +00003654static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3655 NamedDecl *PrevDecl,
3656 SourceLocation Loc,
3657 bool IsPartialSpecialization);
3658
3659static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003660
Richard Smith300e0c32013-09-24 04:49:23 +00003661static bool isTemplateArgumentTemplateParameter(
3662 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3663 switch (Arg.getKind()) {
3664 case TemplateArgument::Null:
3665 case TemplateArgument::NullPtr:
3666 case TemplateArgument::Integral:
3667 case TemplateArgument::Declaration:
3668 case TemplateArgument::Pack:
3669 case TemplateArgument::TemplateExpansion:
3670 return false;
3671
3672 case TemplateArgument::Type: {
3673 QualType Type = Arg.getAsType();
3674 const TemplateTypeParmType *TPT =
3675 Arg.getAsType()->getAs<TemplateTypeParmType>();
3676 return TPT && !Type.hasQualifiers() &&
3677 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3678 }
3679
3680 case TemplateArgument::Expression: {
3681 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3682 if (!DRE || !DRE->getDecl())
3683 return false;
3684 const NonTypeTemplateParmDecl *NTTP =
3685 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3686 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3687 }
3688
3689 case TemplateArgument::Template:
3690 const TemplateTemplateParmDecl *TTP =
3691 dyn_cast_or_null<TemplateTemplateParmDecl>(
3692 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
3693 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3694 }
3695 llvm_unreachable("unexpected kind of template argument");
3696}
3697
3698static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
3699 ArrayRef<TemplateArgument> Args) {
3700 if (Params->size() != Args.size())
3701 return false;
3702
3703 unsigned Depth = Params->getDepth();
3704
3705 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3706 TemplateArgument Arg = Args[I];
3707
3708 // If the parameter is a pack expansion, the argument must be a pack
3709 // whose only element is a pack expansion.
3710 if (Params->getParam(I)->isParameterPack()) {
3711 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3712 !Arg.pack_begin()->isPackExpansion())
3713 return false;
3714 Arg = Arg.pack_begin()->getPackExpansionPattern();
3715 }
3716
3717 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3718 return false;
3719 }
3720
3721 return true;
3722}
3723
Richard Smith4b55a9c2014-04-17 03:29:33 +00003724/// Convert the parser's template argument list representation into our form.
3725static TemplateArgumentListInfo
3726makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
3727 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
3728 TemplateId.RAngleLoc);
3729 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
3730 TemplateId.NumArgs);
3731 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
3732 return TemplateArgs;
3733}
3734
Richard Smith0e617ec2016-12-27 07:56:27 +00003735template<typename PartialSpecDecl>
3736static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3737 if (Partial->getDeclContext()->isDependentContext())
3738 return;
3739
3740 // FIXME: Get the TDK from deduction in order to provide better diagnostics
3741 // for non-substitution-failure issues?
3742 TemplateDeductionInfo Info(Partial->getLocation());
3743 if (S.isMoreSpecializedThanPrimary(Partial, Info))
3744 return;
3745
3746 auto *Template = Partial->getSpecializedTemplate();
3747 S.Diag(Partial->getLocation(),
Richard Smithfa4a09d2016-12-27 20:03:09 +00003748 diag::ext_partial_spec_not_more_specialized_than_primary)
3749 << isa<VarTemplateDecl>(Template);
Richard Smith0e617ec2016-12-27 07:56:27 +00003750
3751 if (Info.hasSFINAEDiagnostic()) {
3752 PartialDiagnosticAt Diag = {SourceLocation(),
3753 PartialDiagnostic::NullDiagnostic()};
3754 Info.takeSFINAEDiagnostic(Diag);
3755 SmallString<128> SFINAEArgString;
3756 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3757 S.Diag(Diag.first,
3758 diag::note_partial_spec_not_more_specialized_than_primary)
3759 << SFINAEArgString;
3760 }
3761
3762 S.Diag(Template->getLocation(), diag::note_template_decl_here);
3763}
3764
Richard Smith4e05eaa2017-02-16 00:36:47 +00003765static void
3766noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
3767 const llvm::SmallBitVector &DeducibleParams) {
3768 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3769 if (!DeducibleParams[I]) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00003770 NamedDecl *Param = TemplateParams->getParam(I);
Richard Smith4e05eaa2017-02-16 00:36:47 +00003771 if (Param->getDeclName())
3772 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3773 << Param->getDeclName();
3774 else
3775 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3776 << "(anonymous)";
3777 }
3778 }
3779}
3780
3781
Richard Smith57aae072016-12-28 02:37:25 +00003782template<typename PartialSpecDecl>
3783static void checkTemplatePartialSpecialization(Sema &S,
3784 PartialSpecDecl *Partial) {
3785 // C++1z [temp.class.spec]p8: (DR1495)
3786 // - The specialization shall be more specialized than the primary
3787 // template (14.5.5.2).
3788 checkMoreSpecializedThanPrimary(S, Partial);
3789
3790 // C++ [temp.class.spec]p8: (DR1315)
3791 // - Each template-parameter shall appear at least once in the
3792 // template-id outside a non-deduced context.
3793 // C++1z [temp.class.spec.match]p3 (P0127R2)
3794 // If the template arguments of a partial specialization cannot be
3795 // deduced because of the structure of its template-parameter-list
3796 // and the template-id, the program is ill-formed.
3797 auto *TemplateParams = Partial->getTemplateParameters();
3798 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3799 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3800 TemplateParams->getDepth(), DeducibleParams);
3801
3802 if (!DeducibleParams.all()) {
3803 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3804 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3805 << isa<VarTemplatePartialSpecializationDecl>(Partial)
3806 << (NumNonDeducible > 1)
3807 << SourceRange(Partial->getLocation(),
3808 Partial->getTemplateArgsAsWritten()->RAngleLoc);
Richard Smith4e05eaa2017-02-16 00:36:47 +00003809 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
Richard Smith57aae072016-12-28 02:37:25 +00003810 }
3811}
3812
3813void Sema::CheckTemplatePartialSpecialization(
3814 ClassTemplatePartialSpecializationDecl *Partial) {
3815 checkTemplatePartialSpecialization(*this, Partial);
3816}
3817
3818void Sema::CheckTemplatePartialSpecialization(
3819 VarTemplatePartialSpecializationDecl *Partial) {
3820 checkTemplatePartialSpecialization(*this, Partial);
3821}
3822
Richard Smith4e05eaa2017-02-16 00:36:47 +00003823void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
3824 // C++1z [temp.param]p11:
3825 // A template parameter of a deduction guide template that does not have a
3826 // default-argument shall be deducible from the parameter-type-list of the
3827 // deduction guide template.
3828 auto *TemplateParams = TD->getTemplateParameters();
3829 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3830 MarkDeducedTemplateParameters(TD, DeducibleParams);
3831 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3832 // A parameter pack is deducible (to an empty pack).
3833 auto *Param = TemplateParams->getParam(I);
3834 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3835 DeducibleParams[I] = true;
3836 }
3837
3838 if (!DeducibleParams.all()) {
3839 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3840 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3841 << (NumNonDeducible > 1);
3842 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3843 }
3844}
3845
Larisse Voufo39a1e502013-08-06 01:03:05 +00003846DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00003847 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00003848 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00003849 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003850 // D must be variable template id.
Faisal Vali2ab8c152017-12-30 04:15:27 +00003851 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00003852 "Variable template specialization is declared with a template it.");
3853
3854 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00003855 TemplateArgumentListInfo TemplateArgs =
3856 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003857 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3858 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3859 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00003860
Richard Smithbeef3452014-01-16 23:39:20 +00003861 TemplateName Name = TemplateId->Template.get();
3862
3863 // The template-id must name a variable template.
3864 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00003865 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3866 if (!VarTemplate) {
3867 NamedDecl *FnTemplate;
3868 if (auto *OTS = Name.getAsOverloadedTemplate())
3869 FnTemplate = *OTS->begin();
3870 else
3871 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3872 if (FnTemplate)
3873 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3874 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00003875 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3876 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00003877 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003878
3879 // Check for unexpanded parameter packs in any of the template arguments.
3880 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3881 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3882 UPPC_PartialSpecialization))
3883 return true;
3884
3885 // Check that the template argument list is well-formed for this
3886 // template.
3887 SmallVector<TemplateArgument, 4> Converted;
3888 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
3889 false, Converted))
3890 return true;
3891
Larisse Voufo39a1e502013-08-06 01:03:05 +00003892 // Find the variable template (partial) specialization declaration that
3893 // corresponds to these arguments.
3894 if (IsPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00003895 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
3896 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00003897 return true;
3898
Richard Smith57aae072016-12-28 02:37:25 +00003899 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
3900 // also do them during instantiation.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003901 bool InstantiationDependent;
3902 if (!Name.isDependent() &&
3903 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00003904 TemplateArgs.arguments(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00003905 InstantiationDependent)) {
3906 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3907 << VarTemplate->getDeclName();
3908 IsPartialSpecialization = false;
3909 }
Richard Smith300e0c32013-09-24 04:49:23 +00003910
3911 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
3912 Converted)) {
3913 // C++ [temp.class.spec]p9b3:
3914 //
3915 // -- The argument list of the specialization shall not be identical
3916 // to the implicit argument list of the primary template.
3917 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3918 << /*variable template*/ 1
3919 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
3920 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
3921 // FIXME: Recover from this by treating the declaration as a redeclaration
3922 // of the primary template.
3923 return true;
3924 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003925 }
3926
Craig Topperc3ec1492014-05-26 06:22:03 +00003927 void *InsertPos = nullptr;
3928 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003929
3930 if (IsPartialSpecialization)
3931 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00003932 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003933 else
Craig Topper7e0daca2014-06-26 04:58:53 +00003934 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003935
Craig Topperc3ec1492014-05-26 06:22:03 +00003936 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003937
3938 // Check whether we can declare a variable template specialization in
3939 // the current scope.
3940 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
3941 TemplateNameLoc,
3942 IsPartialSpecialization))
3943 return true;
3944
3945 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3946 // Since the only prior variable template specialization with these
3947 // arguments was referenced but not declared, reuse that
3948 // declaration node as our own, updating its source location and
3949 // the list of outer template parameters to reflect our new declaration.
3950 Specialization = PrevDecl;
3951 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00003952 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003953 } else if (IsPartialSpecialization) {
3954 // Create a new class template partial specialization declaration node.
3955 VarTemplatePartialSpecializationDecl *PrevPartial =
3956 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003957 VarTemplatePartialSpecializationDecl *Partial =
3958 VarTemplatePartialSpecializationDecl::Create(
3959 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
3960 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
David Majnemer8b622692016-07-03 21:17:51 +00003961 Converted, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003962
3963 if (!PrevPartial)
3964 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
3965 Specialization = Partial;
3966
3967 // If we are providing an explicit specialization of a member variable
3968 // template specialization, make a note of that.
3969 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00003970 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00003971
Richard Smith57aae072016-12-28 02:37:25 +00003972 CheckTemplatePartialSpecialization(Partial);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003973 } else {
3974 // Create a new class template specialization declaration node for
3975 // this explicit specialization or friend declaration.
3976 Specialization = VarTemplateSpecializationDecl::Create(
3977 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
David Majnemer8b622692016-07-03 21:17:51 +00003978 VarTemplate, DI->getType(), DI, SC, Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003979 Specialization->setTemplateArgsInfo(TemplateArgs);
3980
3981 if (!PrevDecl)
3982 VarTemplate->AddSpecialization(Specialization, InsertPos);
3983 }
3984
3985 // C++ [temp.expl.spec]p6:
3986 // If a template, a member template or the member of a class template is
3987 // explicitly specialized then that specialization shall be declared
3988 // before the first use of that specialization that would cause an implicit
3989 // instantiation to take place, in every translation unit in which such a
3990 // use occurs; no diagnostic is required.
3991 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3992 bool Okay = false;
3993 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
3994 // Is there any previous explicit specialization declaration?
3995 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3996 Okay = true;
3997 break;
3998 }
3999 }
4000
4001 if (!Okay) {
4002 SourceRange Range(TemplateNameLoc, RAngleLoc);
4003 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4004 << Name << Range;
4005
4006 Diag(PrevDecl->getPointOfInstantiation(),
4007 diag::note_instantiation_required_here)
4008 << (PrevDecl->getTemplateSpecializationKind() !=
4009 TSK_ImplicitInstantiation);
4010 return true;
4011 }
4012 }
4013
4014 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
4015 Specialization->setLexicalDeclContext(CurContext);
4016
4017 // Add the specialization into its lexical context, so that it can
4018 // be seen when iterating through the list of declarations in that
4019 // context. However, specializations are not found by name lookup.
4020 CurContext->addDecl(Specialization);
4021
4022 // Note that this is an explicit specialization.
4023 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4024
4025 if (PrevDecl) {
4026 // Check that this isn't a redefinition of this specialization,
4027 // merging with previous declarations.
4028 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00004029 forRedeclarationInCurContext());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004030 PrevSpec.addDecl(PrevDecl);
4031 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00004032 } else if (Specialization->isStaticDataMember() &&
4033 Specialization->isOutOfLine()) {
4034 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004035 }
4036
Larisse Voufo39a1e502013-08-06 01:03:05 +00004037 return Specialization;
4038}
4039
4040namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004041/// A partial specialization whose template arguments have matched
Larisse Voufo39a1e502013-08-06 01:03:05 +00004042/// a given template-id.
4043struct PartialSpecMatchResult {
4044 VarTemplatePartialSpecializationDecl *Partial;
4045 TemplateArgumentList *Args;
4046};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004047} // end anonymous namespace
Larisse Voufo39a1e502013-08-06 01:03:05 +00004048
4049DeclResult
4050Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
4051 SourceLocation TemplateNameLoc,
4052 const TemplateArgumentListInfo &TemplateArgs) {
4053 assert(Template && "A variable template id without template?");
4054
4055 // Check that the template argument list is well-formed for this template.
4056 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004057 if (CheckTemplateArgumentList(
4058 Template, TemplateNameLoc,
4059 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00004060 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00004061 return true;
4062
4063 // Find the variable template specialization declaration that
4064 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00004065 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004066 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Richard Smith6739a102016-05-05 00:56:12 +00004067 Converted, InsertPos)) {
4068 checkSpecializationVisibility(TemplateNameLoc, Spec);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004069 // If we already have a variable template specialization, return it.
4070 return Spec;
Richard Smith6739a102016-05-05 00:56:12 +00004071 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004072
4073 // This is the first time we have referenced this variable template
4074 // specialization. Create the canonical declaration and add it to
4075 // the set of specializations, based on the closest partial specialization
4076 // that it represents. That is,
4077 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4078 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00004079 Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004080 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
4081 bool AmbiguousPartialSpec = false;
4082 typedef PartialSpecMatchResult MatchResult;
4083 SmallVector<MatchResult, 4> Matched;
4084 SourceLocation PointOfInstantiation = TemplateNameLoc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00004085 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4086 /*ForTakingAddress=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004087
4088 // 1. Attempt to find the closest partial specialization that this
4089 // specializes, if any.
4090 // If any of the template arguments is dependent, then this is probably
4091 // a placeholder for an incomplete declarative context; which must be
4092 // complete by instantiation time. Thus, do not search through the partial
4093 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00004094 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4095 // Perhaps better after unification of DeduceTemplateArguments() and
4096 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00004097 bool InstantiationDependent = false;
4098 if (!TemplateSpecializationType::anyDependentTemplateArguments(
4099 TemplateArgs, InstantiationDependent)) {
4100
4101 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4102 Template->getPartialSpecializations(PartialSpecs);
4103
4104 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
4105 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
4106 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4107
4108 if (TemplateDeductionResult Result =
4109 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
4110 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00004111 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00004112 FailedCandidates.addCandidate().set(
4113 DeclAccessPair::make(Template, AS_public), Partial,
4114 MakeDeductionFailureInfo(Context, Result, Info));
Larisse Voufo39a1e502013-08-06 01:03:05 +00004115 (void)Result;
4116 } else {
4117 Matched.push_back(PartialSpecMatchResult());
4118 Matched.back().Partial = Partial;
4119 Matched.back().Args = Info.take();
4120 }
4121 }
4122
Larisse Voufo39a1e502013-08-06 01:03:05 +00004123 if (Matched.size() >= 1) {
4124 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4125 if (Matched.size() == 1) {
4126 // -- If exactly one matching specialization is found, the
4127 // instantiation is generated from that specialization.
4128 // We don't need to do anything for this.
4129 } else {
4130 // -- If more than one matching specialization is found, the
4131 // partial order rules (14.5.4.2) are used to determine
4132 // whether one of the specializations is more specialized
4133 // than the others. If none of the specializations is more
4134 // specialized than all of the other matching
4135 // specializations, then the use of the variable template is
4136 // ambiguous and the program is ill-formed.
4137 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4138 PEnd = Matched.end();
4139 P != PEnd; ++P) {
4140 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4141 PointOfInstantiation) ==
4142 P->Partial)
4143 Best = P;
4144 }
4145
4146 // Determine if the best partial specialization is more specialized than
4147 // the others.
4148 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4149 PEnd = Matched.end();
4150 P != PEnd; ++P) {
4151 if (P != Best && getMoreSpecializedPartialSpecialization(
4152 P->Partial, Best->Partial,
4153 PointOfInstantiation) != Best->Partial) {
4154 AmbiguousPartialSpec = true;
4155 break;
4156 }
4157 }
4158 }
4159
4160 // Instantiate using the best variable template partial specialization.
4161 InstantiationPattern = Best->Partial;
4162 InstantiationArgs = Best->Args;
4163 } else {
4164 // -- If no match is found, the instantiation is generated
4165 // from the primary template.
4166 // InstantiationPattern = Template->getTemplatedDecl();
4167 }
4168 }
4169
Larisse Voufo39a1e502013-08-06 01:03:05 +00004170 // 2. Create the canonical declaration.
Richard Smith6739a102016-05-05 00:56:12 +00004171 // Note that we do not instantiate a definition until we see an odr-use
4172 // in DoMarkVarDeclReferenced().
Larisse Voufo39a1e502013-08-06 01:03:05 +00004173 // FIXME: LateAttrs et al.?
4174 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4175 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
4176 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
4177 if (!Decl)
4178 return true;
4179
4180 if (AmbiguousPartialSpec) {
4181 // Partial ordering did not produce a clear winner. Complain.
4182 Decl->setInvalidDecl();
4183 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4184 << Decl;
4185
4186 // Print the matching partial specializations.
Yaron Keren1cb81462016-11-16 13:45:34 +00004187 for (MatchResult P : Matched)
4188 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4189 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4190 *P.Args);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004191 return true;
4192 }
4193
4194 if (VarTemplatePartialSpecializationDecl *D =
4195 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4196 Decl->setInstantiationOf(D, InstantiationArgs);
4197
Richard Smith6739a102016-05-05 00:56:12 +00004198 checkSpecializationVisibility(TemplateNameLoc, Decl);
4199
Larisse Voufo39a1e502013-08-06 01:03:05 +00004200 assert(Decl && "No variable template specialization?");
4201 return Decl;
4202}
4203
4204ExprResult
4205Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
4206 const DeclarationNameInfo &NameInfo,
4207 VarTemplateDecl *Template, SourceLocation TemplateLoc,
4208 const TemplateArgumentListInfo *TemplateArgs) {
4209
4210 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4211 *TemplateArgs);
4212 if (Decl.isInvalid())
4213 return ExprError();
4214
4215 VarDecl *Var = cast<VarDecl>(Decl.get());
4216 if (!Var->getTemplateSpecializationKind())
4217 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
4218 NameInfo.getLoc());
4219
4220 // Build an ordinary singleton decl ref.
4221 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00004222 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004223}
4224
Richard Smithecad88d2018-04-26 01:08:00 +00004225void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4226 SourceLocation Loc) {
4227 Diag(Loc, diag::err_template_missing_args)
4228 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4229 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4230 Diag(TD->getLocation(), diag::note_template_decl_here)
4231 << TD->getTemplateParameters()->getSourceRange();
4232 }
4233}
4234
John McCalldadc5752010-08-24 06:29:42 +00004235ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004236 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00004237 LookupResult &R,
4238 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00004239 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00004240 // FIXME: Can we do any checking at this point? I guess we could check the
4241 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00004242 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00004243 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00004244 // foo<int> could identify a single function unambiguously
4245 // This approach does NOT work, since f<int>(1);
4246 // gets resolved prior to resorting to overload resolution
4247 // i.e., template<class T> void f(double);
4248 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00004249
4250 // These should be filtered out by our callers.
John McCalle66edc12009-11-24 19:00:30 +00004251 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4252
Richard Smith04100942018-04-26 02:10:22 +00004253 // Non-function templates require a template argument list.
4254 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4255 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4256 diagnoseMissingTemplateArguments(TemplateName(TD), R.getNameLoc());
4257 return ExprError();
4258 }
4259 }
4260
Richard Smith0bf96f92018-04-25 22:58:55 +00004261 auto AnyDependentArguments = [&]() -> bool {
4262 bool InstantiationDependent;
4263 return TemplateArgs &&
4264 TemplateSpecializationType::anyDependentTemplateArguments(
4265 *TemplateArgs, InstantiationDependent);
4266 };
4267
Larisse Voufo39a1e502013-08-06 01:03:05 +00004268 // In C++1y, check variable template ids.
Richard Smith0bf96f92018-04-25 22:58:55 +00004269 if (R.getAsSingle<VarTemplateDecl>() && !AnyDependentArguments()) {
Richard Smithd7d11ef2014-02-03 20:09:56 +00004270 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
4271 R.getAsSingle<VarTemplateDecl>(),
4272 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004273 }
4274
John McCall58cc69d2010-01-27 01:50:18 +00004275 // We don't want lookup warnings at this point.
4276 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004277
John McCalle66edc12009-11-24 19:00:30 +00004278 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00004279 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00004280 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00004281 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004282 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004283 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00004284 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00004285
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004286 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00004287}
4288
John McCalle66edc12009-11-24 19:00:30 +00004289// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00004290ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004291Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004292 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004293 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00004294 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004295
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00004296 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00004297 DeclContext *DC;
4298 if (!(DC = computeDeclContext(SS, false)) ||
4299 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00004300 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00004301 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004302
Douglas Gregor786123d2010-05-21 23:18:07 +00004303 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004304 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Richard Smith79810042018-05-11 02:43:08 +00004305 if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(),
4306 /*Entering*/false, MemberOfUnknownSpecialization,
4307 TemplateKWLoc))
4308 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004309
John McCalle66edc12009-11-24 19:00:30 +00004310 if (R.isAmbiguous())
4311 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004312
John McCalle66edc12009-11-24 19:00:30 +00004313 if (R.empty()) {
Richard Smith79810042018-05-11 02:43:08 +00004314 Diag(NameInfo.getLoc(), diag::err_no_member)
4315 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00004316 return ExprError();
4317 }
4318
4319 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004320 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00004321 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00004322 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00004323 Diag(Temp->getLocation(), diag::note_referenced_class_template);
4324 return ExprError();
4325 }
4326
Abramo Bagnara7945c982012-01-27 09:46:47 +00004327 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00004328}
4329
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004330/// Form a dependent template name.
Douglas Gregorb67535d2009-03-31 00:43:58 +00004331///
4332/// This action forms a dependent template name given the template
4333/// name and its (presumably dependent) scope specifier. For
4334/// example, given "MetaFun::template apply", the scope specifier \p
4335/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
4336/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004337TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00004338 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004339 SourceLocation TemplateKWLoc,
Richard Smithc08b6932018-04-27 02:00:13 +00004340 const UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00004341 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00004342 bool EnteringContext,
Richard Smithfd3dae02017-01-20 00:20:39 +00004343 TemplateTy &Result,
4344 bool AllowInjectedClassName) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004345 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4346 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004347 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004348 diag::warn_cxx98_compat_template_outside_of_template :
4349 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004350 << FixItHint::CreateRemoval(TemplateKWLoc);
4351
Craig Topperc3ec1492014-05-26 06:22:03 +00004352 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00004353 if (SS.isSet())
4354 LookupCtx = computeDeclContext(SS, EnteringContext);
4355 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00004356 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00004357 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00004358 // C++0x [temp.names]p5:
4359 // If a name prefixed by the keyword template is not the name of
4360 // a template, the program is ill-formed. [Note: the keyword
4361 // template may not be applied to non-template members of class
4362 // templates. -end note ] [ Note: as is the case with the
4363 // typename prefix, the template prefix is allowed in cases
4364 // where it is not strictly necessary; i.e., when the
4365 // nested-name-specifier or the expression on the left of the ->
4366 // or . is not dependent on a template-parameter, or the use
4367 // does not appear in the scope of a template. -end note]
4368 //
4369 // Note: C++03 was more strict here, because it banned the use of
4370 // the "template" keyword prior to a template-name that was not a
4371 // dependent name. C++ DR468 relaxed this requirement (the
4372 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00004373 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00004374 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00004375 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00004376 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00004377 MemberOfUnknownSpecialization);
Richard Smith79810042018-05-11 02:43:08 +00004378 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization) {
Douglas Gregorbb119652010-06-16 23:00:59 +00004379 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00004380 } else if (TNK == TNK_Non_template) {
Richard Smith79810042018-05-11 02:43:08 +00004381 // Do the lookup again to determine if this is a "nothing found" case or
4382 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
4383 // need to do this.
4384 DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004385 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
Richard Smith79810042018-05-11 02:43:08 +00004386 LookupOrdinaryName);
4387 bool MOUS;
4388 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext,
Richard Smithafcfb6b2019-02-15 21:53:07 +00004389 MOUS, TemplateKWLoc) && !R.isAmbiguous())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004390 Diag(Name.getBeginLoc(), diag::err_no_member)
Richard Smith79810042018-05-11 02:43:08 +00004391 << DNI.getName() << LookupCtx << SS.getRange();
Douglas Gregorbb119652010-06-16 23:00:59 +00004392 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00004393 } else {
4394 // We found something; return it.
Richard Smithfd3dae02017-01-20 00:20:39 +00004395 auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
4396 if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
Faisal Vali2ab8c152017-12-30 04:15:27 +00004397 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4398 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
Richard Smithfd3dae02017-01-20 00:20:39 +00004399 // C++14 [class.qual]p2:
4400 // In a lookup in which function names are not ignored and the
4401 // nested-name-specifier nominates a class C, if the name specified
4402 // [...] is the injected-class-name of C, [...] the name is instead
4403 // considered to name the constructor
4404 //
4405 // We don't get here if naming the constructor would be valid, so we
4406 // just reject immediately and recover by treating the
4407 // injected-class-name as naming the template.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004408 Diag(Name.getBeginLoc(),
Richard Smithfd3dae02017-01-20 00:20:39 +00004409 diag::ext_out_of_line_qualified_id_type_names_constructor)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004410 << Name.Identifier
4411 << 0 /*injected-class-name used as template name*/
4412 << 1 /*'template' keyword was used*/;
Richard Smithfd3dae02017-01-20 00:20:39 +00004413 }
Douglas Gregorbb119652010-06-16 23:00:59 +00004414 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00004415 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00004416 }
4417
Aaron Ballman4a979672014-01-03 13:56:08 +00004418 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004419
Douglas Gregor3cf81312009-11-03 23:16:33 +00004420 switch (Name.getKind()) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00004421 case UnqualifiedIdKind::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004422 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00004423 Name.Identifier));
4424 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004425
Faisal Vali2ab8c152017-12-30 04:15:27 +00004426 case UnqualifiedIdKind::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00004427 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00004428 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00004429 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00004430
Faisal Vali2ab8c152017-12-30 04:15:27 +00004431 case UnqualifiedIdKind::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00004432 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00004433
Douglas Gregor3cf81312009-11-03 23:16:33 +00004434 default:
4435 break;
4436 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004437
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004438 Diag(Name.getBeginLoc(), diag::err_template_kw_refers_to_non_template)
4439 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
4440 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00004441 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00004442}
4443
Mike Stump11289f42009-09-09 15:08:12 +00004444bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00004445 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004446 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00004447 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00004448 QualType ArgType;
4449 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00004450
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004451 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004452 switch(Arg.getKind()) {
4453 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004454 // C++ [temp.arg.type]p1:
4455 // A template-argument for a template-parameter which is a
4456 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00004457 ArgType = Arg.getAsType();
4458 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004459 break;
Richard Smith77a9c602018-02-28 03:02:23 +00004460 case TemplateArgument::Template:
4461 case TemplateArgument::TemplateExpansion: {
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004462 // We have a template type parameter but the template argument
4463 // is a template without any arguments.
4464 SourceRange SR = AL.getSourceRange();
Richard Smith77a9c602018-02-28 03:02:23 +00004465 TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
Richard Smithecad88d2018-04-26 01:08:00 +00004466 diagnoseMissingTemplateArguments(Name, SR.getEnd());
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004467 return true;
4468 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004469 case TemplateArgument::Expression: {
4470 // We have a template type parameter but the template argument is an
4471 // expression; see if maybe it is missing the "typename" keyword.
4472 CXXScopeSpec SS;
4473 DeclarationNameInfo NameInfo;
4474
4475 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
4476 SS.Adopt(ArgExpr->getQualifierLoc());
4477 NameInfo = ArgExpr->getNameInfo();
4478 } else if (DependentScopeDeclRefExpr *ArgExpr =
4479 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4480 SS.Adopt(ArgExpr->getQualifierLoc());
4481 NameInfo = ArgExpr->getNameInfo();
4482 } else if (CXXDependentScopeMemberExpr *ArgExpr =
4483 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00004484 if (ArgExpr->isImplicitAccess()) {
4485 SS.Adopt(ArgExpr->getQualifierLoc());
4486 NameInfo = ArgExpr->getMemberNameInfo();
4487 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004488 }
4489
Reid Kleckner377c1592014-06-10 23:29:48 +00004490 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004491 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4492 LookupParsedName(Result, CurScope, &SS);
4493
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00004494 if (Result.getAsSingle<TypeDecl>() ||
4495 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00004496 LookupResult::NotFoundInCurrentInstantiation) {
4497 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004498 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00004499 Diag(Loc, getLangOpts().MSVCCompat
4500 ? diag::ext_ms_template_type_arg_missing_typename
4501 : diag::err_template_arg_must_be_type_suggest)
4502 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004503 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00004504
4505 // Recover by synthesizing a type using the location information that we
4506 // already have.
4507 ArgType =
4508 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
4509 TypeLocBuilder TLB;
4510 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
4511 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4512 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4513 TL.setNameLoc(NameInfo.getLoc());
4514 TSI = TLB.getTypeSourceInfo(Context, ArgType);
4515
4516 // Overwrite our input TemplateArgumentLoc so that we can recover
4517 // properly.
4518 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
4519 TemplateArgumentLocInfo(TSI));
4520
4521 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004522 }
4523 }
4524 // fallthrough
Galina Kistanova3779cb32017-06-07 06:25:05 +00004525 LLVM_FALLTHROUGH;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004526 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004527 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004528 // We have a template type parameter but the template argument
4529 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00004530 SourceRange SR = AL.getSourceRange();
4531 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004532 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00004533
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004534 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004535 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004536 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004537
Reid Kleckner377c1592014-06-10 23:29:48 +00004538 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004539 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004540
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004541 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00004542 ArgType = Context.getCanonicalType(ArgType);
Simon Pilgrim6905d222016-12-30 22:55:33 +00004543
Douglas Gregore46db902011-06-17 22:11:49 +00004544 // Objective-C ARC:
4545 // If an explicitly-specified template argument type is a lifetime type
4546 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004547 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00004548 ArgType->isObjCLifetimeType() &&
4549 !ArgType.getObjCLifetime()) {
4550 Qualifiers Qs;
4551 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
4552 ArgType = Context.getQualifiedType(ArgType, Qs);
4553 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00004554
Douglas Gregore46db902011-06-17 22:11:49 +00004555 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004556 return false;
4557}
4558
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004559/// Substitute template arguments into the default template argument for
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004560/// the given template type parameter.
4561///
4562/// \param SemaRef the semantic analysis object for which we are performing
4563/// the substitution.
4564///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004565/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004566/// for.
4567///
4568/// \param TemplateLoc the location of the template name that started the
4569/// template-id we are checking.
4570///
4571/// \param RAngleLoc the location of the right angle bracket ('>') that
4572/// terminates the template-id.
4573///
4574/// \param Param the template template parameter whose default we are
4575/// substituting into.
4576///
4577/// \param Converted the list of template arguments provided for template
4578/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004579/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00004580static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004581SubstDefaultTemplateArgument(Sema &SemaRef,
4582 TemplateDecl *Template,
4583 SourceLocation TemplateLoc,
4584 SourceLocation RAngleLoc,
4585 TemplateTypeParmDecl *Param,
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00004586 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00004587 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004588
4589 // If the argument type is dependent, instantiate it now based
4590 // on the previously-computed template arguments.
Erik Pilkingtonba88e212018-11-12 21:31:06 +00004591 if (ArgType->getType()->isInstantiationDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004592 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00004593 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004594 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004595 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00004596 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004597
David Majnemer8b622692016-07-03 21:17:51 +00004598 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004599
4600 // Only substitute for the innermost template argument list.
4601 MultiLevelTemplateArgumentList TemplateArgLists;
4602 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4603 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4604 TemplateArgLists.addOuterTemplateArguments(None);
4605
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00004606 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00004607 ArgType =
4608 SemaRef.SubstType(ArgType, TemplateArgLists,
4609 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004610 }
4611
4612 return ArgType;
4613}
4614
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004615/// Substitute template arguments into the default template argument for
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004616/// the given non-type template parameter.
4617///
4618/// \param SemaRef the semantic analysis object for which we are performing
4619/// the substitution.
4620///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004621/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004622/// for.
4623///
4624/// \param TemplateLoc the location of the template name that started the
4625/// template-id we are checking.
4626///
4627/// \param RAngleLoc the location of the right angle bracket ('>') that
4628/// terminates the template-id.
4629///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004630/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004631/// substituting into.
4632///
4633/// \param Converted the list of template arguments provided for template
4634/// parameters that precede \p Param in the template parameter list.
4635///
4636/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00004637static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004638SubstDefaultTemplateArgument(Sema &SemaRef,
4639 TemplateDecl *Template,
4640 SourceLocation TemplateLoc,
4641 SourceLocation RAngleLoc,
4642 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004643 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004644 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00004645 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004646 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004647 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004648 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004649
David Majnemer8b622692016-07-03 21:17:51 +00004650 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004651
4652 // Only substitute for the innermost template argument list.
4653 MultiLevelTemplateArgumentList TemplateArgLists;
4654 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4655 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4656 TemplateArgLists.addOuterTemplateArguments(None);
4657
Faisal Valid143a0c2017-04-01 21:30:49 +00004658 EnterExpressionEvaluationContext ConstantEvaluated(
4659 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00004660 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004661}
4662
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004663/// Substitute template arguments into the default template argument for
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004664/// the given template template parameter.
4665///
4666/// \param SemaRef the semantic analysis object for which we are performing
4667/// the substitution.
4668///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004669/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004670/// for.
4671///
4672/// \param TemplateLoc the location of the template name that started the
4673/// template-id we are checking.
4674///
4675/// \param RAngleLoc the location of the right angle bracket ('>') that
4676/// terminates the template-id.
4677///
4678/// \param Param the template template parameter whose default we are
4679/// substituting into.
4680///
4681/// \param Converted the list of template arguments provided for template
4682/// parameters that precede \p Param in the template parameter list.
4683///
Simon Pilgrim6905d222016-12-30 22:55:33 +00004684/// \param QualifierLoc Will be set to the nested-name-specifier (with
Douglas Gregordf846d12011-03-02 18:46:51 +00004685/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00004686///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004687/// \returns the substituted template argument, or NULL if an error occurred.
4688static TemplateName
4689SubstDefaultTemplateArgument(Sema &SemaRef,
4690 TemplateDecl *Template,
4691 SourceLocation TemplateLoc,
4692 SourceLocation RAngleLoc,
4693 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004694 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00004695 NestedNameSpecifierLoc &QualifierLoc) {
Richard Smith54f18e82016-08-31 02:15:21 +00004696 Sema::InstantiatingTemplate Inst(
4697 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
4698 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004699 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004700 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004701
David Majnemer8b622692016-07-03 21:17:51 +00004702 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004703
4704 // Only substitute for the innermost template argument list.
4705 MultiLevelTemplateArgumentList TemplateArgLists;
4706 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4707 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4708 TemplateArgLists.addOuterTemplateArguments(None);
4709
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00004710 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00004711 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00004712 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00004713 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00004714 QualifierLoc =
4715 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00004716 if (!QualifierLoc)
4717 return TemplateName();
4718 }
David Majnemer89189202013-08-28 23:48:32 +00004719
4720 return SemaRef.SubstTemplateName(
4721 QualifierLoc,
4722 Param->getDefaultArgument().getArgument().getAsTemplate(),
4723 Param->getDefaultArgument().getTemplateNameLoc(),
4724 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004725}
4726
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004727/// If the given template parameter has a default template
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004728/// argument, substitute into that default template argument and
4729/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004730TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004731Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
4732 SourceLocation TemplateLoc,
4733 SourceLocation RAngleLoc,
4734 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00004735 SmallVectorImpl<TemplateArgument>
4736 &Converted,
4737 bool &HasDefaultArg) {
4738 HasDefaultArg = false;
4739
4740 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004741 if (!hasVisibleDefaultArgument(TypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004742 return TemplateArgumentLoc();
4743
Richard Smithc87b9382013-07-04 01:01:24 +00004744 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00004745 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004746 TemplateLoc,
4747 RAngleLoc,
4748 TypeParm,
4749 Converted);
4750 if (DI)
4751 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4752
4753 return TemplateArgumentLoc();
4754 }
4755
4756 if (NonTypeTemplateParmDecl *NonTypeParm
4757 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004758 if (!hasVisibleDefaultArgument(NonTypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004759 return TemplateArgumentLoc();
4760
Richard Smithc87b9382013-07-04 01:01:24 +00004761 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00004762 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00004763 TemplateLoc,
4764 RAngleLoc,
4765 NonTypeParm,
4766 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004767 if (Arg.isInvalid())
4768 return TemplateArgumentLoc();
4769
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004770 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004771 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
4772 }
4773
4774 TemplateTemplateParmDecl *TempTempParm
4775 = cast<TemplateTemplateParmDecl>(Param);
Richard Smith95d83952015-06-10 20:36:34 +00004776 if (!hasVisibleDefaultArgument(TempTempParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004777 return TemplateArgumentLoc();
4778
Richard Smithc87b9382013-07-04 01:01:24 +00004779 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00004780 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004781 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004782 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004783 RAngleLoc,
4784 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00004785 Converted,
4786 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004787 if (TName.isNull())
4788 return TemplateArgumentLoc();
4789
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004790 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00004791 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004792 TempTempParm->getDefaultArgument().getTemplateNameLoc());
4793}
4794
Richard Smith11255ec2017-01-18 19:19:22 +00004795/// Convert a template-argument that we parsed as a type into a template, if
4796/// possible. C++ permits injected-class-names to perform dual service as
4797/// template template arguments and as template type arguments.
4798static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
4799 // Extract and step over any surrounding nested-name-specifier.
4800 NestedNameSpecifierLoc QualLoc;
4801 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4802 if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
4803 return TemplateArgumentLoc();
4804
4805 QualLoc = ETLoc.getQualifierLoc();
4806 TLoc = ETLoc.getNamedTypeLoc();
4807 }
4808
4809 // If this type was written as an injected-class-name, it can be used as a
4810 // template template argument.
4811 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4812 return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
4813 QualLoc, InjLoc.getNameLoc());
4814
4815 // If this type was written as an injected-class-name, it may have been
4816 // converted to a RecordType during instantiation. If the RecordType is
4817 // *not* wrapped in a TemplateSpecializationType and denotes a class
4818 // template specialization, it must have come from an injected-class-name.
4819 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
4820 if (auto *CTSD =
4821 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
4822 return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
4823 QualLoc, RecLoc.getNameLoc());
4824
4825 return TemplateArgumentLoc();
4826}
4827
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004828/// Check that the given template argument corresponds to the given
Douglas Gregorda0fb532009-11-11 19:31:23 +00004829/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004830///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004831/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004832/// checked.
4833///
Richard Trieu15b66532015-01-24 02:48:32 +00004834/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004835///
4836/// \param Template The template in which the template argument resides.
4837///
4838/// \param TemplateLoc The location of the template name for the template
4839/// whose argument list we're matching.
4840///
4841/// \param RAngleLoc The location of the right angle bracket ('>') that closes
4842/// the template argument list.
4843///
4844/// \param ArgumentPackIndex The index into the argument pack where this
4845/// argument will be placed. Only valid if the parameter is a parameter pack.
4846///
4847/// \param Converted The checked, converted argument will be added to the
4848/// end of this small vector.
4849///
4850/// \param CTAK Describes how we arrived at this particular template argument:
4851/// explicitly written, deduced, etc.
4852///
4853/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004854bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00004855 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00004856 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004857 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004858 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004859 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004860 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00004861 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00004862 // Check template type parameters.
4863 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004864 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004865
Douglas Gregoreebed722009-11-11 19:41:09 +00004866 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004867 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004868 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00004869 // with the template arguments we've seen thus far. But if the
4870 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004871 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004872 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
4873 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004874
Richard Smith5d331022018-03-08 01:07:33 +00004875 // FIXME: Do we need to substitute into parameters here if they're
4876 // instantiation-dependent but not dependent?
Peter Collingbourne01687632010-12-10 17:08:53 +00004877 if (NTTPType->isDependentType() &&
4878 !isa<TemplateTemplateParmDecl>(Template) &&
4879 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004880 // Do substitution on the type of the non-type template parameter.
4881 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00004882 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004883 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004884 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004885 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004886
4887 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00004888 Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004889 NTTPType = SubstType(NTTPType,
4890 MultiLevelTemplateArgumentList(TemplateArgs),
4891 NTTP->getLocation(),
4892 NTTP->getDeclName());
4893 // If that worked, check the non-type template parameter type
4894 // for validity.
4895 if (!NTTPType.isNull())
4896 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
4897 NTTP->getLocation());
4898 if (NTTPType.isNull())
4899 return true;
4900 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004901
Douglas Gregorda0fb532009-11-11 19:31:23 +00004902 switch (Arg.getArgument().getKind()) {
4903 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00004904 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004905
Douglas Gregorda0fb532009-11-11 19:31:23 +00004906 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004907 TemplateArgument Result;
Erich Keanec90bb6d2018-05-07 17:05:20 +00004908 unsigned CurSFINAEErrors = NumSFINAEErrors;
John Wiegley01296292011-04-08 18:41:53 +00004909 ExprResult Res =
4910 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
4911 Result, CTAK);
4912 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00004913 return true;
Erich Keanec90bb6d2018-05-07 17:05:20 +00004914 // If the current template argument causes an error, give up now.
4915 if (CurSFINAEErrors < NumSFINAEErrors)
4916 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004917
Richard Trieu15b66532015-01-24 02:48:32 +00004918 // If the resulting expression is new, then use it in place of the
4919 // old expression in the template argument.
4920 if (Res.get() != Arg.getArgument().getAsExpr()) {
4921 TemplateArgument TA(Res.get());
4922 Arg = TemplateArgumentLoc(TA, Res.get());
4923 }
4924
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004925 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004926 break;
4927 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004928
Douglas Gregorda0fb532009-11-11 19:31:23 +00004929 case TemplateArgument::Declaration:
4930 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00004931 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00004932 // We've already checked this template argument, so just copy
4933 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004934 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00004935 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004936
Douglas Gregorda0fb532009-11-11 19:31:23 +00004937 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004938 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00004939 // We were given a template template argument. It may not be ill-formed;
4940 // see below.
4941 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004942 = Arg.getArgument().getAsTemplateOrTemplatePattern()
4943 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004944 // We have a template argument such as \c T::template X, which we
4945 // parsed as a template template argument. However, since we now
4946 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004947 // template name into an expression.
4948
4949 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
4950 Arg.getTemplateNameLoc());
4951
Douglas Gregor3a43fd62011-02-25 20:49:16 +00004952 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00004953 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00004954 // FIXME: the template-template arg was a DependentTemplateName,
4955 // so it was provided with a template keyword. However, its source
4956 // location is not stored in the template argument structure.
4957 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004958 ExprResult E = DependentScopeDeclRefExpr::Create(
4959 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
4960 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004961
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004962 // If we parsed the template argument as a pack expansion, create a
4963 // pack expansion expression.
4964 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004965 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00004966 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004967 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004968 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004969
Douglas Gregorda0fb532009-11-11 19:31:23 +00004970 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004971 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00004972 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00004973 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004974
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 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00004980 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00004981 // therefore cannot be a non-type template argument.
4982 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
4983 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004984
Douglas Gregorda0fb532009-11-11 19:31:23 +00004985 Diag(Param->getLocation(), diag::note_template_param_here);
4986 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004987
Douglas Gregorda0fb532009-11-11 19:31:23 +00004988 case TemplateArgument::Type: {
4989 // We have a non-type template parameter but the template
4990 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004991
Douglas Gregorda0fb532009-11-11 19:31:23 +00004992 // C++ [temp.arg]p2:
4993 // In a template-argument, an ambiguity between a type-id and
4994 // an expression is resolved to a type-id, regardless of the
4995 // form of the corresponding template-parameter.
4996 //
4997 // We warn specifically about this case, since it can be rather
4998 // confusing for users.
4999 QualType T = Arg.getArgument().getAsType();
5000 SourceRange SR = Arg.getSourceRange();
5001 if (T->isFunctionType())
5002 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5003 else
5004 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5005 Diag(Param->getLocation(), diag::note_template_param_here);
5006 return true;
5007 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005008
Douglas Gregorda0fb532009-11-11 19:31:23 +00005009 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005010 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00005011 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005012
Douglas Gregorda0fb532009-11-11 19:31:23 +00005013 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005014 }
5015
5016
Douglas Gregorda0fb532009-11-11 19:31:23 +00005017 // Check template template parameters.
5018 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005019
Richard Smith5d331022018-03-08 01:07:33 +00005020 TemplateParameterList *Params = TempParm->getTemplateParameters();
5021 if (TempParm->isExpandedParameterPack())
5022 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5023
Douglas Gregorda0fb532009-11-11 19:31:23 +00005024 // Substitute into the template parameter list of the template
5025 // template parameter, since previously-supplied template arguments
5026 // may appear within the template template parameter.
Richard Smith5d331022018-03-08 01:07:33 +00005027 //
5028 // FIXME: Skip this if the parameters aren't instantiation-dependent.
Douglas Gregorda0fb532009-11-11 19:31:23 +00005029 {
5030 // Set up a template instantiation context.
5031 LocalInstantiationScope Scope(*this);
5032 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00005033 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00005034 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00005035 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00005036 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005037
David Majnemer8b622692016-07-03 21:17:51 +00005038 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
Richard Smith5d331022018-03-08 01:07:33 +00005039 Params = SubstTemplateParams(Params, CurContext,
5040 MultiLevelTemplateArgumentList(TemplateArgs));
5041 if (!Params)
Douglas Gregorda0fb532009-11-11 19:31:23 +00005042 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00005043 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005044
Richard Smith11255ec2017-01-18 19:19:22 +00005045 // C++1z [temp.local]p1: (DR1004)
5046 // When [the injected-class-name] is used [...] as a template-argument for
5047 // a template template-parameter [...] it refers to the class template
5048 // itself.
5049 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
5050 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
5051 Arg.getTypeSourceInfo()->getTypeLoc());
5052 if (!ConvertedArg.getArgument().isNull())
5053 Arg = ConvertedArg;
5054 }
5055
Douglas Gregorda0fb532009-11-11 19:31:23 +00005056 switch (Arg.getArgument().getKind()) {
5057 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00005058 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005059
Douglas Gregorda0fb532009-11-11 19:31:23 +00005060 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005061 case TemplateArgument::TemplateExpansion:
Richard Smith5d331022018-03-08 01:07:33 +00005062 if (CheckTemplateTemplateArgument(Params, Arg))
Douglas Gregorda0fb532009-11-11 19:31:23 +00005063 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005064
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005065 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00005066 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005067
Douglas Gregorda0fb532009-11-11 19:31:23 +00005068 case TemplateArgument::Expression:
5069 case TemplateArgument::Type:
5070 // We have a template template parameter but the template
5071 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00005072 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005073 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00005074 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005075
Douglas Gregorda0fb532009-11-11 19:31:23 +00005076 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00005077 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00005078 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00005079 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00005080 case TemplateArgument::NullPtr:
5081 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005082
Douglas Gregorda0fb532009-11-11 19:31:23 +00005083 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005084 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00005085 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005086
Douglas Gregorda0fb532009-11-11 19:31:23 +00005087 return false;
5088}
5089
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005090/// Check whether the template parameter is a pack expansion, and if so,
Richard Smith1fde8ec2012-09-07 02:06:42 +00005091/// determine the number of parameters produced by that expansion. For instance:
5092///
5093/// \code
5094/// template<typename ...Ts> struct A {
5095/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
5096/// };
5097/// \endcode
5098///
5099/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
5100/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00005101static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00005102 if (NonTypeTemplateParmDecl *NTTP
5103 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5104 if (NTTP->isExpandedParameterPack())
5105 return NTTP->getNumExpansionTypes();
5106 }
5107
5108 if (TemplateTemplateParmDecl *TTP
5109 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
5110 if (TTP->isExpandedParameterPack())
5111 return TTP->getNumExpansionTemplateParameters();
5112 }
5113
David Blaikie7a30dc52013-02-21 01:47:18 +00005114 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00005115}
5116
Richard Smith35c1df52015-06-17 20:16:32 +00005117/// Diagnose a missing template argument.
5118template<typename TemplateParmDecl>
5119static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
5120 TemplateDecl *TD,
5121 const TemplateParmDecl *D,
5122 TemplateArgumentListInfo &Args) {
5123 // Dig out the most recent declaration of the template parameter; there may be
5124 // declarations of the template that are more recent than TD.
5125 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
5126 ->getTemplateParameters()
5127 ->getParam(D->getIndex()));
5128
5129 // If there's a default argument that's not visible, diagnose that we're
5130 // missing a module import.
5131 llvm::SmallVector<Module*, 8> Modules;
5132 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
5133 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
5134 D->getDefaultArgumentLoc(), Modules,
5135 Sema::MissingImportKind::DefaultArgument,
Richard Smith6739a102016-05-05 00:56:12 +00005136 /*Recover*/true);
Richard Smith35c1df52015-06-17 20:16:32 +00005137 return true;
5138 }
5139
5140 // FIXME: If there's a more recent default argument that *is* visible,
5141 // diagnose that it was declared too late.
5142
Richard Smith4a8f3512018-07-19 19:00:37 +00005143 TemplateParameterList *Params = TD->getTemplateParameters();
5144
5145 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5146 << /*not enough args*/0
5147 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD))
5148 << TD;
5149 S.Diag(TD->getLocation(), diag::note_template_decl_here)
5150 << Params->getSourceRange();
5151 return true;
Richard Smith35c1df52015-06-17 20:16:32 +00005152}
5153
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005154/// Check that the given template argument list is well-formed
Douglas Gregord32e0282009-02-09 23:23:08 +00005155/// for specializing the given template.
Richard Smith11255ec2017-01-18 19:19:22 +00005156bool Sema::CheckTemplateArgumentList(
5157 TemplateDecl *Template, SourceLocation TemplateLoc,
5158 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
5159 SmallVectorImpl<TemplateArgument> &Converted,
5160 bool UpdateArgsWithConversions) {
Richard Trieu15b66532015-01-24 02:48:32 +00005161 // Make a copy of the template arguments for processing. Only make the
5162 // changes at the end when successful in matching the arguments to the
5163 // template.
5164 TemplateArgumentListInfo NewArgs = TemplateArgs;
5165
Erich Keaneaf0795b2017-10-24 01:39:56 +00005166 // Make sure we get the template parameter list from the most
5167 // recentdeclaration, since that is the only one that has is guaranteed to
5168 // have all the default template argument information.
5169 TemplateParameterList *Params =
5170 cast<TemplateDecl>(Template->getMostRecentDecl())
5171 ->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00005172
Richard Trieu15b66532015-01-24 02:48:32 +00005173 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00005174
Mike Stump11289f42009-09-09 15:08:12 +00005175 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00005176 // [...] The type and form of each template-argument specified in
5177 // a template-id shall match the type and form specified for the
5178 // corresponding parameter declared by the template in its
5179 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00005180 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005181 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00005182 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00005183 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00005184 for (TemplateParameterList::iterator Param = Params->begin(),
5185 ParamEnd = Params->end();
5186 Param != ParamEnd; /* increment in loop */) {
5187 // If we have an expanded parameter pack, make sure we don't have too
5188 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00005189 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00005190 if (*Expansions == ArgumentPack.size()) {
5191 // We're done with this parameter pack. Pack up its arguments and add
5192 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00005193 Converted.push_back(
Benjamin Kramercce63472015-08-05 09:40:22 +00005194 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00005195 ArgumentPack.clear();
5196
Richard Smith1fde8ec2012-09-07 02:06:42 +00005197 // This argument is assigned to the next parameter.
5198 ++Param;
5199 continue;
5200 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5201 // Not enough arguments for this parameter pack.
5202 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
Richard Smith4a8f3512018-07-19 19:00:37 +00005203 << /*not enough args*/0
Richard Smith0c062b42017-01-14 02:19:59 +00005204 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
Richard Smith1fde8ec2012-09-07 02:06:42 +00005205 << Template;
5206 Diag(Template->getLocation(), diag::note_template_decl_here)
5207 << Params->getSourceRange();
5208 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00005209 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00005210 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005211
Richard Smith1fde8ec2012-09-07 02:06:42 +00005212 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00005213 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00005214 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005215 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00005216 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00005217 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005218
Richard Smith96d71c32014-11-12 23:38:38 +00005219 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00005220 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00005221 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
5222 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00005223 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00005224 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00005225 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00005226 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00005227 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00005228 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00005229 Diag((*Param)->getLocation(), diag::note_template_param_here);
5230 return true;
5231 }
5232
Richard Smith1fde8ec2012-09-07 02:06:42 +00005233 // We're now done with this argument.
5234 ++ArgIdx;
5235
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005236 if ((*Param)->isTemplateParameterPack()) {
5237 // The template parameter was a template parameter pack, so take the
5238 // deduced argument and place it on the argument pack. Note that we
5239 // stay on the same template parameter so that we can deduce more
5240 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00005241 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005242 } else {
5243 // Move to the next template parameter.
5244 ++Param;
5245 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00005246
Richard Smith96d71c32014-11-12 23:38:38 +00005247 // If we just saw a pack expansion into a non-pack, then directly convert
5248 // the remaining arguments, because we don't know what parameters they'll
5249 // match up with.
5250 if (PackExpansionIntoNonPack) {
5251 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00005252 // If we were part way through filling in an expanded parameter pack,
5253 // fall back to just producing individual arguments.
5254 Converted.insert(Converted.end(),
5255 ArgumentPack.begin(), ArgumentPack.end());
5256 ArgumentPack.clear();
5257 }
5258
5259 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00005260 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00005261 ++ArgIdx;
5262 }
5263
Richard Smith1fde8ec2012-09-07 02:06:42 +00005264 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00005265 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00005266
Douglas Gregor84d49a22009-11-11 21:54:23 +00005267 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005268 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005269
Douglas Gregor2f157c92011-06-03 02:59:40 +00005270 // If we're checking a partial template argument list, we're done.
5271 if (PartialTemplateArgs) {
5272 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
Benjamin Kramercce63472015-08-05 09:40:22 +00005273 Converted.push_back(
5274 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5275
Richard Smith1fde8ec2012-09-07 02:06:42 +00005276 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00005277 }
5278
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005279 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005280 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00005281 if ((*Param)->isTemplateParameterPack()) {
5282 assert(!getExpandedPackSize(*Param) &&
5283 "Should have dealt with this already");
5284
5285 // A non-expanded parameter pack before the end of the parameter list
5286 // only occurs for an ill-formed template parameter list, unless we've
5287 // got a partial argument list for a function template, so just bail out.
5288 if (Param + 1 != ParamEnd)
5289 return true;
5290
Benjamin Kramercce63472015-08-05 09:40:22 +00005291 Converted.push_back(
5292 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00005293 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00005294
5295 ++Param;
5296 continue;
5297 }
5298
Douglas Gregor8e072612012-02-03 07:34:46 +00005299 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00005300 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005301
Douglas Gregor84d49a22009-11-11 21:54:23 +00005302 // Retrieve the default template argument from the template
5303 // parameter. For each kind of template parameter, we substitute the
5304 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005305 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00005306 // the default argument.
5307 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00005308 if (!hasVisibleDefaultArgument(TTP))
Richard Smith35c1df52015-06-17 20:16:32 +00005309 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
5310 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005311
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005312 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00005313 Template,
5314 TemplateLoc,
5315 RAngleLoc,
5316 TTP,
5317 Converted);
5318 if (!ArgType)
5319 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005320
Douglas Gregor84d49a22009-11-11 21:54:23 +00005321 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
5322 ArgType);
5323 } else if (NonTypeTemplateParmDecl *NTTP
5324 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00005325 if (!hasVisibleDefaultArgument(NTTP))
Richard Smith35c1df52015-06-17 20:16:32 +00005326 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
5327 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005328
John McCalldadc5752010-08-24 06:29:42 +00005329 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005330 TemplateLoc,
5331 RAngleLoc,
5332 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00005333 Converted);
5334 if (E.isInvalid())
5335 return true;
5336
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005337 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00005338 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
5339 } else {
5340 TemplateTemplateParmDecl *TempParm
5341 = cast<TemplateTemplateParmDecl>(*Param);
5342
Richard Smith95d83952015-06-10 20:36:34 +00005343 if (!hasVisibleDefaultArgument(TempParm))
Richard Smith35c1df52015-06-17 20:16:32 +00005344 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
5345 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005346
Douglas Gregordf846d12011-03-02 18:46:51 +00005347 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00005348 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005349 TemplateLoc,
5350 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00005351 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00005352 Converted,
5353 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005354 if (Name.isNull())
5355 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005356
Douglas Gregor9d802122011-03-02 17:09:35 +00005357 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
5358 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00005359 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005360
Douglas Gregor84d49a22009-11-11 21:54:23 +00005361 // Introduce an instantiation record that describes where we are using
Richard Smith54f18e82016-08-31 02:15:21 +00005362 // the default template argument. We're not actually instantiating a
5363 // template here, we just create this object to put a note into the
5364 // context stack.
Alp Tokerd4a72d52013-10-08 08:09:04 +00005365 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
5366 SourceRange(TemplateLoc, RAngleLoc));
5367 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00005368 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005369
Douglas Gregor84d49a22009-11-11 21:54:23 +00005370 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00005371 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00005372 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00005373 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005374
Richard Trieu15b66532015-01-24 02:48:32 +00005375 // Core issue 150 (assumed resolution): if this is a template template
5376 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00005377 // template definition.
5378 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00005379 NewArgs.addArgument(Arg);
5380
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005381 // Move to the next template parameter and argument.
5382 ++Param;
5383 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00005384 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005385
Richard Smith07f79912014-06-06 16:00:50 +00005386 // If we're performing a partial argument substitution, allow any trailing
5387 // pack expansions; they might be empty. This can happen even if
5388 // PartialTemplateArgs is false (the list of arguments is complete but
5389 // still dependent).
5390 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5391 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00005392 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
5393 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00005394 }
5395
Douglas Gregor8e072612012-02-03 07:34:46 +00005396 // If we have any leftover arguments, then there were too many arguments.
5397 // Complain and fail.
Richard Smith4a8f3512018-07-19 19:00:37 +00005398 if (ArgIdx < NumArgs) {
5399 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5400 << /*too many args*/1
5401 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5402 << Template
5403 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
5404 Diag(Template->getLocation(), diag::note_template_decl_here)
5405 << Params->getSourceRange();
5406 return true;
5407 }
Richard Trieu15b66532015-01-24 02:48:32 +00005408
5409 // No problems found with the new argument list, propagate changes back
5410 // to caller.
Richard Smith11255ec2017-01-18 19:19:22 +00005411 if (UpdateArgsWithConversions)
5412 TemplateArgs = std::move(NewArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005413
Richard Smith1fde8ec2012-09-07 02:06:42 +00005414 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00005415}
5416
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005417namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005418 class UnnamedLocalNoLinkageFinder
5419 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005420 {
5421 Sema &S;
5422 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005423
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005424 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005425
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005426 public:
5427 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5428
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005429 bool Visit(QualType T) {
Daniel Jasper5cad6852017-01-02 22:55:45 +00005430 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005431 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005432
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005433#define TYPE(Class, Parent) \
5434 bool Visit##Class##Type(const Class##Type *);
5435#define ABSTRACT_TYPE(Class, Parent) \
5436 bool Visit##Class##Type(const Class##Type *) { return false; }
5437#define NON_CANONICAL_TYPE(Class, Parent) \
5438 bool Visit##Class##Type(const Class##Type *) { return false; }
5439#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005440
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005441 bool VisitTagDecl(const TagDecl *Tag);
5442 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5443 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005444} // end anonymous namespace
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005445
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005446bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005447 return false;
5448}
5449
5450bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5451 return Visit(T->getElementType());
5452}
5453
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005454bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005455 return Visit(T->getPointeeType());
5456}
5457
5458bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005459 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005460 return Visit(T->getPointeeType());
5461}
5462
5463bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005464 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005465 return Visit(T->getPointeeType());
5466}
5467
5468bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005469 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005470 return Visit(T->getPointeeType());
5471}
5472
5473bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005474 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005475 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5476}
5477
5478bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005479 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005480 return Visit(T->getElementType());
5481}
5482
5483bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005484 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005485 return Visit(T->getElementType());
5486}
5487
5488bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005489 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005490 return Visit(T->getElementType());
5491}
5492
5493bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005494 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005495 return Visit(T->getElementType());
5496}
5497
5498bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005499 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005500 return Visit(T->getElementType());
5501}
5502
Andrew Gozillon572bbb02017-10-02 06:25:51 +00005503bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
5504 const DependentAddressSpaceType *T) {
5505 return Visit(T->getPointeeType());
5506}
5507
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005508bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5509 return Visit(T->getElementType());
5510}
5511
Erich Keanef702b022018-07-13 19:46:04 +00005512bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
5513 const DependentVectorType *T) {
5514 return Visit(T->getElementType());
5515}
5516
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005517bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5518 return Visit(T->getElementType());
5519}
5520
5521bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5522 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005523 for (const auto &A : T->param_types()) {
5524 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005525 return true;
5526 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005527
Alp Toker314cc812014-01-25 16:55:45 +00005528 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005529}
5530
5531bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5532 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00005533 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005534}
5535
5536bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5537 const UnresolvedUsingType*) {
5538 return false;
5539}
5540
5541bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5542 return false;
5543}
5544
5545bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5546 return Visit(T->getUnderlyingType());
5547}
5548
5549bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5550 return false;
5551}
5552
Alexis Hunte852b102011-05-24 22:41:36 +00005553bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5554 const UnaryTransformType*) {
5555 return false;
5556}
5557
Richard Smith30482bc2011-02-20 03:19:35 +00005558bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5559 return Visit(T->getDeducedType());
5560}
5561
Richard Smith600b5262017-01-26 20:40:47 +00005562bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5563 const DeducedTemplateSpecializationType *T) {
5564 return Visit(T->getDeducedType());
5565}
5566
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005567bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5568 return VisitTagDecl(T->getDecl());
5569}
5570
5571bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5572 return VisitTagDecl(T->getDecl());
5573}
5574
5575bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5576 const TemplateTypeParmType*) {
5577 return false;
5578}
5579
Douglas Gregorada4b792011-01-14 02:55:32 +00005580bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5581 const SubstTemplateTypeParmPackType *) {
5582 return false;
5583}
5584
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005585bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
5586 const TemplateSpecializationType*) {
5587 return false;
5588}
5589
5590bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
5591 const InjectedClassNameType* T) {
5592 return VisitTagDecl(T->getDecl());
5593}
5594
5595bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
5596 const DependentNameType* T) {
5597 return VisitNestedNameSpecifier(T->getQualifier());
5598}
5599
5600bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
5601 const DependentTemplateSpecializationType* T) {
5602 return VisitNestedNameSpecifier(T->getQualifier());
5603}
5604
Douglas Gregord2fa7662010-12-20 02:24:11 +00005605bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
5606 const PackExpansionType* T) {
5607 return Visit(T->getPattern());
5608}
5609
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005610bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5611 return false;
5612}
5613
5614bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
5615 const ObjCInterfaceType *) {
5616 return false;
5617}
5618
5619bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
5620 const ObjCObjectPointerType *) {
5621 return false;
5622}
5623
Eli Friedman0dfb8892011-10-06 23:00:33 +00005624bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
5625 return Visit(T->getValueType());
5626}
5627
Xiuli Pan9c14e282016-01-09 12:53:17 +00005628bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
5629 return false;
5630}
5631
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005632bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
5633 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005634 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005635 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00005636 diag::warn_cxx98_compat_template_arg_local_type :
5637 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005638 << S.Context.getTypeDeclType(Tag) << SR;
5639 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005640 }
5641
John McCall5ea95772013-03-09 00:54:27 +00005642 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005643 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005644 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00005645 diag::warn_cxx98_compat_template_arg_unnamed_type :
5646 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005647 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
5648 return true;
5649 }
5650
5651 return false;
5652}
5653
5654bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5655 NestedNameSpecifier *NNS) {
5656 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5657 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005658
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005659 switch (NNS->getKind()) {
5660 case NestedNameSpecifier::Identifier:
5661 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005662 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005663 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00005664 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005665 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005666
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005667 case NestedNameSpecifier::TypeSpec:
5668 case NestedNameSpecifier::TypeSpecWithTemplate:
5669 return Visit(QualType(NNS->getAsType(), 0));
5670 }
David Blaikie8a40f702012-01-17 06:56:22 +00005671 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005672}
5673
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005674/// Check a template argument against its corresponding
Douglas Gregord32e0282009-02-09 23:23:08 +00005675/// template type parameter.
5676///
5677/// This routine implements the semantics of C++ [temp.arg.type]. It
5678/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005679bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00005680 TypeSourceInfo *ArgInfo) {
5681 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00005682 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00005683 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00005684
5685 if (Arg->isVariablyModifiedType()) {
5686 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005687 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005688 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00005689 }
5690
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005691 // C++03 [temp.arg.type]p2:
5692 // A local type, a type with no linkage, an unnamed type or a type
5693 // compounded from any of these types shall not be used as a
5694 // template-argument for a template type-parameter.
5695 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00005696 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005697 // a warning.
Daniel Jasper5cad6852017-01-02 22:55:45 +00005698 if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005699 UnnamedLocalNoLinkageFinder Finder(*this, SR);
5700 (void)Finder.Visit(Context.getCanonicalType(Arg));
5701 }
5702
Douglas Gregord32e0282009-02-09 23:23:08 +00005703 return false;
5704}
5705
Douglas Gregor20fdef32012-04-10 17:08:25 +00005706enum NullPointerValueKind {
5707 NPV_NotNullPointer,
5708 NPV_NullPointer,
5709 NPV_Error
5710};
5711
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005712/// Determine whether the given template argument is a null pointer
Douglas Gregor20fdef32012-04-10 17:08:25 +00005713/// value of the appropriate type.
5714static NullPointerValueKind
5715isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
Reid Klecknercd016d82017-07-07 22:04:29 +00005716 QualType ParamType, Expr *Arg,
5717 Decl *Entity = nullptr) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00005718 if (Arg->isValueDependent() || Arg->isTypeDependent())
5719 return NPV_NotNullPointer;
David Majnemer69c3ddc2015-09-11 20:18:09 +00005720
Reid Klecknercd016d82017-07-07 22:04:29 +00005721 // dllimport'd entities aren't constant but are available inside of template
5722 // arguments.
5723 if (Entity && Entity->hasAttr<DLLImportAttr>())
5724 return NPV_NotNullPointer;
5725
Richard Smithdb0ac552015-12-18 22:40:25 +00005726 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
David Majnemerb54368c2015-09-11 20:55:29 +00005727 llvm_unreachable(
5728 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
David Majnemer69c3ddc2015-09-11 20:18:09 +00005729
David Majnemer5c734ad2014-08-14 00:49:23 +00005730 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00005731 return NPV_NotNullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005732
Douglas Gregor20fdef32012-04-10 17:08:25 +00005733 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00005734 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
5735 if (ArgRV.isInvalid())
5736 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005737 Arg = ArgRV.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005738
Douglas Gregor20fdef32012-04-10 17:08:25 +00005739 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005740 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00005741 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005742 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00005743 EvalResult.HasSideEffects) {
5744 SourceLocation DiagLoc = Arg->getExprLoc();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005745
Douglas Gregor350880c2012-04-10 19:03:30 +00005746 // If our only note is the usual "invalid subexpression" note, just point
5747 // the caret at its location rather than producing an essentially
5748 // redundant note.
5749 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5750 diag::note_invalid_subexpr_in_const_expr) {
5751 DiagLoc = Notes[0].first;
5752 Notes.clear();
5753 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005754
Douglas Gregor350880c2012-04-10 19:03:30 +00005755 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5756 << Arg->getType() << Arg->getSourceRange();
5757 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5758 S.Diag(Notes[I].first, Notes[I].second);
Simon Pilgrim6905d222016-12-30 22:55:33 +00005759
Douglas Gregor350880c2012-04-10 19:03:30 +00005760 S.Diag(Param->getLocation(), diag::note_template_param_here);
5761 return NPV_Error;
5762 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005763
Douglas Gregor20fdef32012-04-10 17:08:25 +00005764 // C++11 [temp.arg.nontype]p1:
5765 // - an address constant expression of type std::nullptr_t
5766 if (Arg->getType()->isNullPtrType())
5767 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005768
Douglas Gregor20fdef32012-04-10 17:08:25 +00005769 // - a constant expression that evaluates to a null pointer value (4.10); or
5770 // - a constant expression that evaluates to a null member pointer value
5771 // (4.11); or
5772 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
5773 (EvalResult.Val.isMemberPointer() &&
5774 !EvalResult.Val.getMemberPointerDecl())) {
5775 // If our expression has an appropriate type, we've succeeded.
5776 bool ObjCLifetimeConversion;
5777 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5778 S.IsQualificationConversion(Arg->getType(), ParamType, false,
5779 ObjCLifetimeConversion))
5780 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005781
Douglas Gregor20fdef32012-04-10 17:08:25 +00005782 // The types didn't match, but we know we got a null pointer; complain,
5783 // then recover as if the types were correct.
5784 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
5785 << Arg->getType() << ParamType << Arg->getSourceRange();
5786 S.Diag(Param->getLocation(), diag::note_template_param_here);
5787 return NPV_NullPointer;
5788 }
5789
5790 // If we don't have a null pointer value, but we do have a NULL pointer
5791 // constant, suggest a cast to the appropriate type.
5792 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
5793 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
5794 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005795 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005796 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getEndLoc()),
Alp Tokerb6cc5922014-05-03 03:45:55 +00005797 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00005798 S.Diag(Param->getLocation(), diag::note_template_param_here);
5799 return NPV_NullPointer;
5800 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005801
Douglas Gregor20fdef32012-04-10 17:08:25 +00005802 // FIXME: If we ever want to support general, address-constant expressions
5803 // as non-type template arguments, we should return the ExprResult here to
5804 // be interpreted by the caller.
5805 return NPV_NotNullPointer;
5806}
5807
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005808/// Checks whether the given template argument is compatible with its
David Majnemer61c39a12013-08-23 05:39:39 +00005809/// template parameter.
5810static bool CheckTemplateArgumentIsCompatibleWithParameter(
5811 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
5812 Expr *Arg, QualType ArgType) {
5813 bool ObjCLifetimeConversion;
5814 if (ParamType->isPointerType() &&
5815 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
5816 S.IsQualificationConversion(ArgType, ParamType, false,
5817 ObjCLifetimeConversion)) {
5818 // For pointer-to-object types, qualification conversions are
5819 // permitted.
5820 } else {
5821 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
5822 if (!ParamRef->getPointeeType()->isFunctionType()) {
5823 // C++ [temp.arg.nontype]p5b3:
5824 // For a non-type template-parameter of type reference to
5825 // object, no conversions apply. The type referred to by the
5826 // reference may be more cv-qualified than the (otherwise
5827 // identical) type of the template- argument. The
5828 // template-parameter is bound directly to the
5829 // template-argument, which shall be an lvalue.
5830
5831 // FIXME: Other qualifiers?
5832 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
5833 unsigned ArgQuals = ArgType.getCVRQualifiers();
5834
5835 if ((ParamQuals | ArgQuals) != ParamQuals) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005836 S.Diag(Arg->getBeginLoc(),
David Majnemer61c39a12013-08-23 05:39:39 +00005837 diag::err_template_arg_ref_bind_ignores_quals)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005838 << ParamType << Arg->getType() << Arg->getSourceRange();
David Majnemer61c39a12013-08-23 05:39:39 +00005839 S.Diag(Param->getLocation(), diag::note_template_param_here);
5840 return true;
5841 }
5842 }
5843 }
5844
5845 // At this point, the template argument refers to an object or
5846 // function with external linkage. We now need to check whether the
5847 // argument and parameter types are compatible.
5848 if (!S.Context.hasSameUnqualifiedType(ArgType,
5849 ParamType.getNonReferenceType())) {
5850 // We can't perform this conversion or binding.
5851 if (ParamType->isReferenceType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005852 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
5853 << ParamType << ArgIn->getType() << Arg->getSourceRange();
David Majnemer61c39a12013-08-23 05:39:39 +00005854 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005855 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
5856 << ArgIn->getType() << ParamType << Arg->getSourceRange();
David Majnemer61c39a12013-08-23 05:39:39 +00005857 S.Diag(Param->getLocation(), diag::note_template_param_here);
5858 return true;
5859 }
5860 }
5861
5862 return false;
5863}
5864
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005865/// Checks whether the given template argument is the address
Douglas Gregorccb07762009-02-11 19:52:55 +00005866/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005867static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00005868CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
5869 NonTypeTemplateParmDecl *Param,
5870 QualType ParamType,
5871 Expr *ArgIn,
5872 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005873 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005874 Expr *Arg = ArgIn;
5875 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00005876
Douglas Gregorb242683d2010-04-01 18:32:35 +00005877 bool AddressTaken = false;
5878 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00005879 if (S.getLangOpts().MicrosoftExt) {
5880 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
5881 // dereference and address-of operators.
5882 Arg = Arg->IgnoreParenCasts();
5883
5884 bool ExtWarnMSTemplateArg = false;
5885 UnaryOperatorKind FirstOpKind;
5886 SourceLocation FirstOpLoc;
5887 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5888 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
5889 if (UnOpKind == UO_Deref)
5890 ExtWarnMSTemplateArg = true;
5891 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
5892 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
5893 if (!AddrOpLoc.isValid()) {
5894 FirstOpKind = UnOpKind;
5895 FirstOpLoc = UnOp->getOperatorLoc();
5896 }
5897 } else
5898 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005899 }
David Majnemer61c39a12013-08-23 05:39:39 +00005900 if (FirstOpLoc.isValid()) {
5901 if (ExtWarnMSTemplateArg)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005902 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
5903 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00005904
David Majnemer61c39a12013-08-23 05:39:39 +00005905 if (FirstOpKind == UO_AddrOf)
5906 AddressTaken = true;
5907 else if (Arg->getType()->isPointerType()) {
5908 // We cannot let pointers get dereferenced here, that is obviously not a
5909 // constant expression.
5910 assert(FirstOpKind == UO_Deref);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005911 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
5912 << Arg->getSourceRange();
David Majnemer61c39a12013-08-23 05:39:39 +00005913 }
5914 }
5915 } else {
5916 // See through any implicit casts we added to fix the type.
5917 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00005918
David Majnemer61c39a12013-08-23 05:39:39 +00005919 // C++ [temp.arg.nontype]p1:
5920 //
5921 // A template-argument for a non-type, non-template
5922 // template-parameter shall be one of: [...]
5923 //
5924 // -- the address of an object or function with external
5925 // linkage, including function templates and function
5926 // template-ids but excluding non-static class members,
5927 // expressed as & id-expression where the & is optional if
5928 // the name refers to a function or array, or if the
5929 // corresponding template-parameter is a reference; or
5930
5931 // In C++98/03 mode, give an extension warning on any extra parentheses.
5932 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5933 bool ExtraParens = false;
5934 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5935 if (!Invalid && !ExtraParens) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005936 S.Diag(Arg->getBeginLoc(),
David Majnemer61c39a12013-08-23 05:39:39 +00005937 S.getLangOpts().CPlusPlus11
5938 ? diag::warn_cxx98_compat_template_arg_extra_parens
5939 : diag::ext_template_arg_extra_parens)
5940 << Arg->getSourceRange();
5941 ExtraParens = true;
5942 }
5943
5944 Arg = Parens->getSubExpr();
5945 }
5946
5947 while (SubstNonTypeTemplateParmExpr *subst =
5948 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5949 Arg = subst->getReplacement()->IgnoreImpCasts();
5950
5951 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5952 if (UnOp->getOpcode() == UO_AddrOf) {
5953 Arg = UnOp->getSubExpr();
5954 AddressTaken = true;
5955 AddrOpLoc = UnOp->getOperatorLoc();
5956 }
5957 }
5958
5959 while (SubstNonTypeTemplateParmExpr *subst =
5960 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5961 Arg = subst->getReplacement()->IgnoreImpCasts();
5962 }
John McCall7c454bb2011-07-15 05:09:51 +00005963
David Majnemer07910d62014-06-26 07:48:46 +00005964 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
5965 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5966
5967 // If our parameter has pointer type, check for a null template value.
5968 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
Reid Klecknercd016d82017-07-07 22:04:29 +00005969 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
5970 Entity)) {
David Majnemer07910d62014-06-26 07:48:46 +00005971 case NPV_NullPointer:
5972 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005973 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5974 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00005975 return false;
5976
5977 case NPV_Error:
5978 return true;
5979
5980 case NPV_NotNullPointer:
5981 break;
5982 }
5983 }
5984
Chandler Carruth724a8a12010-01-31 10:01:20 +00005985 // Stop checking the precise nature of the argument if it is value dependent,
5986 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00005987 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005988 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00005989 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005990 }
David Majnemer61c39a12013-08-23 05:39:39 +00005991
5992 if (isa<CXXUuidofExpr>(Arg)) {
5993 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
5994 ArgIn, Arg, ArgType))
5995 return true;
5996
5997 Converted = TemplateArgument(ArgIn);
5998 return false;
5999 }
6000
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006001 if (!DRE) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006002 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6003 << Arg->getSourceRange();
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006004 S.Diag(Param->getLocation(), diag::note_template_param_here);
6005 return true;
6006 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00006007
Douglas Gregorccb07762009-02-11 19:52:55 +00006008 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00006009 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006010 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6011 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006012 S.Diag(Param->getLocation(), diag::note_template_param_here);
6013 return true;
6014 }
Douglas Gregorccb07762009-02-11 19:52:55 +00006015
6016 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00006017 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006018 if (!Method->isStatic()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006019 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6020 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006021 S.Diag(Param->getLocation(), diag::note_template_param_here);
6022 return true;
6023 }
Richard Smith9380e0e2012-04-04 21:11:30 +00006024 }
Mike Stump11289f42009-09-09 15:08:12 +00006025
Richard Smith9380e0e2012-04-04 21:11:30 +00006026 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6027 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00006028
Richard Smith9380e0e2012-04-04 21:11:30 +00006029 // A non-type template argument must refer to an object or function.
6030 if (!Func && !Var) {
6031 // We found something, but we don't know specifically what it is.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006032 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6033 << Arg->getSourceRange();
Richard Smith9380e0e2012-04-04 21:11:30 +00006034 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
6035 return true;
6036 }
Douglas Gregorccb07762009-02-11 19:52:55 +00006037
Richard Smith9380e0e2012-04-04 21:11:30 +00006038 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00006039 if (Entity->getFormalLinkage() == InternalLinkage) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006040 S.Diag(Arg->getBeginLoc(),
6041 S.getLangOpts().CPlusPlus11
6042 ? diag::warn_cxx98_compat_template_arg_object_internal
6043 : diag::ext_template_arg_object_internal)
6044 << !Func << Entity << Arg->getSourceRange();
Richard Smith9380e0e2012-04-04 21:11:30 +00006045 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6046 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00006047 } else if (!Entity->hasLinkage()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006048 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6049 << !Func << Entity << Arg->getSourceRange();
Richard Smith9380e0e2012-04-04 21:11:30 +00006050 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6051 << !Func;
6052 return true;
6053 }
6054
6055 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006056 // If the template parameter has pointer type, the function decays.
6057 if (ParamType->isPointerType() && !AddressTaken)
6058 ArgType = S.Context.getPointerType(Func->getType());
6059 else if (AddressTaken && ParamType->isReferenceType()) {
6060 // If we originally had an address-of operator, but the
6061 // parameter has reference type, complain and (if things look
6062 // like they will work) drop the address-of operator.
6063 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
6064 ParamType.getNonReferenceType())) {
6065 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6066 << ParamType;
6067 S.Diag(Param->getLocation(), diag::note_template_param_here);
6068 return true;
6069 }
6070
6071 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6072 << ParamType
6073 << FixItHint::CreateRemoval(AddrOpLoc);
6074 S.Diag(Param->getLocation(), diag::note_template_param_here);
6075
6076 ArgType = Func->getType();
6077 }
Richard Smith9380e0e2012-04-04 21:11:30 +00006078 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006079 // A value of reference type is not an object.
6080 if (Var->getType()->isReferenceType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006081 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6082 << Var->getType() << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006083 S.Diag(Param->getLocation(), diag::note_template_param_here);
6084 return true;
6085 }
6086
Richard Smith9380e0e2012-04-04 21:11:30 +00006087 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00006088 if (Var->getTLSKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006089 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6090 << Arg->getSourceRange();
Richard Smith9380e0e2012-04-04 21:11:30 +00006091 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6092 return true;
6093 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00006094
6095 // If the template parameter has pointer type, we must have taken
6096 // the address of this object.
6097 if (ParamType->isReferenceType()) {
6098 if (AddressTaken) {
6099 // If we originally had an address-of operator, but the
6100 // parameter has reference type, complain and (if things look
6101 // like they will work) drop the address-of operator.
6102 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
6103 ParamType.getNonReferenceType())) {
6104 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6105 << ParamType;
6106 S.Diag(Param->getLocation(), diag::note_template_param_here);
6107 return true;
6108 }
6109
6110 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6111 << ParamType
6112 << FixItHint::CreateRemoval(AddrOpLoc);
6113 S.Diag(Param->getLocation(), diag::note_template_param_here);
6114
6115 ArgType = Var->getType();
6116 }
6117 } else if (!AddressTaken && ParamType->isPointerType()) {
6118 if (Var->getType()->isArrayType()) {
6119 // Array-to-pointer decay.
6120 ArgType = S.Context.getArrayDecayedType(Var->getType());
6121 } else {
6122 // If the template parameter has pointer type but the address of
6123 // this object was not taken, complain and (possibly) recover by
6124 // taking the address of the entity.
6125 ArgType = S.Context.getPointerType(Var->getType());
6126 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006127 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6128 << ParamType;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006129 S.Diag(Param->getLocation(), diag::note_template_param_here);
6130 return true;
6131 }
6132
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006133 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6134 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
Douglas Gregorb242683d2010-04-01 18:32:35 +00006135
6136 S.Diag(Param->getLocation(), diag::note_template_param_here);
6137 }
6138 }
Douglas Gregorccb07762009-02-11 19:52:55 +00006139 }
Mike Stump11289f42009-09-09 15:08:12 +00006140
David Majnemer61c39a12013-08-23 05:39:39 +00006141 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6142 Arg, ArgType))
6143 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006144
6145 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00006146 Converted =
6147 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006148 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00006149 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00006150}
6151
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006152/// Checks whether the given template argument is a pointer to
Douglas Gregorccb07762009-02-11 19:52:55 +00006153/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00006154static bool CheckTemplateArgumentPointerToMember(Sema &S,
6155 NonTypeTemplateParmDecl *Param,
6156 QualType ParamType,
6157 Expr *&ResultArg,
6158 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00006159 bool Invalid = false;
6160
Douglas Gregor20fdef32012-04-10 17:08:25 +00006161 Expr *Arg = ResultArg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006162 bool ObjCLifetimeConversion;
Douglas Gregorccb07762009-02-11 19:52:55 +00006163
6164 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00006165 //
Douglas Gregorccb07762009-02-11 19:52:55 +00006166 // A template-argument for a non-type, non-template
6167 // template-parameter shall be one of: [...]
6168 //
6169 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00006170 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00006171
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00006172 // In C++98/03 mode, give an extension warning on any extra parentheses.
6173 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6174 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00006175 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00006176 if (!Invalid && !ExtraParens) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006177 S.Diag(Arg->getBeginLoc(),
6178 S.getLangOpts().CPlusPlus11
6179 ? diag::warn_cxx98_compat_template_arg_extra_parens
6180 : diag::ext_template_arg_extra_parens)
6181 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00006182 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00006183 }
6184
6185 Arg = Parens->getSubExpr();
6186 }
6187
John McCall7c454bb2011-07-15 05:09:51 +00006188 while (SubstNonTypeTemplateParmExpr *subst =
6189 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6190 Arg = subst->getReplacement()->IgnoreImpCasts();
6191
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006192 // A pointer-to-member constant written &Class::member.
6193 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00006194 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00006195 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
6196 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00006197 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00006198 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006199 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006200 // A constant of pointer-to-member type.
6201 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00006202 ValueDecl *VD = DRE->getDecl();
6203 if (VD->getType()->isMemberPointerType()) {
6204 if (isa<NonTypeTemplateParmDecl>(VD)) {
6205 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6206 Converted = TemplateArgument(Arg);
6207 } else {
6208 VD = cast<ValueDecl>(VD->getCanonicalDecl());
6209 Converted = TemplateArgument(VD, ParamType);
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006210 }
George Burgess IV00f70bd2018-03-01 05:43:23 +00006211 return Invalid;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006212 }
6213 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006214
Craig Topperc3ec1492014-05-26 06:22:03 +00006215 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006216 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006217
Reid Klecknercd016d82017-07-07 22:04:29 +00006218 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6219
6220 // Check for a null pointer value.
6221 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
6222 Entity)) {
6223 case NPV_Error:
6224 return true;
6225 case NPV_NullPointer:
6226 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6227 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
6228 /*isNullPtr*/true);
6229 return false;
6230 case NPV_NotNullPointer:
6231 break;
6232 }
6233
6234 if (S.IsQualificationConversion(ResultArg->getType(),
6235 ParamType.getNonReferenceType(), false,
6236 ObjCLifetimeConversion)) {
6237 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
6238 ResultArg->getValueKind())
6239 .get();
6240 } else if (!S.Context.hasSameUnqualifiedType(
6241 ResultArg->getType(), ParamType.getNonReferenceType())) {
6242 // We can't perform this conversion.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006243 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
Reid Klecknercd016d82017-07-07 22:04:29 +00006244 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
6245 S.Diag(Param->getLocation(), diag::note_template_param_here);
6246 return true;
6247 }
6248
Douglas Gregorccb07762009-02-11 19:52:55 +00006249 if (!DRE)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006250 return S.Diag(Arg->getBeginLoc(),
Douglas Gregor20fdef32012-04-10 17:08:25 +00006251 diag::err_template_arg_not_pointer_to_member_form)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006252 << Arg->getSourceRange();
Douglas Gregorccb07762009-02-11 19:52:55 +00006253
David Majnemer3ac84e62013-10-22 21:56:38 +00006254 if (isa<FieldDecl>(DRE->getDecl()) ||
6255 isa<IndirectFieldDecl>(DRE->getDecl()) ||
6256 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00006257 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00006258 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00006259 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
6260 "Only non-static member pointers can make it here");
6261
6262 // Okay: this is the address of a non-static member, and therefore
6263 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00006264 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00006265 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00006266 } else {
6267 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00006268 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00006269 }
Douglas Gregorccb07762009-02-11 19:52:55 +00006270 return Invalid;
6271 }
6272
6273 // We found something else, but we don't know specifically what it is.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006274 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
6275 << Arg->getSourceRange();
Douglas Gregor20fdef32012-04-10 17:08:25 +00006276 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00006277 return true;
6278}
6279
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006280/// Check a template argument against its corresponding
Douglas Gregord32e0282009-02-09 23:23:08 +00006281/// non-type template parameter.
6282///
Douglas Gregor463421d2009-03-03 04:44:36 +00006283/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00006284/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00006285/// returns the converted template argument. \p ParamType is the
6286/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00006287ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00006288 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00006289 TemplateArgument &Converted,
6290 CheckTemplateArgumentKind CTAK) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006291 SourceLocation StartLoc = Arg->getBeginLoc();
Douglas Gregorc40290e2009-03-09 23:48:35 +00006292
Richard Smith5f274382016-09-28 23:55:27 +00006293 // If the parameter type somehow involves auto, deduce the type now.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00006294 if (getLangOpts().CPlusPlus17 && ParamType->isUndeducedType()) {
Richard Smith4ae5ec82017-02-22 20:01:55 +00006295 // During template argument deduction, we allow 'decltype(auto)' to
6296 // match an arbitrary dependent argument.
6297 // FIXME: The language rules don't say what happens in this case.
6298 // FIXME: We get an opaque dependent type out of decltype(auto) if the
6299 // expression is merely instantiation-dependent; is this enough?
6300 if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
6301 auto *AT = dyn_cast<AutoType>(ParamType);
6302 if (AT && AT->isDecltypeAuto()) {
6303 Converted = TemplateArgument(Arg);
6304 return Arg;
6305 }
6306 }
6307
Richard Smith87d263e2016-12-25 08:05:23 +00006308 // When checking a deduced template argument, deduce from its type even if
6309 // the type is dependent, in order to check the types of non-type template
6310 // arguments line up properly in partial ordering.
6311 Optional<unsigned> Depth;
6312 if (CTAK != CTAK_Specified)
6313 Depth = Param->getDepth() + 1;
Richard Smith5f274382016-09-28 23:55:27 +00006314 if (DeduceAutoType(
6315 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
Richard Smith87d263e2016-12-25 08:05:23 +00006316 Arg, ParamType, Depth) == DAR_Failed) {
Richard Smith5f274382016-09-28 23:55:27 +00006317 Diag(Arg->getExprLoc(),
6318 diag::err_non_type_template_parm_type_deduction_failure)
6319 << Param->getDeclName() << Param->getType() << Arg->getType()
6320 << Arg->getSourceRange();
6321 Diag(Param->getLocation(), diag::note_template_param_here);
6322 return ExprError();
6323 }
6324 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
6325 // an error. The error message normally references the parameter
6326 // declaration, but here we'll pass the argument location because that's
6327 // where the parameter type is deduced.
6328 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
6329 if (ParamType.isNull()) {
6330 Diag(Param->getLocation(), diag::note_template_param_here);
6331 return ExprError();
6332 }
6333 }
6334
Richard Smithd663fdd2014-12-17 20:42:37 +00006335 // We should have already dropped all cv-qualifiers by now.
6336 assert(!ParamType.hasQualifiers() &&
6337 "non-type template parameter type cannot be qualified");
6338
6339 if (CTAK == CTAK_Deduced &&
Richard Smithd92eddf2016-12-27 06:14:37 +00006340 !Context.hasSameType(ParamType.getNonLValueExprType(Context),
Richard Smith0e617ec2016-12-27 07:56:27 +00006341 Arg->getType())) {
Richard Smith957fbf12017-01-17 02:14:37 +00006342 // FIXME: If either type is dependent, we skip the check. This isn't
6343 // correct, since during deduction we're supposed to have replaced each
6344 // template parameter with some unique (non-dependent) placeholder.
6345 // FIXME: If the argument type contains 'auto', we carry on and fail the
6346 // type check in order to force specific types to be more specialized than
6347 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
6348 // work.
6349 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
6350 !Arg->getType()->getContainedAutoType()) {
6351 Converted = TemplateArgument(Arg);
6352 return Arg;
6353 }
6354 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
6355 // we should actually be checking the type of the template argument in P,
6356 // not the type of the template argument deduced from A, against the
6357 // template parameter type.
Richard Smithd663fdd2014-12-17 20:42:37 +00006358 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
Richard Smith0e617ec2016-12-27 07:56:27 +00006359 << Arg->getType()
Richard Smithd663fdd2014-12-17 20:42:37 +00006360 << ParamType.getUnqualifiedType();
6361 Diag(Param->getLocation(), diag::note_template_param_here);
6362 return ExprError();
6363 }
6364
Richard Smith87d263e2016-12-25 08:05:23 +00006365 // If either the parameter has a dependent type or the argument is
6366 // type-dependent, there's nothing we can check now.
6367 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
6368 // FIXME: Produce a cloned, canonical expression?
6369 Converted = TemplateArgument(Arg);
6370 return Arg;
6371 }
6372
Richard Smithe5945872017-01-06 22:52:53 +00006373 // The initialization of the parameter from the argument is
6374 // a constant-evaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006375 EnterExpressionEvaluationContext ConstantEvaluated(
6376 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Richard Smithe5945872017-01-06 22:52:53 +00006377
Aaron Ballmanc351fba2017-12-04 20:27:34 +00006378 if (getLangOpts().CPlusPlus17) {
6379 // C++17 [temp.arg.nontype]p1:
Richard Smith410cc892014-11-26 03:26:53 +00006380 // A template-argument for a non-type template parameter shall be
6381 // a converted constant expression of the type of the template-parameter.
6382 APValue Value;
6383 ExprResult ArgResult = CheckConvertedConstantExpression(
6384 Arg, ParamType, Value, CCEK_TemplateArg);
6385 if (ArgResult.isInvalid())
6386 return ExprError();
6387
Richard Smith52e624f2016-12-21 21:42:57 +00006388 // For a value-dependent argument, CheckConvertedConstantExpression is
6389 // permitted (and expected) to be unable to determine a value.
6390 if (ArgResult.get()->isValueDependent()) {
Richard Smith01bfa682016-12-27 02:02:09 +00006391 Converted = TemplateArgument(ArgResult.get());
6392 return ArgResult;
Richard Smith52e624f2016-12-21 21:42:57 +00006393 }
6394
Richard Smithd663fdd2014-12-17 20:42:37 +00006395 QualType CanonParamType = Context.getCanonicalType(ParamType);
6396
Richard Smith410cc892014-11-26 03:26:53 +00006397 // Convert the APValue to a TemplateArgument.
6398 switch (Value.getKind()) {
Richard Smithe637cbe2019-05-21 23:15:18 +00006399 case APValue::None:
Richard Smith410cc892014-11-26 03:26:53 +00006400 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00006401 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00006402 break;
Richard Smithe637cbe2019-05-21 23:15:18 +00006403 case APValue::Indeterminate:
6404 llvm_unreachable("result of constant evaluation should be initialized");
6405 break;
Richard Smith410cc892014-11-26 03:26:53 +00006406 case APValue::Int:
6407 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00006408 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00006409 break;
6410 case APValue::MemberPointer: {
6411 assert(ParamType->isMemberPointerType());
6412
6413 // FIXME: We need TemplateArgument representation and mangling for these.
6414 if (!Value.getMemberPointerPath().empty()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006415 Diag(Arg->getBeginLoc(),
Richard Smith410cc892014-11-26 03:26:53 +00006416 diag::err_template_arg_member_ptr_base_derived_not_supported)
6417 << Value.getMemberPointerDecl() << ParamType
6418 << Arg->getSourceRange();
6419 return ExprError();
6420 }
6421
6422 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00006423 Converted = VD ? TemplateArgument(VD, CanonParamType)
6424 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00006425 break;
6426 }
6427 case APValue::LValue: {
6428 // For a non-type template-parameter of pointer or reference type,
6429 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00006430 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
6431 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00006432 // -- a temporary object
6433 // -- a string literal
6434 // -- the result of a typeid expression, or
Eric Christopher0d2c56a2017-03-31 01:45:39 +00006435 // -- a predefined __func__ variable
Richard Smithee0ce3022019-05-17 07:06:46 +00006436 APValue::LValueBase Base = Value.getLValueBase();
6437 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
6438 if (Base && !VD) {
6439 auto *E = Base.dyn_cast<const Expr *>();
6440 if (E && isa<CXXUuidofExpr>(E)) {
Bill Wendlingff573072019-01-27 07:24:03 +00006441 Converted = TemplateArgument(ArgResult.get()->IgnoreImpCasts());
Richard Smith410cc892014-11-26 03:26:53 +00006442 break;
6443 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006444 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6445 << Arg->getSourceRange();
Richard Smith410cc892014-11-26 03:26:53 +00006446 return ExprError();
6447 }
Richard Smith410cc892014-11-26 03:26:53 +00006448 // -- a subobject
6449 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
6450 VD && VD->getType()->isArrayType() &&
Richard Smith5b5e27a2019-05-10 20:05:31 +00006451 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
Richard Smith410cc892014-11-26 03:26:53 +00006452 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
6453 // Per defect report (no number yet):
6454 // ... other than a pointer to the first element of a complete array
6455 // object.
6456 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
6457 Value.isLValueOnePastTheEnd()) {
6458 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
6459 << Value.getAsString(Context, ParamType);
6460 return ExprError();
6461 }
Richard Smithd663fdd2014-12-17 20:42:37 +00006462 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00006463 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00006464 assert((!VD || !ParamType->isNullPtrType()) &&
6465 "non-null value of type nullptr_t?");
6466 Converted = VD ? TemplateArgument(VD, CanonParamType)
6467 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00006468 break;
6469 }
6470 case APValue::AddrLabelDiff:
6471 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
Leonard Chan86285d22019-01-16 18:53:05 +00006472 case APValue::FixedPoint:
Richard Smith410cc892014-11-26 03:26:53 +00006473 case APValue::Float:
6474 case APValue::ComplexInt:
6475 case APValue::ComplexFloat:
6476 case APValue::Vector:
6477 case APValue::Array:
6478 case APValue::Struct:
6479 case APValue::Union:
6480 llvm_unreachable("invalid kind for template argument");
6481 }
6482
6483 return ArgResult.get();
6484 }
6485
Douglas Gregor86560402009-02-10 23:36:10 +00006486 // C++ [temp.arg.nontype]p5:
6487 // The following conversions are performed on each expression used
6488 // as a non-type template-argument. If a non-type
6489 // template-argument cannot be converted to the type of the
6490 // corresponding template-parameter then the program is
6491 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00006492 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00006493 // C++11:
6494 // -- for a non-type template-parameter of integral or
6495 // enumeration type, conversions permitted in a converted
6496 // constant expression are applied.
6497 //
6498 // C++98:
6499 // -- for a non-type template-parameter of integral or
6500 // enumeration type, integral promotions (4.5) and integral
6501 // conversions (4.7) are applied.
6502
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006503 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00006504 // C++ [temp.arg.nontype]p1:
6505 // A template-argument for a non-type, non-template template-parameter
6506 // shall be one of:
6507 //
6508 // -- for a non-type template-parameter of integral or enumeration
6509 // type, a converted constant expression of the type of the
6510 // template-parameter; or
6511 llvm::APSInt Value;
6512 ExprResult ArgResult =
6513 CheckConvertedConstantExpression(Arg, ParamType, Value,
6514 CCEK_TemplateArg);
6515 if (ArgResult.isInvalid())
6516 return ExprError();
6517
Richard Smith01bfa682016-12-27 02:02:09 +00006518 // We can't check arbitrary value-dependent arguments.
6519 if (ArgResult.get()->isValueDependent()) {
6520 Converted = TemplateArgument(ArgResult.get());
6521 return ArgResult;
6522 }
6523
Richard Smithf8379a02012-01-18 23:55:52 +00006524 // Widen the argument value to sizeof(parameter type). This is almost
6525 // always a no-op, except when the parameter type is bool. In
6526 // that case, this may extend the argument from 1 bit to 8 bits.
6527 QualType IntegerType = ParamType;
6528 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6529 IntegerType = Enum->getDecl()->getIntegerType();
6530 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
6531
Benjamin Kramer6003ad52012-06-07 15:09:51 +00006532 Converted = TemplateArgument(Context, Value,
6533 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00006534 return ArgResult;
6535 }
6536
Richard Smith08b12f12011-10-27 22:11:44 +00006537 ExprResult ArgResult = DefaultLvalueConversion(Arg);
6538 if (ArgResult.isInvalid())
6539 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006540 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00006541
6542 QualType ArgType = Arg->getType();
6543
Douglas Gregor86560402009-02-10 23:36:10 +00006544 // C++ [temp.arg.nontype]p1:
6545 // A template-argument for a non-type, non-template
6546 // template-parameter shall be one of:
6547 //
6548 // -- an integral constant-expression of integral or enumeration
6549 // type; or
6550 // -- the name of a non-type template-parameter; or
Douglas Gregor264ec4f2009-02-17 01:05:43 +00006551 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00006552 if (!ArgType->isIntegralOrEnumerationType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006553 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
6554 << ArgType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00006555 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00006556 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00006557 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00006558 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
6559 QualType T;
Simon Pilgrim6905d222016-12-30 22:55:33 +00006560
Douglas Gregore2b37442012-05-04 22:38:52 +00006561 public:
6562 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00006563
6564 void diagnoseNotICE(Sema &S, SourceLocation Loc,
6565 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00006566 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
6567 }
6568 } Diagnoser(ArgType);
6569
6570 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006571 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00006572 if (!Arg)
6573 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00006574 }
6575
Richard Smithd663fdd2014-12-17 20:42:37 +00006576 // From here on out, all we care about is the unqualified form
6577 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006578 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00006579
6580 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00006581 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00006582 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00006583 } else if (ParamType->isBooleanType()) {
6584 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006585 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00006586 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
6587 !ParamType->isEnumeralType()) {
6588 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006589 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00006590 } else {
6591 // We can't perform this conversion.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006592 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6593 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00006594 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00006595 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00006596 }
6597
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006598 // Add the value of this argument to the list of converted
6599 // arguments. We use the bitwidth and signedness of the template
6600 // parameter.
6601 if (Arg->isValueDependent()) {
6602 // The argument is value-dependent. Create a new
6603 // TemplateArgument with the converted expression.
6604 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006605 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006606 }
6607
Douglas Gregor52aba872009-03-14 00:20:21 +00006608 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00006609 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00006610 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00006611
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006612 if (ParamType->isBooleanType()) {
6613 // Value must be zero or one.
6614 Value = Value != 0;
6615 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6616 if (Value.getBitWidth() != AllowedBits)
6617 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006618 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006619 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006620 llvm::APSInt OldValue = Value;
Simon Pilgrim6905d222016-12-30 22:55:33 +00006621
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006622 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006623 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00006624 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00006625 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006626 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006627 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Simon Pilgrim6905d222016-12-30 22:55:33 +00006628
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006629 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006630 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006631 && (OldValue.isSigned() && OldValue.isNegative())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006632 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
6633 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6634 << Arg->getSourceRange();
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006635 Diag(Param->getLocation(), diag::note_template_param_here);
6636 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006637
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006638 // Complain if we overflowed the template parameter's type.
6639 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006640 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006641 RequiredBits = OldValue.getActiveBits();
6642 else if (OldValue.isUnsigned())
6643 RequiredBits = OldValue.getActiveBits() + 1;
6644 else
6645 RequiredBits = OldValue.getMinSignedBits();
6646 if (RequiredBits > AllowedBits) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006647 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
6648 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6649 << Arg->getSourceRange();
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006650 Diag(Param->getLocation(), diag::note_template_param_here);
6651 }
Douglas Gregor52aba872009-03-14 00:20:21 +00006652 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00006653
Benjamin Kramer6003ad52012-06-07 15:09:51 +00006654 Converted = TemplateArgument(Context, Value,
Simon Pilgrim6905d222016-12-30 22:55:33 +00006655 ParamType->isEnumeralType()
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00006656 ? Context.getCanonicalType(ParamType)
6657 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006658 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00006659 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006660
Richard Smith08b12f12011-10-27 22:11:44 +00006661 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00006662 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
6663
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006664 // Handle pointer-to-function, reference-to-function, and
6665 // pointer-to-member-function all in (roughly) the same way.
6666 if (// -- For a non-type template-parameter of type pointer to
6667 // function, only the function-to-pointer conversion (4.3) is
6668 // applied. If the template-argument represents a set of
6669 // overloaded functions (or a pointer to such), the matching
6670 // function is selected from the set (13.4).
6671 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006672 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006673 // -- For a non-type template-parameter of type reference to
6674 // function, no conversions apply. If the template-argument
6675 // represents a set of overloaded functions, the matching
6676 // function is selected from the set (13.4).
6677 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006678 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006679 // -- For a non-type template-parameter of type pointer to
6680 // member function, no conversions apply. If the
6681 // template-argument represents a set of overloaded member
6682 // functions, the matching member function is selected from
6683 // the set (13.4).
6684 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006685 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006686 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006687
Douglas Gregor064fdb22010-04-14 23:11:21 +00006688 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006689 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00006690 true,
6691 FoundResult)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006692 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
John Wiegley01296292011-04-08 18:41:53 +00006693 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00006694
6695 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6696 ArgType = Arg->getType();
6697 } else
John Wiegley01296292011-04-08 18:41:53 +00006698 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006699 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006700
John Wiegley01296292011-04-08 18:41:53 +00006701 if (!ParamType->isMemberPointerType()) {
6702 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6703 ParamType,
6704 Arg, Converted))
6705 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006706 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00006707 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00006708
Douglas Gregor20fdef32012-04-10 17:08:25 +00006709 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6710 Converted))
John Wiegley01296292011-04-08 18:41:53 +00006711 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006712 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006713 }
6714
Chris Lattner696197c2009-02-20 21:37:53 +00006715 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006716 // -- for a non-type template-parameter of type pointer to
6717 // object, qualification conversions (4.4) and the
6718 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00006719 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00006720 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006721 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00006722
John Wiegley01296292011-04-08 18:41:53 +00006723 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6724 ParamType,
6725 Arg, Converted))
6726 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006727 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00006728 }
Mike Stump11289f42009-09-09 15:08:12 +00006729
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006730 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006731 // -- For a non-type template-parameter of type reference to
6732 // object, no conversions apply. The type referred to by the
6733 // reference may be more cv-qualified than the (otherwise
6734 // identical) type of the template-argument. The
6735 // template-parameter is bound directly to the
6736 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00006737 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006738 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00006739
Douglas Gregor064fdb22010-04-14 23:11:21 +00006740 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006741 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
6742 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00006743 true,
6744 FoundResult)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006745 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
John Wiegley01296292011-04-08 18:41:53 +00006746 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00006747
6748 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6749 ArgType = Arg->getType();
6750 } else
John Wiegley01296292011-04-08 18:41:53 +00006751 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006752 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006753
John Wiegley01296292011-04-08 18:41:53 +00006754 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6755 ParamType,
6756 Arg, Converted))
6757 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006758 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006759 }
Douglas Gregor0e558532009-02-11 16:16:59 +00006760
Douglas Gregor20fdef32012-04-10 17:08:25 +00006761 // Deal with parameters of type std::nullptr_t.
6762 if (ParamType->isNullPtrType()) {
6763 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6764 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006765 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006766 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006767
Douglas Gregor20fdef32012-04-10 17:08:25 +00006768 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
6769 case NPV_NotNullPointer:
6770 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
6771 << Arg->getType() << ParamType;
6772 Diag(Param->getLocation(), diag::note_template_param_here);
6773 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00006774
Douglas Gregor20fdef32012-04-10 17:08:25 +00006775 case NPV_Error:
6776 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00006777
Douglas Gregor20fdef32012-04-10 17:08:25 +00006778 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00006779 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00006780 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
6781 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006782 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006783 }
6784 }
6785
Douglas Gregor0e558532009-02-11 16:16:59 +00006786 // -- For a non-type template-parameter of type pointer to data
6787 // member, qualification conversions (4.4) are applied.
6788 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
6789
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 Gregord32e0282009-02-09 23:23:08 +00006794}
6795
Richard Smith26b86ea2016-12-31 21:41:23 +00006796static void DiagnoseTemplateParameterListArityMismatch(
6797 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
6798 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
6799
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006800/// Check a template argument against its corresponding
Douglas Gregord32e0282009-02-09 23:23:08 +00006801/// template template parameter.
6802///
6803/// This routine implements the semantics of C++ [temp.arg.template].
6804/// It returns true if an error occurred, and false otherwise.
Richard Smith5d331022018-03-08 01:07:33 +00006805bool Sema::CheckTemplateTemplateArgument(TemplateParameterList *Params,
6806 TemplateArgumentLoc &Arg) {
Eli Friedmanb826a002012-09-26 02:36:12 +00006807 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006808 TemplateDecl *Template = Name.getAsTemplateDecl();
6809 if (!Template) {
6810 // Any dependent template name is fine.
6811 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
6812 return false;
6813 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00006814
Richard Smith26b86ea2016-12-31 21:41:23 +00006815 if (Template->isInvalidDecl())
6816 return true;
6817
Richard Smith3f1b5d02011-05-05 21:57:07 +00006818 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00006819 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00006820 // the name of a class template or an alias template, expressed as an
6821 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00006822 // primary class templates are considered when matching the
6823 // template template argument with the corresponding parameter;
6824 // partial specializations are not considered even if their
6825 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00006826 //
6827 // Note that we also allow template template parameters here, which
6828 // will happen when we are dealing with, e.g., class template
6829 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00006830 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00006831 !isa<TemplateTemplateParmDecl>(Template) &&
David Majnemerc2406d42016-07-11 17:09:56 +00006832 !isa<TypeAliasTemplateDecl>(Template) &&
6833 !isa<BuiltinTemplateDecl>(Template)) {
6834 assert(isa<FunctionTemplateDecl>(Template) &&
6835 "Only function templates are possible here");
Faisal Valib8b04f82016-03-26 20:46:45 +00006836 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
David Majnemerc2406d42016-07-11 17:09:56 +00006837 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
6838 << Template;
Douglas Gregor85e0f662009-02-10 00:24:35 +00006839 }
6840
Richard Smith26b86ea2016-12-31 21:41:23 +00006841 // C++1z [temp.arg.template]p3: (DR 150)
6842 // A template-argument matches a template template-parameter P when P
6843 // is at least as specialized as the template-argument A.
6844 if (getLangOpts().RelaxedTemplateTemplateArgs) {
6845 // Quick check for the common case:
6846 // If P contains a parameter pack, then A [...] matches P if each of A's
6847 // template parameters matches the corresponding template parameter in
6848 // the template-parameter-list of P.
6849 if (TemplateParameterListsAreEqual(
6850 Template->getTemplateParameters(), Params, false,
6851 TPL_TemplateTemplateArgumentMatch, Arg.getLocation()))
6852 return false;
6853
6854 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
6855 Arg.getLocation()))
6856 return false;
6857 // FIXME: Produce better diagnostics for deduction failures.
6858 }
6859
Douglas Gregor85e0f662009-02-10 00:24:35 +00006860 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00006861 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006862 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006863 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006864 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00006865}
6866
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006867/// Given a non-type template argument that refers to a
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006868/// declaration and the type of its corresponding non-type template
6869/// parameter, produce an expression that properly refers to that
6870/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006871ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006872Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6873 QualType ParamType,
6874 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00006875 // C++ [temp.param]p8:
6876 //
6877 // A non-type template-parameter of type "array of T" or
6878 // "function returning T" is adjusted to be of type "pointer to
6879 // T" or "pointer to function returning T", respectively.
6880 if (ParamType->isArrayType())
6881 ParamType = Context.getArrayDecayedType(ParamType);
6882 else if (ParamType->isFunctionType())
6883 ParamType = Context.getPointerType(ParamType);
6884
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006885 // For a NULL non-type template argument, return nullptr casted to the
6886 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00006887 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006888 return ImpCastExprToType(
6889 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
6890 ParamType,
6891 ParamType->getAs<MemberPointerType>()
6892 ? CK_NullToMemberPointer
6893 : CK_NullToPointer);
6894 }
Eli Friedmanb826a002012-09-26 02:36:12 +00006895 assert(Arg.getKind() == TemplateArgument::Declaration &&
6896 "Only declaration template arguments permitted here");
6897
George Burgess IV00f70bd2018-03-01 05:43:23 +00006898 ValueDecl *VD = Arg.getAsDecl();
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006899
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006900 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00006901 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
6902 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006903 // If the value is a class member, we might have a pointer-to-member.
6904 // Determine whether the non-type template template parameter is of
6905 // pointer-to-member type. If so, we need to build an appropriate
6906 // expression for a pointer-to-member, since a "normal" DeclRefExpr
6907 // would refer to the member itself.
6908 if (ParamType->isMemberPointerType()) {
6909 QualType ClassType
6910 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
6911 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00006912 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00006913 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006914 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00006915 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00006916
6917 // The actual value-ness of this is unimportant, but for
6918 // internal consistency's sake, references to instance methods
6919 // are r-values.
6920 ExprValueKind VK = VK_LValue;
6921 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
6922 VK = VK_RValue;
6923
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006924 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00006925 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00006926 VK,
John McCall7decc9e2010-11-18 06:31:45 +00006927 Loc,
6928 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006929 if (RefExpr.isInvalid())
6930 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006931
John McCalle3027922010-08-25 11:45:40 +00006932 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006933
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006934 // We might need to perform a trailing qualification conversion, since
6935 // the element type on the parameter could be more qualified than the
6936 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00006937 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006938 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00006939 ParamType.getUnqualifiedType(), false,
6940 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006941 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006942
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006943 assert(!RefExpr.isInvalid() &&
6944 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006945 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006946 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006947 }
6948 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006949
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006950 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00006951
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006952 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006953 // When the non-type template parameter is a pointer, take the
6954 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00006955 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006956 if (RefExpr.isInvalid())
6957 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006958
Richard Smithfc6fca12017-01-28 00:38:35 +00006959 if (!Context.hasSameUnqualifiedType(ParamType->getPointeeType(), T) &&
6960 (T->isFunctionType() || T->isArrayType())) {
6961 // Decay functions and arrays unless we're forming a pointer to array.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006962 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00006963 if (RefExpr.isInvalid())
6964 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006965
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006966 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006967 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006968
Douglas Gregorb242683d2010-04-01 18:32:35 +00006969 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00006970 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006971 }
6972
John McCall7decc9e2010-11-18 06:31:45 +00006973 ExprValueKind VK = VK_RValue;
6974
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006975 // If the non-type template parameter has reference type, qualify the
6976 // resulting declaration reference with the extra qualifiers on the
6977 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00006978 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
6979 VK = VK_LValue;
6980 T = Context.getQualifiedType(T,
6981 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00006982 } else if (isa<FunctionDecl>(VD)) {
6983 // References to functions are always lvalues.
6984 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00006985 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006986
John McCall7decc9e2010-11-18 06:31:45 +00006987 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006988}
6989
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006990/// Construct a new expression that refers to the given
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006991/// integral template argument with the given source-location
6992/// information.
6993///
6994/// This routine takes care of the mapping from an integral template
6995/// argument (which may have any integral type) to the appropriate
6996/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006997ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006998Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6999 SourceLocation Loc) {
7000 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00007001 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00007002 QualType OrigT = Arg.getIntegralType();
7003
7004 // If this is an enum type that we're instantiating, we need to use an integer
7005 // type the same size as the enumerator. We don't want to build an
7006 // IntegerLiteral with enum type. The integer type of an enum type can be of
7007 // any integral type with C++11 enum classes, make sure we create the right
7008 // type of literal for it.
7009 QualType T = OrigT;
7010 if (const EnumType *ET = OrigT->getAs<EnumType>())
7011 T = ET->getDecl()->getIntegerType();
7012
7013 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00007014 if (T->isAnyCharacterType()) {
7015 CharacterLiteral::CharacterKind Kind;
7016 if (T->isWideCharType())
7017 Kind = CharacterLiteral::Wide;
Richard Smith3a8244d2018-05-01 05:02:45 +00007018 else if (T->isChar8Type() && getLangOpts().Char8)
7019 Kind = CharacterLiteral::UTF8;
Douglas Gregorfb65e592011-07-27 05:40:30 +00007020 else if (T->isChar16Type())
7021 Kind = CharacterLiteral::UTF16;
7022 else if (T->isChar32Type())
7023 Kind = CharacterLiteral::UTF32;
7024 else
7025 Kind = CharacterLiteral::Ascii;
7026
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00007027 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
7028 Kind, T, Loc);
7029 } else if (T->isBooleanType()) {
7030 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
7031 T, Loc);
7032 } else if (T->isNullPtrType()) {
7033 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
7034 } else {
7035 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00007036 }
7037
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00007038 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00007039 // FIXME: This is a hack. We need a better way to handle substituted
7040 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00007041 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
7042 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00007043 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00007044 Loc, Loc);
7045 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00007046
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007047 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00007048}
7049
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007050/// Match two template parameters within template parameter lists.
Douglas Gregor641040a2011-01-12 23:45:44 +00007051static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
7052 bool Complain,
7053 Sema::TemplateParameterListEqualKind Kind,
7054 SourceLocation TemplateArgLoc) {
7055 // Check the actual kind (type, non-type, template).
7056 if (Old->getKind() != New->getKind()) {
7057 if (Complain) {
7058 unsigned NextDiag = diag::err_template_param_different_kind;
7059 if (TemplateArgLoc.isValid()) {
7060 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7061 NextDiag = diag::note_template_param_different_kind;
7062 }
7063 S.Diag(New->getLocation(), NextDiag)
7064 << (Kind != Sema::TPL_TemplateMatch);
7065 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
7066 << (Kind != Sema::TPL_TemplateMatch);
7067 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007068
Douglas Gregor641040a2011-01-12 23:45:44 +00007069 return false;
7070 }
7071
Richard Smith26b86ea2016-12-31 21:41:23 +00007072 // Check that both are parameter packs or neither are parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007073 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007074 // template template parameter, the template template parameter can have
7075 // a parameter pack where the template template argument does not.
7076 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
7077 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
7078 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00007079 if (Complain) {
7080 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
7081 if (TemplateArgLoc.isValid()) {
7082 S.Diag(TemplateArgLoc,
7083 diag::err_template_arg_template_params_mismatch);
7084 NextDiag = diag::note_template_parameter_pack_non_pack;
7085 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007086
Douglas Gregor641040a2011-01-12 23:45:44 +00007087 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
7088 : isa<NonTypeTemplateParmDecl>(New)? 1
7089 : 2;
7090 S.Diag(New->getLocation(), NextDiag)
7091 << ParamKind << New->isParameterPack();
7092 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
7093 << ParamKind << Old->isParameterPack();
7094 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007095
Douglas Gregor641040a2011-01-12 23:45:44 +00007096 return false;
7097 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007098
Douglas Gregor641040a2011-01-12 23:45:44 +00007099 // For non-type template parameters, check the type of the parameter.
7100 if (NonTypeTemplateParmDecl *OldNTTP
7101 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
7102 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007103
Douglas Gregor641040a2011-01-12 23:45:44 +00007104 // If we are matching a template template argument to a template
7105 // template parameter and one of the non-type template parameter types
Richard Smith13894182017-04-13 21:37:24 +00007106 // is dependent, then we must wait until template instantiation time
7107 // to actually compare the arguments.
Douglas Gregor641040a2011-01-12 23:45:44 +00007108 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
Richard Smith13894182017-04-13 21:37:24 +00007109 (OldNTTP->getType()->isDependentType() ||
7110 NewNTTP->getType()->isDependentType()))
Douglas Gregor641040a2011-01-12 23:45:44 +00007111 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007112
Douglas Gregor641040a2011-01-12 23:45:44 +00007113 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
7114 if (Complain) {
7115 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
7116 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007117 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00007118 diag::err_template_arg_template_params_mismatch);
7119 NextDiag = diag::note_template_nontype_parm_different_type;
7120 }
7121 S.Diag(NewNTTP->getLocation(), NextDiag)
7122 << NewNTTP->getType()
7123 << (Kind != Sema::TPL_TemplateMatch);
7124 S.Diag(OldNTTP->getLocation(),
7125 diag::note_template_nontype_parm_prev_declaration)
7126 << OldNTTP->getType();
7127 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007128
Douglas Gregor641040a2011-01-12 23:45:44 +00007129 return false;
7130 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007131
Douglas Gregor641040a2011-01-12 23:45:44 +00007132 return true;
7133 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007134
Douglas Gregor641040a2011-01-12 23:45:44 +00007135 // For template template parameters, check the template parameter types.
7136 // The template parameter lists of template template
7137 // parameters must agree.
7138 if (TemplateTemplateParmDecl *OldTTP
7139 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007140 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00007141 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
7142 OldTTP->getTemplateParameters(),
7143 Complain,
7144 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007145 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00007146 : Kind),
7147 TemplateArgLoc);
7148 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007149
Douglas Gregor641040a2011-01-12 23:45:44 +00007150 return true;
7151}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00007152
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007153/// Diagnose a known arity mismatch when comparing template argument
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007154/// lists.
7155static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007156void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007157 TemplateParameterList *New,
7158 TemplateParameterList *Old,
7159 Sema::TemplateParameterListEqualKind Kind,
7160 SourceLocation TemplateArgLoc) {
7161 unsigned NextDiag = diag::err_template_param_list_different_arity;
7162 if (TemplateArgLoc.isValid()) {
7163 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7164 NextDiag = diag::note_template_param_list_different_arity;
7165 }
7166 S.Diag(New->getTemplateLoc(), NextDiag)
7167 << (New->size() > Old->size())
7168 << (Kind != Sema::TPL_TemplateMatch)
7169 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
7170 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
7171 << (Kind != Sema::TPL_TemplateMatch)
7172 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
7173}
7174
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007175/// Determine whether the given template parameter lists are
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007176/// equivalent.
7177///
Mike Stump11289f42009-09-09 15:08:12 +00007178/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007179/// source code as part of a new template declaration.
7180///
7181/// \param Old The old template parameter list, typically found via
7182/// name lookup of the template declared with this template parameter
7183/// list.
7184///
7185/// \param Complain If true, this routine will produce a diagnostic if
7186/// the template parameter lists are not equivalent.
7187///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00007188/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00007189///
7190/// \param TemplateArgLoc If this source location is valid, then we
7191/// are actually checking the template parameter list of a template
7192/// argument (New) against the template parameter list of its
7193/// corresponding template template parameter (Old). We produce
7194/// slightly different diagnostics in this scenario.
7195///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007196/// \returns True if the template parameter lists are equal, false
7197/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00007198bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007199Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
7200 TemplateParameterList *Old,
7201 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00007202 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00007203 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007204 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
7205 if (Complain)
7206 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7207 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007208
7209 return false;
7210 }
7211
Douglas Gregor641040a2011-01-12 23:45:44 +00007212 // C++0x [temp.arg.template]p3:
7213 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00007214 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00007215 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00007216 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007217 // template-parameter-list of P. [...]
7218 TemplateParameterList::iterator NewParm = New->begin();
7219 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007220 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007221 OldParmEnd = Old->end();
7222 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00007223 if (Kind != TPL_TemplateTemplateArgumentMatch ||
7224 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007225 if (NewParm == NewParmEnd) {
7226 if (Complain)
7227 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7228 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007229
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007230 return false;
7231 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007232
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007233 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
7234 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007235 return false;
7236
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007237 ++NewParm;
7238 continue;
7239 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007240
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007241 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00007242 // [...] When P's template- parameter-list contains a template parameter
7243 // pack (14.5.3), the template parameter pack will match zero or more
7244 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007245 // template-parameter-list of A with the same type and form as the
7246 // template parameter pack in P (ignoring whether those template
7247 // parameters are template parameter packs).
7248 for (; NewParm != NewParmEnd; ++NewParm) {
7249 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
7250 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007251 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007252 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007253 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007254
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007255 // Make sure we exhausted all of the arguments.
7256 if (NewParm != NewParmEnd) {
7257 if (Complain)
7258 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7259 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007260
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007261 return false;
7262 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007263
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007264 return true;
7265}
7266
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007267/// Check whether a template can be declared within this scope.
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007268///
7269/// If the template declaration is valid in this scope, returns
7270/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00007271bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007272Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00007273 if (!S)
7274 return false;
7275
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007276 // Find the nearest enclosing declaration scope.
7277 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7278 (S->getFlags() & Scope::TemplateParamScope) != 0)
7279 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00007280
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00007281 // C++ [temp]p4:
7282 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007283 DeclContext *Ctx = S->getEntity();
Alex Lorenz560ae562016-11-02 15:46:34 +00007284 if (Ctx && Ctx->isExternCContext()) {
7285 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
7286 << TemplateParams->getSourceRange();
7287 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
7288 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
7289 return true;
7290 }
Richard Smith8df390f2016-09-08 23:14:54 +00007291 Ctx = Ctx->getRedeclContext();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007292
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00007293 // C++ [temp]p2:
7294 // A template-declaration can appear only as a namespace scope or
7295 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00007296 if (Ctx) {
7297 if (Ctx->isFileContext())
7298 return false;
7299 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
7300 // C++ [temp.mem]p2:
7301 // A local class shall not have member templates.
7302 if (RD->isLocalClass())
7303 return Diag(TemplateParams->getTemplateLoc(),
7304 diag::err_template_inside_local_class)
7305 << TemplateParams->getSourceRange();
7306 else
7307 return false;
7308 }
7309 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007310
Mike Stump11289f42009-09-09 15:08:12 +00007311 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007312 diag::err_template_outside_namespace_or_class_scope)
7313 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007314}
Douglas Gregor67a65642009-02-17 23:15:12 +00007315
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007316/// Determine what kind of template specialization the given declaration
Douglas Gregor54888652009-10-07 00:13:32 +00007317/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007318static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00007319 if (!D)
7320 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007321
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007322 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
7323 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00007324 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
7325 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007326 if (VarDecl *Var = dyn_cast<VarDecl>(D))
7327 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007328
Douglas Gregor54888652009-10-07 00:13:32 +00007329 return TSK_Undeclared;
7330}
7331
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007332/// Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007333/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00007334///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007335/// This routine determines whether a template specialization can be declared
7336/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00007337///
7338/// \param S the semantic analysis object for which this check is being
7339/// performed.
7340///
7341/// \param Specialized the entity being specialized or instantiated, which
7342/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007343/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00007344/// member class).
7345///
7346/// \param PrevDecl the previous declaration of this entity, if any.
7347///
7348/// \param Loc the location of the explicit specialization or instantiation of
7349/// this entity.
7350///
7351/// \param IsPartialSpecialization whether this is a partial specialization of
7352/// a class template.
7353///
Douglas Gregor54888652009-10-07 00:13:32 +00007354/// \returns true if there was an error that we cannot recover from, false
7355/// otherwise.
7356static bool CheckTemplateSpecializationScope(Sema &S,
7357 NamedDecl *Specialized,
7358 NamedDecl *PrevDecl,
7359 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007360 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00007361 // Keep these "kind" numbers in sync with the %select statements in the
7362 // various diagnostics emitted by this routine.
7363 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00007364 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00007365 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007366 else if (isa<VarTemplateDecl>(Specialized))
7367 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00007368 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00007369 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007370 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00007371 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007372 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00007373 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007374 else if (isa<RecordDecl>(Specialized))
7375 EntityKind = 7;
7376 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
7377 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00007378 else {
Richard Smith7d137e32012-03-23 03:33:32 +00007379 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007380 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007381 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00007382 return true;
7383 }
7384
Douglas Gregorf47b9112009-02-25 22:02:03 +00007385 // C++ [temp.expl.spec]p2:
Richard Smithc660c8f2018-03-16 13:36:56 +00007386 // An explicit specialization may be declared in any scope in which
7387 // the corresponding primary template may be defined.
Sebastian Redl50c68252010-08-31 00:36:30 +00007388 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00007389 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007390 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007391 return true;
7392 }
Douglas Gregore4b05162009-10-07 17:21:34 +00007393
7394 // C++ [temp.class.spec]p6:
Richard Smithc660c8f2018-03-16 13:36:56 +00007395 // A class template partial specialization may be declared in any
7396 // scope in which the primary template may be defined.
7397 DeclContext *SpecializedContext =
7398 Specialized->getDeclContext()->getRedeclContext();
7399 DeclContext *DC = S.CurContext->getRedeclContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00007400
Richard Smithc660c8f2018-03-16 13:36:56 +00007401 // Make sure that this redeclaration (or definition) occurs in the same
7402 // scope or an enclosing namespace.
7403 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
7404 : DC->Equals(SpecializedContext))) {
Richard Smitha98f8fc2013-12-07 05:09:50 +00007405 if (isa<TranslationUnitDecl>(SpecializedContext))
7406 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
7407 << EntityKind << Specialized;
Richard Smithc660c8f2018-03-16 13:36:56 +00007408 else {
7409 auto *ND = cast<NamedDecl>(SpecializedContext);
Alexey Bataev0068cb22015-03-20 07:21:46 +00007410 int Diag = diag::err_template_spec_redecl_out_of_scope;
Richard Smithc660c8f2018-03-16 13:36:56 +00007411 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
Alexey Bataev0068cb22015-03-20 07:21:46 +00007412 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
7413 S.Diag(Loc, Diag) << EntityKind << Specialized
Richard Smithc660c8f2018-03-16 13:36:56 +00007414 << ND << isa<CXXRecordDecl>(ND);
7415 }
Richard Smitha98f8fc2013-12-07 05:09:50 +00007416
7417 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007418
Richard Smithc660c8f2018-03-16 13:36:56 +00007419 // Don't allow specializing in the wrong class during error recovery.
7420 // Otherwise, things can go horribly wrong.
7421 if (DC->isRecord())
7422 return true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007423 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007424
Douglas Gregorf47b9112009-02-25 22:02:03 +00007425 return false;
7426}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007427
Richard Smith57aae072016-12-28 02:37:25 +00007428static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
7429 if (!E->isTypeDependent())
Richard Smith6056d5e2014-02-09 00:54:43 +00007430 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00007431 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00007432 Checker.TraverseStmt(E);
Richard Smith57aae072016-12-28 02:37:25 +00007433 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00007434 return E->getSourceRange();
7435 return Checker.MatchLoc;
7436}
7437
7438static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
7439 if (!TL.getType()->isDependentType())
7440 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00007441 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00007442 Checker.TraverseTypeLoc(TL);
Richard Smith57aae072016-12-28 02:37:25 +00007443 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00007444 return TL.getSourceRange();
7445 return Checker.MatchLoc;
7446}
7447
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007448/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007449/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007450static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00007451 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
7452 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007453 for (unsigned I = 0; I != NumArgs; ++I) {
7454 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00007455 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00007456 S, TemplateNameLoc, Param, Args[I].pack_begin(),
7457 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007458 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007459
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007460 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007461 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007462
Eli Friedmanb826a002012-09-26 02:36:12 +00007463 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007464 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00007465
7466 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007467
Douglas Gregor98318c22011-01-03 21:37:45 +00007468 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007469 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
7470 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00007471
7472 // Strip off any implicit casts we added as part of type checking.
7473 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
7474 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007475
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007476 // C++ [temp.class.spec]p8:
7477 // A non-type argument is non-specialized if it is the name of a
7478 // non-type parameter. All other non-type arguments are
7479 // specialized.
7480 //
7481 // Below, we check the two conditions that only apply to
7482 // specialized non-type arguments, so skip any non-specialized
7483 // arguments.
7484 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00007485 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007486 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007487
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007488 // C++ [temp.class.spec]p9:
7489 // Within the argument list of a class template partial
7490 // specialization, the following restrictions apply:
7491 // -- A partially specialized non-type argument expression
7492 // shall not involve a template parameter of the partial
7493 // specialization except when the argument expression is a
7494 // simple identifier.
Richard Smith57aae072016-12-28 02:37:25 +00007495 // -- The type of a template parameter corresponding to a
7496 // specialized non-type argument shall not be dependent on a
7497 // parameter of the specialization.
7498 // DR1315 removes the first bullet, leaving an incoherent set of rules.
7499 // We implement a compromise between the original rules and DR1315:
7500 // -- A specialized non-type template argument shall not be
7501 // type-dependent and the corresponding template parameter
7502 // shall have a non-dependent type.
Richard Smith6056d5e2014-02-09 00:54:43 +00007503 SourceRange ParamUseRange =
Richard Smith57aae072016-12-28 02:37:25 +00007504 findTemplateParameterInType(Param->getDepth(), ArgExpr);
Richard Smith6056d5e2014-02-09 00:54:43 +00007505 if (ParamUseRange.isValid()) {
7506 if (IsDefaultArgument) {
7507 S.Diag(TemplateNameLoc,
7508 diag::err_dependent_non_type_arg_in_partial_spec);
7509 S.Diag(ParamUseRange.getBegin(),
7510 diag::note_dependent_non_type_default_arg_in_partial_spec)
7511 << ParamUseRange;
7512 } else {
7513 S.Diag(ParamUseRange.getBegin(),
7514 diag::err_dependent_non_type_arg_in_partial_spec)
7515 << ParamUseRange;
7516 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007517 return true;
7518 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007519
Richard Smith6056d5e2014-02-09 00:54:43 +00007520 ParamUseRange = findTemplateParameter(
Richard Smith57aae072016-12-28 02:37:25 +00007521 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
Richard Smith6056d5e2014-02-09 00:54:43 +00007522 if (ParamUseRange.isValid()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007523 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
Richard Smith6056d5e2014-02-09 00:54:43 +00007524 diag::err_dependent_typed_non_type_arg_in_partial_spec)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007525 << Param->getType();
Richard Smith6056d5e2014-02-09 00:54:43 +00007526 S.Diag(Param->getLocation(), diag::note_template_param_here)
Richard Smith57aae072016-12-28 02:37:25 +00007527 << (IsDefaultArgument ? ParamUseRange : SourceRange())
7528 << ParamUseRange;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007529 return true;
7530 }
7531 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007532
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007533 return false;
7534}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007535
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007536/// Check the non-type template arguments of a class template
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007537/// partial specialization according to C++ [temp.class.spec]p9.
7538///
Richard Smith6056d5e2014-02-09 00:54:43 +00007539/// \param TemplateNameLoc the location of the template name.
Simon Pilgrim6905d222016-12-30 22:55:33 +00007540/// \param PrimaryTemplate the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00007541/// template.
7542/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00007543/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00007544/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007545///
Richard Smith6056d5e2014-02-09 00:54:43 +00007546/// \returns \c true if there was an error, \c false otherwise.
Richard Smith57aae072016-12-28 02:37:25 +00007547bool Sema::CheckTemplatePartialSpecializationArgs(
7548 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
7549 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
7550 // We have to be conservative when checking a template in a dependent
7551 // context.
7552 if (PrimaryTemplate->getDeclContext()->isDependentContext())
7553 return false;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007554
Richard Smith57aae072016-12-28 02:37:25 +00007555 TemplateParameterList *TemplateParams =
7556 PrimaryTemplate->getTemplateParameters();
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007557 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7558 NonTypeTemplateParmDecl *Param
7559 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
7560 if (!Param)
7561 continue;
7562
Richard Smith57aae072016-12-28 02:37:25 +00007563 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
7564 Param, &TemplateArgs[I],
7565 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007566 return true;
7567 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007568
7569 return false;
7570}
7571
Erich Keanec480f302018-07-12 21:09:05 +00007572DeclResult Sema::ActOnClassTemplateSpecialization(
7573 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7574 SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId,
7575 const ParsedAttributesView &Attr,
7576 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00007577 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00007578
Richard Smith4b55a9c2014-04-17 03:29:33 +00007579 CXXScopeSpec &SS = TemplateId.SS;
7580
Abramo Bagnara60804e12011-03-18 15:16:37 +00007581 // NOTE: KWLoc is the location of the tag keyword. This will instead
7582 // store the location of the outermost template keyword in the declaration.
7583 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00007584 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
7585 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
7586 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
7587 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00007588
Douglas Gregor67a65642009-02-17 23:15:12 +00007589 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00007590 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00007591 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00007592 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
7593
7594 if (!ClassTemplate) {
7595 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007596 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00007597 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
7598 return true;
7599 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007600
Richard Smithf445f192017-02-09 21:04:43 +00007601 bool isMemberSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00007602 bool isPartialSpecialization = false;
7603
Douglas Gregorf47b9112009-02-25 22:02:03 +00007604 // Check the validity of the template headers that introduce this
7605 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00007606 // FIXME: We probably shouldn't complain about these headers for
7607 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007608 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00007609 TemplateParameterList *TemplateParams =
7610 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00007611 KWLoc, TemplateNameLoc, SS, &TemplateId,
Richard Smithf445f192017-02-09 21:04:43 +00007612 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
Richard Smith4b55a9c2014-04-17 03:29:33 +00007613 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007614 if (Invalid)
7615 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007616
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007617 if (TemplateParams && TemplateParams->size() > 0) {
7618 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007619
Douglas Gregorec9518b2010-12-21 08:14:57 +00007620 if (TUK == TUK_Friend) {
7621 Diag(KWLoc, diag::err_partial_specialization_friend)
7622 << SourceRange(LAngleLoc, RAngleLoc);
7623 return true;
7624 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007625
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007626 // C++ [temp.class.spec]p10:
7627 // The template parameter list of a specialization shall not
7628 // contain default template argument values.
7629 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7630 Decl *Param = TemplateParams->getParam(I);
7631 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
7632 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00007633 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007634 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00007635 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007636 }
7637 } else if (NonTypeTemplateParmDecl *NTTP
7638 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
7639 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00007640 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007641 diag::err_default_arg_in_partial_spec)
7642 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00007643 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007644 }
7645 } else {
7646 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00007647 if (TTP->hasDefaultArgument()) {
7648 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007649 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00007650 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00007651 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00007652 }
7653 }
7654 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007655 } else if (TemplateParams) {
7656 if (TUK == TUK_Friend)
7657 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00007658 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007659 SourceRange(TemplateParams->getTemplateLoc(),
7660 TemplateParams->getRAngleLoc()))
7661 << SourceRange(LAngleLoc, RAngleLoc);
Richard Smith4b55a9c2014-04-17 03:29:33 +00007662 } else {
7663 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007664 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00007665
Douglas Gregor67a65642009-02-17 23:15:12 +00007666 // Check that the specialization uses the same tag kind as the
7667 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007668 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7669 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00007670 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007671 Kind, TUK == TUK_Definition, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00007672 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007673 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00007674 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007675 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00007676 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007677 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00007678 diag::note_previous_use);
7679 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7680 }
7681
Douglas Gregorc40290e2009-03-09 23:48:35 +00007682 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00007683 TemplateArgumentListInfo TemplateArgs =
7684 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00007685
Douglas Gregor14406932011-01-03 20:35:03 +00007686 // Check for unexpanded parameter packs in any of the template arguments.
7687 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007688 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00007689 UPPC_PartialSpecialization))
7690 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007691
Douglas Gregor67a65642009-02-17 23:15:12 +00007692 // Check that the template argument list is well-formed for this
7693 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007694 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007695 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7696 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00007697 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00007698
Douglas Gregor2373c592009-05-31 09:31:02 +00007699 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00007700 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00007701 if (isPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00007702 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
7703 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007704 return true;
7705
Richard Smith57aae072016-12-28 02:37:25 +00007706 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
7707 // also do it during instantiation.
Douglas Gregor678d76c2011-07-01 01:22:09 +00007708 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007709 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00007710 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00007711 TemplateArgs.arguments(), InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00007712 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
7713 << ClassTemplate->getDeclName();
7714 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00007715 }
7716 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007717
Craig Topperc3ec1492014-05-26 06:22:03 +00007718 void *InsertPos = nullptr;
7719 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00007720
7721 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007722 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00007723 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00007724 else
Craig Topper7e0daca2014-06-26 04:58:53 +00007725 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00007726
Craig Topperc3ec1492014-05-26 06:22:03 +00007727 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00007728
Douglas Gregorf47b9112009-02-25 22:02:03 +00007729 // Check whether we can declare a class template specialization in
7730 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00007731 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007732 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
7733 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007734 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00007735 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007736
Douglas Gregor15301382009-07-30 17:40:51 +00007737 // The canonical type
7738 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00007739 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00007740 // Build the canonical type that describes the converted template
7741 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00007742 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7743 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00007744 Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007745
7746 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007747 ClassTemplate->getInjectedClassNameSpecialization())) {
7748 // C++ [temp.class.spec]p9b3:
7749 //
7750 // -- The argument list of the specialization shall not be identical
7751 // to the implicit argument list of the primary template.
Richard Smith0e617ec2016-12-27 07:56:27 +00007752 //
7753 // This rule has since been removed, because it's redundant given DR1495,
7754 // but we keep it because it produces better diagnostics and recovery.
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007755 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00007756 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00007757 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007758 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
7759 ClassTemplate->getIdentifier(),
7760 TemplateNameLoc,
7761 Attr,
7762 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00007763 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00007764 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00007765 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007766 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007767 }
Douglas Gregor15301382009-07-30 17:40:51 +00007768
Douglas Gregor2373c592009-05-31 09:31:02 +00007769 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00007770 ClassTemplatePartialSpecializationDecl *PrevPartial
7771 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007772 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00007773 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00007774 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007775 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00007776 TemplateParams,
7777 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007778 Converted,
John McCall6b51f282009-11-23 01:53:49 +00007779 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00007780 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00007781 PrevPartial);
Bruno Ricci4224c872018-12-21 14:35:24 +00007782 SetNestedNameSpecifier(*this, Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007783 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Benjamin Kramer9cc210652015-08-05 09:40:49 +00007784 Partial->setTemplateParameterListsInfo(
7785 Context, TemplateParameterLists.drop_back(1));
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007786 }
Douglas Gregor2373c592009-05-31 09:31:02 +00007787
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007788 if (!PrevPartial)
7789 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00007790 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00007791
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007792 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00007793 // template specialization, make a note of that.
7794 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
7795 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007796
Richard Smith57aae072016-12-28 02:37:25 +00007797 CheckTemplatePartialSpecialization(Partial);
Douglas Gregor67a65642009-02-17 23:15:12 +00007798 } else {
7799 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00007800 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00007801 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007802 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00007803 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007804 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007805 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007806 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00007807 PrevDecl);
Bruno Ricci4224c872018-12-21 14:35:24 +00007808 SetNestedNameSpecifier(*this, Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007809 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00007810 Specialization->setTemplateParameterListsInfo(Context,
Benjamin Kramer9cc210652015-08-05 09:40:49 +00007811 TemplateParameterLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007812 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007813
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007814 if (!PrevDecl)
7815 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00007816
David Majnemer678f50b2015-11-18 19:49:19 +00007817 if (CurContext->isDependentContext()) {
David Majnemer678f50b2015-11-18 19:49:19 +00007818 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7819 CanonType = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00007820 CanonTemplate, Converted);
David Majnemer678f50b2015-11-18 19:49:19 +00007821 } else {
7822 CanonType = Context.getTypeDeclType(Specialization);
7823 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007824 }
7825
Douglas Gregor06db9f52009-10-12 20:18:28 +00007826 // C++ [temp.expl.spec]p6:
7827 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007828 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007829 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007830 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007831 // use occurs; no diagnostic is required.
7832 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007833 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007834 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007835 // Is there any previous explicit specialization declaration?
7836 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7837 Okay = true;
7838 break;
7839 }
7840 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007841
Douglas Gregorc854c662010-02-26 06:03:23 +00007842 if (!Okay) {
7843 SourceRange Range(TemplateNameLoc, RAngleLoc);
7844 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
7845 << Context.getTypeDeclType(Specialization) << Range;
7846
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007847 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00007848 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007849 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00007850 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00007851 return true;
7852 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007853 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007854
Douglas Gregor2208a292009-09-26 20:57:03 +00007855 // If this is not a friend, note that this is an explicit specialization.
7856 if (TUK != TUK_Friend)
7857 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00007858
7859 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00007860 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00007861 RecordDecl *Def = Specialization->getDefinition();
7862 NamedDecl *Hidden = nullptr;
7863 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
7864 SkipBody->ShouldSkip = true;
Richard Smithc4577662018-09-12 02:13:47 +00007865 SkipBody->Previous = Def;
Richard Smith858e0e02017-05-11 23:11:16 +00007866 makeMergedDefinitionVisible(Hidden);
Richard Smithc7e6ff02015-05-18 20:36:47 +00007867 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00007868 SourceRange Range(TemplateNameLoc, RAngleLoc);
Richard Smith792c22d2016-12-24 04:09:05 +00007869 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00007870 Diag(Def->getLocation(), diag::note_previous_definition);
7871 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00007872 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00007873 }
7874 }
7875
Erich Keanec480f302018-07-12 21:09:05 +00007876 ProcessDeclAttributeList(S, Specialization, Attr);
John McCall659a3372010-12-18 03:30:47 +00007877
Richard Smith034b94a2012-08-17 03:20:55 +00007878 // Add alignment attributes if necessary; these attributes are checked when
7879 // the ASTContext lays out the structure.
Richard Smithc4577662018-09-12 02:13:47 +00007880 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
Richard Smith034b94a2012-08-17 03:20:55 +00007881 AddAlignmentAttributesForRecord(Specialization);
7882 AddMsStructLayoutForRecord(Specialization);
7883 }
7884
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00007885 if (ModulePrivateLoc.isValid())
7886 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
7887 << (isPartialSpecialization? 1 : 0)
7888 << FixItHint::CreateRemoval(ModulePrivateLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00007889
Douglas Gregord56a91e2009-02-26 22:19:44 +00007890 // Build the fully-sugared type for this class template
7891 // specialization as the user wrote in the specialization
7892 // itself. This means that we'll pretty-print the type retrieved
7893 // from the specialization's declaration the way that the user
7894 // actually wrote the specialization, rather than formatting the
7895 // name based on the "canonical" representation used to store the
7896 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007897 TypeSourceInfo *WrittenTy
7898 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7899 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007900 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00007901 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007902 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007903 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007904
Douglas Gregor1e249f82009-02-25 22:18:32 +00007905 // C++ [temp.expl.spec]p9:
7906 // A template explicit specialization is in the scope of the
7907 // namespace in which the template was defined.
7908 //
7909 // We actually implement this paragraph where we set the semantic
7910 // context (in the creation of the ClassTemplateSpecializationDecl),
7911 // but we also maintain the lexical context where the actual
7912 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00007913 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00007914
Douglas Gregor67a65642009-02-17 23:15:12 +00007915 // We may be starting the definition of this specialization.
Richard Smithc4577662018-09-12 02:13:47 +00007916 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
Douglas Gregor67a65642009-02-17 23:15:12 +00007917 Specialization->startDefinition();
7918
Douglas Gregor2208a292009-09-26 20:57:03 +00007919 if (TUK == TUK_Friend) {
7920 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
7921 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00007922 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00007923 /*FIXME:*/KWLoc);
7924 Friend->setAccess(AS_public);
7925 CurContext->addDecl(Friend);
7926 } else {
7927 // Add the specialization into its lexical context, so that it can
7928 // be seen when iterating through the list of declarations in that
7929 // context. However, specializations are not found by name lookup.
7930 CurContext->addDecl(Specialization);
7931 }
Richard Smithc4577662018-09-12 02:13:47 +00007932
7933 if (SkipBody && SkipBody->ShouldSkip)
7934 return SkipBody->Previous;
7935
John McCall48871652010-08-21 09:40:31 +00007936 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00007937}
Douglas Gregor333489b2009-03-27 23:10:48 +00007938
John McCall48871652010-08-21 09:40:31 +00007939Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00007940 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00007941 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007942 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00007943 ActOnDocumentableDecl(NewDecl);
7944 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00007945}
7946
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007947/// Strips various properties off an implicit instantiation
John McCall4f7ced62010-02-11 01:33:53 +00007948/// that has just been explicitly specialized.
7949static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00007950 D->dropAttr<DLLImportAttr>();
7951 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00007952
Nico Webere4974382014-12-19 23:52:45 +00007953 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00007954 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00007955}
7956
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007957/// Compute the diagnostic location for an explicit instantiation
Nico Webera8f80b32012-01-09 19:52:25 +00007958// declaration or definition.
7959static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007960 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00007961 // Explicit instantiations following a specialization have no effect and
7962 // hence no PointOfInstantiation. In that case, walk decl backwards
7963 // until a valid name loc is found.
7964 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007965 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
7966 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00007967 PrevDiagLoc = Prev->getLocation();
7968 }
7969 assert(PrevDiagLoc.isValid() &&
7970 "Explicit instantiation without point of instantiation?");
7971 return PrevDiagLoc;
7972}
7973
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007974/// Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007975/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007976/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007977/// new specialization/instantiation will have any effect.
7978///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007979/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007980/// instantiation.
7981///
7982/// \param NewTSK the kind of the new explicit specialization or instantiation.
7983///
7984/// \param PrevDecl the previous declaration of the entity.
7985///
7986/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
7987///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007988/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007989/// declaration was instantiated (either implicitly or explicitly).
7990///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007991/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007992/// specialization or instantiation has no effect and should be ignored.
7993///
7994/// \returns true if there was an error that should prevent the introduction of
7995/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00007996bool
7997Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7998 TemplateSpecializationKind NewTSK,
7999 NamedDecl *PrevDecl,
8000 TemplateSpecializationKind PrevTSK,
8001 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00008002 bool &HasNoEffect) {
8003 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008004
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008005 switch (NewTSK) {
8006 case TSK_Undeclared:
8007 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00008008 assert(
8009 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
8010 "previous declaration must be implicit!");
8011 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008012
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008013 case TSK_ExplicitSpecialization:
8014 switch (PrevTSK) {
8015 case TSK_Undeclared:
8016 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008017 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008018 // explicitly specialized or has merely been mentioned without any
8019 // instantiation.
8020 return false;
8021
8022 case TSK_ImplicitInstantiation:
8023 if (PrevPointOfInstantiation.isInvalid()) {
8024 // The declaration itself has not actually been instantiated, so it is
8025 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00008026 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008027 return false;
8028 }
8029 // Fall through
Galina Kistanova3779cb32017-06-07 06:25:05 +00008030 LLVM_FALLTHROUGH;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008031
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008032 case TSK_ExplicitInstantiationDeclaration:
8033 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008034 assert((PrevTSK == TSK_ImplicitInstantiation ||
8035 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008036 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008037
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008038 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008039 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008040 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008041 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008042 // implicit instantiation to take place, in every translation unit in
8043 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00008044 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00008045 // Is there any previous explicit specialization declaration?
8046 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
8047 return false;
8048 }
8049
Douglas Gregor1d957a32009-10-27 18:42:08 +00008050 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008051 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008052 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008053 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008054
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008055 return true;
8056 }
Galina Kistanova1d36e832017-06-08 18:20:32 +00008057 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008058
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008059 case TSK_ExplicitInstantiationDeclaration:
8060 switch (PrevTSK) {
8061 case TSK_ExplicitInstantiationDeclaration:
8062 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00008063 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008064 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008065
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008066 case TSK_Undeclared:
8067 case TSK_ImplicitInstantiation:
8068 // We're explicitly instantiating something that may have already been
8069 // implicitly instantiated; that's fine.
8070 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008071
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008072 case TSK_ExplicitSpecialization:
8073 // C++0x [temp.explicit]p4:
8074 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008075 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008076 // specialization for that template, the explicit instantiation has no
8077 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00008078 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008079 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008080
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008081 case TSK_ExplicitInstantiationDefinition:
8082 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008083 // If an entity is the subject of both an explicit instantiation
8084 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008085 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008086 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00008087 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00008088
8089 // Explicit instantiations following a specialization have no effect and
8090 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
8091 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00008092 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
8093 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008094 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008095 return false;
8096 }
Bruno Riccid8c17672018-12-21 20:38:06 +00008097 llvm_unreachable("Unexpected TemplateSpecializationKind!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008098
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008099 case TSK_ExplicitInstantiationDefinition:
8100 switch (PrevTSK) {
8101 case TSK_Undeclared:
8102 case TSK_ImplicitInstantiation:
8103 // We're explicitly instantiating something that may have already been
8104 // implicitly instantiated; that's fine.
8105 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008106
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008107 case TSK_ExplicitSpecialization:
8108 // C++ DR 259, C++0x [temp.explicit]p4:
8109 // For a given set of template parameters, if an explicit
8110 // instantiation of a template appears after a declaration of
8111 // an explicit specialization for that template, the explicit
8112 // instantiation has no effect.
Richard Smithe4caa482016-08-31 23:23:25 +00008113 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
Richard Smith0bf8a4922011-10-18 20:49:44 +00008114 << PrevDecl;
8115 Diag(PrevDecl->getLocation(),
8116 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008117 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008118 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008119
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008120 case TSK_ExplicitInstantiationDeclaration:
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00008121 // We're explicitly instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008122 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00008123
8124 // C++0x [temp.explicit]p4:
8125 // For a given set of template parameters, if an explicit instantiation
8126 // of a template appears after a declaration of an explicit
8127 // specialization for that template, the explicit instantiation has no
8128 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00008129 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00008130 // Is there any previous explicit specialization declaration?
8131 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
8132 HasNoEffect = true;
8133 break;
8134 }
8135 }
8136
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008137 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008138
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008139 case TSK_ExplicitInstantiationDefinition:
8140 // C++0x [temp.spec]p5:
8141 // For a given template and a given set of template-arguments,
8142 // - an explicit instantiation definition shall appear at most once
8143 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00008144
8145 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
8146 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00008147 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00008148 : diag::err_explicit_instantiation_duplicate)
8149 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00008150 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00008151 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008152 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008153 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008154 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008155 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008156
David Blaikie83d382b2011-09-23 05:06:16 +00008157 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008158}
8159
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008160/// Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00008161/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00008162///
James Dennettf14a6e52012-06-15 22:23:43 +00008163/// The only possible way to get a dependent function template specialization
8164/// is with a friend declaration, like so:
8165///
8166/// \code
8167/// template \<class T> void foo(T);
8168/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00008169/// friend void foo<>(T);
8170/// };
James Dennettf14a6e52012-06-15 22:23:43 +00008171/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00008172///
8173/// There really isn't any useful analysis we can do here, so we
8174/// just store the information.
8175bool
8176Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
8177 const TemplateArgumentListInfo &ExplicitTemplateArgs,
8178 LookupResult &Previous) {
8179 // Remove anything from Previous that isn't a function template in
8180 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00008181 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00008182 LookupResult::Filter F = Previous.makeFilter();
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008183 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
8184 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
John McCallb9c78482010-04-08 09:05:18 +00008185 while (F.hasNext()) {
8186 NamedDecl *D = F.next()->getUnderlyingDecl();
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008187 if (!isa<FunctionTemplateDecl>(D)) {
John McCallb9c78482010-04-08 09:05:18 +00008188 F.erase();
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008189 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
8190 continue;
8191 }
8192
8193 if (!FDLookupContext->InEnclosingNamespaceSetOf(
8194 D->getDeclContext()->getRedeclContext())) {
8195 F.erase();
8196 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
8197 continue;
8198 }
John McCallb9c78482010-04-08 09:05:18 +00008199 }
8200 F.done();
8201
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008202 if (Previous.empty()) {
8203 Diag(FD->getLocation(),
8204 diag::err_dependent_function_template_spec_no_match);
8205 for (auto &P : DiscardedCandidates)
8206 Diag(P.second->getLocation(),
8207 diag::note_dependent_function_template_spec_discard_reason)
8208 << P.first;
8209 return true;
8210 }
John McCallb9c78482010-04-08 09:05:18 +00008211
8212 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
8213 ExplicitTemplateArgs);
8214 return false;
8215}
8216
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008217/// Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008218/// specialization.
8219///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008220/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008221/// explicit function template specialization. On successful completion,
8222/// the function declaration \p FD will become a function template
8223/// specialization.
8224///
8225/// \param FD the function declaration, which will be updated to become a
8226/// function template specialization.
8227///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008228/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
8229/// if any. Note that this may be valid info even when 0 arguments are
8230/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
8231/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008232///
Francois Pichet3a44e432011-07-08 06:21:47 +00008233/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008234/// this function specialization.
Richard Smith8ce732b2019-01-07 06:00:46 +00008235///
8236/// \param QualifiedFriend whether this is a lookup for a qualified friend
8237/// declaration with no explicit template argument list that might be
8238/// befriending a function template specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008239bool Sema::CheckFunctionTemplateSpecialization(
8240 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smith8ce732b2019-01-07 06:00:46 +00008241 LookupResult &Previous, bool QualifiedFriend) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008242 // The set of function template specializations that could match this
8243 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00008244 UnresolvedSet<8> Candidates;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008245 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
8246 /*ForTakingAddress=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008247
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008248 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
8249 ConvertedTemplateArgs;
8250
Sebastian Redl50c68252010-08-31 00:36:30 +00008251 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00008252 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8253 I != E; ++I) {
8254 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
8255 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008256 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008257 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00008258 if (!FDLookupContext->InEnclosingNamespaceSetOf(
8259 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008260 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008261
Richard Smith574f4f62013-01-14 05:37:29 +00008262 // When matching a constexpr member function template specialization
8263 // against the primary template, we don't yet know whether the
8264 // specialization has an implicit 'const' (because we don't know whether
8265 // it will be a static member function until we know which template it
8266 // specializes), so adjust it now assuming it specializes this template.
8267 QualType FT = FD->getType();
8268 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00008269 CXXMethodDecl *OldMD =
8270 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00008271 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00008272 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00008273 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00008274 EPI.TypeQuals.addConst();
Alp Toker314cc812014-01-25 16:55:45 +00008275 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00008276 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00008277 }
8278 }
8279
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008280 TemplateArgumentListInfo Args;
8281 if (ExplicitTemplateArgs)
8282 Args = *ExplicitTemplateArgs;
8283
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008284 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008285 // A trailing template-argument can be left unspecified in the
8286 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008287 // provided it can be deduced from the function argument type.
8288 // Perform template argument deduction to determine whether we may be
8289 // specializing this template.
8290 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00008291 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00008292 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00008293 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
8294 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
Richard Smithc2bebe92016-05-11 20:37:46 +00008295 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
8296 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008297 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008298 // that we can provide nifty diagnostics.
Richard Smithc2bebe92016-05-11 20:37:46 +00008299 FailedCandidates.addCandidate().set(
8300 I.getPair(), FunTmpl->getTemplatedDecl(),
8301 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008302 (void)TDK;
8303 continue;
8304 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008305
Artem Belevich64135c32016-12-08 19:38:13 +00008306 // Target attributes are part of the cuda function signature, so
8307 // the deduced template's cuda target must match that of the
8308 // specialization. Given that C++ template deduction does not
8309 // take target attributes into account, we reject candidates
8310 // here that have a different target.
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008311 if (LangOpts.CUDA &&
Artem Belevich64135c32016-12-08 19:38:13 +00008312 IdentifyCUDATarget(Specialization,
8313 /* IgnoreImplicitHDAttributes = */ true) !=
8314 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttributes = */ true)) {
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008315 FailedCandidates.addCandidate().set(
8316 I.getPair(), FunTmpl->getTemplatedDecl(),
8317 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
8318 continue;
8319 }
8320
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008321 // Record this candidate.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008322 if (ExplicitTemplateArgs)
8323 ConvertedTemplateArgs[Specialization] = std::move(Args);
John McCall58cc69d2010-01-27 01:50:18 +00008324 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008325 }
8326 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008327
Richard Smith8ce732b2019-01-07 06:00:46 +00008328 // For a qualified friend declaration (with no explicit marker to indicate
8329 // that a template specialization was intended), note all (template and
8330 // non-template) candidates.
8331 if (QualifiedFriend && Candidates.empty()) {
8332 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
8333 << FD->getDeclName() << FDLookupContext;
8334 // FIXME: We should form a single candidate list and diagnose all
8335 // candidates at once, to get proper sorting and limiting.
8336 for (auto *OldND : Previous) {
8337 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
8338 NoteOverloadCandidate(OldND, OldFD, FD->getType(), false);
8339 }
8340 FailedCandidates.NoteCandidates(*this, FD->getLocation());
8341 return true;
8342 }
8343
Douglas Gregor5de279c2009-09-26 03:41:46 +00008344 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008345 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith8ce732b2019-01-07 06:00:46 +00008346 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
Larisse Voufo98b20f12013-07-19 23:00:19 +00008347 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
8348 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00008349 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00008350 PDiag(diag::note_function_template_spec_matched));
8351
John McCall58cc69d2010-01-27 01:50:18 +00008352 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008353 return true;
John McCall58cc69d2010-01-27 01:50:18 +00008354
8355 // Ignore access information; it doesn't figure into redeclaration checking.
8356 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00008357
8358 FunctionTemplateSpecializationInfo *SpecInfo
8359 = Specialization->getTemplateSpecializationInfo();
8360 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00008361
8362 // Note: do not overwrite location info if previous template
8363 // specialization kind was explicit.
8364 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00008365 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00008366 Specialization->setLocation(FD->getLocation());
Richard Smith54f04402017-05-18 02:29:20 +00008367 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
Richard Smith5b8b3db2012-02-20 23:28:05 +00008368 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
8369 // function can differ from the template declaration with respect to
8370 // the constexpr specifier.
Richard Smith77e9e842017-05-09 23:02:10 +00008371 // FIXME: We need an update record for this AST mutation.
8372 // FIXME: What if there are multiple such prior declarations (for instance,
8373 // from different modules)?
Richard Smith5b8b3db2012-02-20 23:28:05 +00008374 Specialization->setConstexpr(FD->isConstexpr());
8375 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008376
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008377 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00008378 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00008379
8380 // If this is a friend declaration, then we're not really declaring
8381 // an explicit specialization.
8382 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008383
Douglas Gregor54888652009-10-07 00:13:32 +00008384 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00008385 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008386 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00008387 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008388 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00008389 false))
Douglas Gregor54888652009-10-07 00:13:32 +00008390 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00008391
8392 // C++ [temp.expl.spec]p6:
8393 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008394 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00008395 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008396 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00008397 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00008398 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00008399 if (!isFriend &&
8400 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00008401 TSK_ExplicitSpecialization,
8402 Specialization,
8403 SpecInfo->getTemplateSpecializationKind(),
8404 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008405 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00008406 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008407
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008408 // Mark the prior declaration as an explicit specialization, so that later
8409 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00008410 if (!isFriend) {
Faisal Vali81a88be2016-06-14 03:23:15 +00008411 // Since explicit specializations do not inherit '=delete' from their
8412 // primary function template - check if the 'specialization' that was
8413 // implicitly generated (during template argument deduction for partial
8414 // ordering) from the most specialized of all the function templates that
8415 // 'FD' could have been specializing, has a 'deleted' definition. If so,
8416 // first check that it was implicitly generated during template argument
8417 // deduction by making sure it wasn't referenced, and then reset the deleted
8418 // flag to not-deleted, so that we can inherit that information from 'FD'.
8419 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
8420 !Specialization->getCanonicalDecl()->isReferenced()) {
Richard Smith77e9e842017-05-09 23:02:10 +00008421 // FIXME: This assert will not hold in the presence of modules.
Faisal Vali81a88be2016-06-14 03:23:15 +00008422 assert(
8423 Specialization->getCanonicalDecl() == Specialization &&
8424 "This must be the only existing declaration of this specialization");
Richard Smith77e9e842017-05-09 23:02:10 +00008425 // FIXME: We need an update record for this AST mutation.
Faisal Vali81a88be2016-06-14 03:23:15 +00008426 Specialization->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008427 }
Richard Smith54f04402017-05-18 02:29:20 +00008428 // FIXME: We need an update record for this AST mutation.
John McCall816d75b2010-03-24 07:46:06 +00008429 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00008430 MarkUnusedFileScopedDecl(Specialization);
8431 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008432
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008433 // Turn the given function declaration into a function template
8434 // specialization, with the template arguments from the previous
8435 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008436 // Take copies of (semantic and syntactic) template argument lists.
8437 const TemplateArgumentList* TemplArgs = new (Context)
8438 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008439 FD->setFunctionTemplateSpecialization(
8440 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
8441 SpecInfo->getTemplateSpecializationKind(),
8442 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008443
Artem Belevich64135c32016-12-08 19:38:13 +00008444 // A function template specialization inherits the target attributes
8445 // of its template. (We require the attributes explicitly in the
8446 // code to match, but a template may have implicit attributes by
8447 // virtue e.g. of being constexpr, and it passes these implicit
8448 // attributes on to its specializations.)
8449 if (LangOpts.CUDA)
8450 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
8451
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008452 // The "previous declaration" for this function template specialization is
8453 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00008454 Previous.clear();
8455 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008456 return false;
8457}
8458
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008459/// Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008460/// specialization.
8461///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008462/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008463/// explicit member function specialization. On successful completion,
8464/// the function declaration \p FD will become a member function
8465/// specialization.
8466///
Douglas Gregor86d142a2009-10-08 07:24:58 +00008467/// \param Member the member declaration, which will be updated to become a
8468/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008469///
John McCall1f82f242009-11-18 22:49:29 +00008470/// \param Previous the set of declarations, one of which may be specialized
8471/// by this function specialization; the set will be modified to contain the
8472/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008473bool
John McCall1f82f242009-11-18 22:49:29 +00008474Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008475 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00008476
Douglas Gregor86d142a2009-10-08 07:24:58 +00008477 // Try to find the member we are instantiating.
Richard Smith22e7cc62016-05-24 00:01:49 +00008478 NamedDecl *FoundInstantiation = nullptr;
Craig Topperc3ec1492014-05-26 06:22:03 +00008479 NamedDecl *Instantiation = nullptr;
8480 NamedDecl *InstantiatedFrom = nullptr;
8481 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00008482
John McCall1f82f242009-11-18 22:49:29 +00008483 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008484 // Nowhere to look anyway.
8485 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008486 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8487 I != E; ++I) {
8488 NamedDecl *D = (*I)->getUnderlyingDecl();
8489 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00008490 QualType Adjusted = Function->getType();
8491 if (!hasExplicitCallingConv(Adjusted))
8492 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
Richard Smith4576a772018-09-10 06:35:32 +00008493 // This doesn't handle deduced return types, but both function
8494 // declarations should be undeduced at this point.
Rafael Espindola66747222013-12-10 00:59:31 +00008495 if (Context.hasSameType(Adjusted, Method->getType())) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008496 FoundInstantiation = *I;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008497 Instantiation = Method;
8498 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008499 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008500 break;
8501 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008502 }
8503 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00008504 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008505 VarDecl *PrevVar;
8506 if (Previous.isSingleResult() &&
8507 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00008508 if (PrevVar->isStaticDataMember()) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008509 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00008510 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008511 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008512 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008513 }
8514 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008515 CXXRecordDecl *PrevRecord;
8516 if (Previous.isSingleResult() &&
8517 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008518 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00008519 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008520 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008521 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008522 }
Richard Smith7d137e32012-03-23 03:33:32 +00008523 } else if (isa<EnumDecl>(Member)) {
8524 EnumDecl *PrevEnum;
8525 if (Previous.isSingleResult() &&
8526 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008527 FoundInstantiation = Previous.getRepresentativeDecl();
Richard Smith7d137e32012-03-23 03:33:32 +00008528 Instantiation = PrevEnum;
8529 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
8530 MSInfo = PrevEnum->getMemberSpecializationInfo();
8531 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008532 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008533
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008534 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008535 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008536 // specializations are always out-of-line, the caller will complain about
8537 // this mismatch later.
8538 return false;
8539 }
John McCalle820e5e2010-04-13 20:37:33 +00008540
Richard Smith77e9e842017-05-09 23:02:10 +00008541 // A member specialization in a friend declaration isn't really declaring
8542 // an explicit specialization, just identifying a specific (possibly implicit)
8543 // specialization. Don't change the template specialization kind.
8544 //
8545 // FIXME: Is this really valid? Other compilers reject.
John McCalle820e5e2010-04-13 20:37:33 +00008546 if (Member->getFriendObjectKind() != Decl::FOK_None) {
8547 // Preserve instantiation information.
8548 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
8549 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
8550 cast<CXXMethodDecl>(InstantiatedFrom),
8551 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
8552 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
8553 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
8554 cast<CXXRecordDecl>(InstantiatedFrom),
8555 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
8556 }
8557
8558 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00008559 Previous.addDecl(FoundInstantiation);
John McCalle820e5e2010-04-13 20:37:33 +00008560 return false;
8561 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008562
Douglas Gregor86d142a2009-10-08 07:24:58 +00008563 // Make sure that this is a specialization of a member.
8564 if (!InstantiatedFrom) {
8565 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
8566 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008567 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
8568 return true;
8569 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008570
Douglas Gregor06db9f52009-10-12 20:18:28 +00008571 // C++ [temp.expl.spec]p6:
8572 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00008573 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00008574 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008575 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00008576 // use occurs; no diagnostic is required.
8577 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00008578
Abramo Bagnara8075c852010-06-12 07:44:57 +00008579 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00008580 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
8581 TSK_ExplicitSpecialization,
8582 Instantiation,
8583 MSInfo->getTemplateSpecializationKind(),
8584 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008585 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00008586 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008587
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008588 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008589 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00008590 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008591 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00008592 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008593 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00008594
Richard Smith77e9e842017-05-09 23:02:10 +00008595 // Note that this member specialization is an "instantiation of" the
8596 // corresponding member of the original template.
8597 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008598 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
8599 if (InstantiationFunction->getTemplateSpecializationKind() ==
8600 TSK_ImplicitInstantiation) {
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008601 // Explicit specializations of member functions of class templates do not
8602 // inherit '=delete' from the member function they are specializing.
8603 if (InstantiationFunction->isDeleted()) {
Richard Smith77e9e842017-05-09 23:02:10 +00008604 // FIXME: This assert will not hold in the presence of modules.
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008605 assert(InstantiationFunction->getCanonicalDecl() ==
8606 InstantiationFunction);
Richard Smith77e9e842017-05-09 23:02:10 +00008607 // FIXME: We need an update record for this AST mutation.
Richard Smith5f274382016-09-28 23:55:27 +00008608 InstantiationFunction->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008609 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008610 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008611
Richard Smith77e9e842017-05-09 23:02:10 +00008612 MemberFunction->setInstantiationOfMemberFunction(
8613 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8614 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
8615 MemberVar->setInstantiationOfStaticDataMember(
Larisse Voufo39a1e502013-08-06 01:03:05 +00008616 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Richard Smith77e9e842017-05-09 23:02:10 +00008617 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
8618 MemberClass->setInstantiationOfMemberClass(
8619 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8620 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
8621 MemberEnum->setInstantiationOfMemberEnum(
Richard Smith7d137e32012-03-23 03:33:32 +00008622 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Richard Smith77e9e842017-05-09 23:02:10 +00008623 } else {
8624 llvm_unreachable("unknown member specialization kind");
Douglas Gregor86d142a2009-10-08 07:24:58 +00008625 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008626
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008627 // Save the caller the trouble of having to figure out which declaration
8628 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00008629 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00008630 Previous.addDecl(FoundInstantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008631 return false;
8632}
8633
Richard Smith77e9e842017-05-09 23:02:10 +00008634/// Complete the explicit specialization of a member of a class template by
8635/// updating the instantiated member to be marked as an explicit specialization.
8636///
8637/// \param OrigD The member declaration instantiated from the template.
8638/// \param Loc The location of the explicit specialization of the member.
8639template<typename DeclT>
8640static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
8641 SourceLocation Loc) {
8642 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
8643 return;
8644
8645 // FIXME: Inform AST mutation listeners of this AST mutation.
8646 // FIXME: If there are multiple in-class declarations of the member (from
8647 // multiple modules, or a declaration and later definition of a member type),
8648 // should we update all of them?
8649 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
8650 OrigD->setLocation(Loc);
8651}
8652
8653void Sema::CompleteMemberSpecialization(NamedDecl *Member,
8654 LookupResult &Previous) {
8655 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
8656 if (Instantiation == Member)
8657 return;
8658
8659 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
8660 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
8661 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
8662 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
8663 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
8664 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
8665 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
8666 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
8667 else
8668 llvm_unreachable("unknown member specialization kind");
8669}
8670
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008671/// Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008672///
8673/// \returns true if a serious error occurs, false otherwise.
8674static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00008675 SourceLocation InstLoc,
8676 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00008677 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
8678 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008679
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008680 if (CurContext->isRecord()) {
8681 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
8682 << D;
8683 return true;
8684 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008685
Richard Smith050d2612011-10-18 02:28:33 +00008686 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008687 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00008688 // template. If the name declared in the explicit instantiation is an
8689 // unqualified name, the explicit instantiation shall appear in the
8690 // namespace where its template is declared or, if that namespace is inline
8691 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008692 //
8693 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00008694 if (WasQualifiedName) {
8695 if (CurContext->Encloses(OrigContext))
8696 return false;
8697 } else {
8698 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
8699 return false;
8700 }
8701
8702 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
8703 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008704 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008705 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008706 diag::err_explicit_instantiation_out_of_scope :
8707 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008708 << D << NS;
8709 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008710 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008711 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008712 diag::err_explicit_instantiation_unqualified_wrong_namespace :
8713 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
8714 << D << NS;
8715 } else
8716 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008717 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008718 diag::err_explicit_instantiation_must_be_global :
8719 diag::warn_explicit_instantiation_must_be_global_0x)
8720 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00008721 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008722 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00008723}
8724
Richard Smith0d923af2019-04-26 01:51:07 +00008725/// Common checks for whether an explicit instantiation of \p D is valid.
8726static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D,
8727 SourceLocation InstLoc,
8728 bool WasQualifiedName,
8729 TemplateSpecializationKind TSK) {
8730 // C++ [temp.explicit]p13:
8731 // An explicit instantiation declaration shall not name a specialization of
8732 // a template with internal linkage.
8733 if (TSK == TSK_ExplicitInstantiationDeclaration &&
8734 D->getFormalLinkage() == InternalLinkage) {
8735 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
8736 return true;
8737 }
8738
8739 // C++11 [temp.explicit]p3: [DR 275]
8740 // An explicit instantiation shall appear in an enclosing namespace of its
8741 // template.
8742 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
8743 return true;
8744
8745 return false;
8746}
8747
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008748/// Determine whether the given scope specifier has a template-id in it.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008749static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
8750 if (!SS.isSet())
8751 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008752
Richard Smith050d2612011-10-18 02:28:33 +00008753 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008754 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008755 // or a static data member of a class template specialization, the name of
8756 // the class template specialization in the qualified-id for the member
8757 // name shall be a simple-template-id.
8758 //
8759 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00008760 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
8761 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00008762 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00008763 if (isa<TemplateSpecializationType>(T))
8764 return true;
8765
8766 return false;
8767}
8768
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008769/// Make a dllexport or dllimport attr on a class template specialization take
8770/// effect.
8771static void dllExportImportClassTemplateSpecialization(
8772 Sema &S, ClassTemplateSpecializationDecl *Def) {
8773 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
8774 assert(A && "dllExportImportClassTemplateSpecialization called "
8775 "on Def without dllexport or dllimport");
8776
8777 // We reject explicit instantiations in class scope, so there should
8778 // never be any delayed exported classes to worry about.
8779 assert(S.DelayedDllExportClasses.empty() &&
8780 "delayed exports present at explicit instantiation");
8781 S.checkClassLevelDLLAttribute(Def);
8782
8783 // Propagate attribute to base class templates.
8784 for (auto &B : Def->bases()) {
8785 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
8786 B.getType()->getAsCXXRecordDecl()))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008787 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getBeginLoc());
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008788 }
8789
8790 S.referenceDLLExportedClassMethods();
8791}
8792
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008793// Explicit instantiation of a class template specialization
Erich Keanec480f302018-07-12 21:09:05 +00008794DeclResult Sema::ActOnExplicitInstantiation(
8795 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
8796 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
8797 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
8798 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
8799 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
Douglas Gregora1f49972009-05-13 00:25:59 +00008800 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00008801 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00008802 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00008803 // Check that the specialization uses the same tag kind as the
8804 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00008805 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8806 assert(Kind != TTK_Enum &&
8807 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00008808
Richard Trieu265c3442016-04-05 21:13:54 +00008809 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
8810
8811 if (!ClassTemplate) {
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00008812 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
8813 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
Richard Trieu265c3442016-04-05 21:13:54 +00008814 Diag(TD->getLocation(), diag::note_previous_use);
Richard Smith392497b2013-06-22 22:03:31 +00008815 return true;
8816 }
8817
Douglas Gregord9034f02009-05-14 16:41:31 +00008818 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00008819 Kind, /*isDefinition*/false, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00008820 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00008821 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00008822 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00008823 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00008824 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00008825 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00008826 diag::note_previous_use);
8827 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8828 }
8829
Douglas Gregore47f5a72009-10-14 23:41:34 +00008830 // C++0x [temp.explicit]p2:
8831 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008832 // definition and an explicit instantiation declaration. An explicit
8833 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00008834 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
8835 ? TSK_ExplicitInstantiationDefinition
8836 : TSK_ExplicitInstantiationDeclaration;
8837
Martin Storsjo5be69bc2019-04-26 08:09:51 +00008838 if (TSK == TSK_ExplicitInstantiationDeclaration &&
8839 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
8840 // Check for dllexport class template instantiation declarations,
8841 // except for MinGW mode.
Erich Keanee891aa92018-07-13 15:07:47 +00008842 for (const ParsedAttr &AL : Attr) {
8843 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
Hans Wennborgfd76d912015-01-15 21:18:30 +00008844 Diag(ExternLoc,
8845 diag::warn_attribute_dllexport_explicit_instantiation_decl);
Erich Keanec480f302018-07-12 21:09:05 +00008846 Diag(AL.getLoc(), diag::note_attribute);
Hans Wennborgfd76d912015-01-15 21:18:30 +00008847 break;
8848 }
8849 }
8850
8851 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
8852 Diag(ExternLoc,
8853 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8854 Diag(A->getLocation(), diag::note_attribute);
8855 }
8856 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008857
Hans Wennborga86a83b2016-05-26 19:42:56 +00008858 // In MSVC mode, dllimported explicit instantiation definitions are treated as
8859 // instantiation declarations for most purposes.
8860 bool DLLImportExplicitInstantiationDef = false;
8861 if (TSK == TSK_ExplicitInstantiationDefinition &&
8862 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
8863 // Check for dllimport class template instantiation definitions.
8864 bool DLLImport =
8865 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
Erich Keanee891aa92018-07-13 15:07:47 +00008866 for (const ParsedAttr &AL : Attr) {
8867 if (AL.getKind() == ParsedAttr::AT_DLLImport)
Hans Wennborga86a83b2016-05-26 19:42:56 +00008868 DLLImport = true;
Erich Keanee891aa92018-07-13 15:07:47 +00008869 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
Hans Wennborga86a83b2016-05-26 19:42:56 +00008870 // dllexport trumps dllimport here.
8871 DLLImport = false;
8872 break;
8873 }
8874 }
8875 if (DLLImport) {
8876 TSK = TSK_ExplicitInstantiationDeclaration;
8877 DLLImportExplicitInstantiationDef = true;
8878 }
8879 }
8880
Douglas Gregora1f49972009-05-13 00:25:59 +00008881 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00008882 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00008883 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00008884
8885 // Check that the template argument list is well-formed for this
8886 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008887 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00008888 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
8889 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00008890 return true;
8891
Douglas Gregora1f49972009-05-13 00:25:59 +00008892 // Find the class template specialization declaration that
8893 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00008894 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00008895 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00008896 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00008897
Abramo Bagnara8075c852010-06-12 07:44:57 +00008898 TemplateSpecializationKind PrevDecl_TSK
8899 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
8900
Martin Storsjo5be69bc2019-04-26 08:09:51 +00008901 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
8902 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
8903 // Check for dllexport class template instantiation definitions in MinGW
8904 // mode, if a previous declaration of the instantiation was seen.
8905 for (const ParsedAttr &AL : Attr) {
8906 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
8907 Diag(AL.getLoc(),
8908 diag::warn_attribute_dllexport_explicit_instantiation_def);
8909 break;
8910 }
8911 }
8912 }
8913
Richard Smith0d923af2019-04-26 01:51:07 +00008914 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
8915 SS.isSet(), TSK))
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008916 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008917
Craig Topperc3ec1492014-05-26 06:22:03 +00008918 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00008919
Abramo Bagnara8075c852010-06-12 07:44:57 +00008920 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00008921 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00008922 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00008923 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00008924 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008925 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00008926 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00008927
Abramo Bagnara8075c852010-06-12 07:44:57 +00008928 // Even though HasNoEffect == true means that this explicit instantiation
8929 // has no effect on semantics, we go on to put its syntax in the AST.
8930
8931 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
8932 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008933 // Since the only prior class template specialization with these
8934 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00008935 // declaration node as our own, updating the source location
8936 // for the template name to reflect our new declaration.
8937 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008938 Specialization = PrevDecl;
8939 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00008940 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008941 }
Hans Wennborga86a83b2016-05-26 19:42:56 +00008942
8943 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
8944 DLLImportExplicitInstantiationDef) {
8945 // The new specialization might add a dllimport attribute.
8946 HasNoEffect = false;
8947 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00008948 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00008949
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008950 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00008951 // Create a new class template specialization declaration node for
8952 // this explicit specialization.
8953 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00008954 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00008955 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00008956 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00008957 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00008958 Converted,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008959 PrevDecl);
Bruno Ricci4224c872018-12-21 14:35:24 +00008960 SetNestedNameSpecifier(*this, Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00008961
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00008962 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00008963 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00008964 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008965 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008966 }
8967
8968 // Build the fully-sugared type for this explicit instantiation as
8969 // the user wrote in the explicit instantiation itself. This means
8970 // that we'll pretty-print the type retrieved from the
8971 // specialization's declaration the way that the user actually wrote
8972 // the explicit instantiation, rather than formatting the name based
8973 // on the "canonical" representation used to store the template
8974 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00008975 TypeSourceInfo *WrittenTy
8976 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
8977 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00008978 Context.getTypeDeclType(Specialization));
8979 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00008980
Abramo Bagnara8075c852010-06-12 07:44:57 +00008981 // Set source locations for keywords.
8982 Specialization->setExternLoc(ExternLoc);
8983 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00008984 Specialization->setBraceRange(SourceRange());
Abramo Bagnara8075c852010-06-12 07:44:57 +00008985
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00008986 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
Erich Keanec480f302018-07-12 21:09:05 +00008987 ProcessDeclAttributeList(S, Specialization, Attr);
Rafael Espindola0b062072012-01-03 06:04:21 +00008988
Abramo Bagnara8075c852010-06-12 07:44:57 +00008989 // Add the explicit instantiation into its lexical context. However,
8990 // since explicit instantiations are never found by name lookup, we
8991 // just put it into the declaration context directly.
8992 Specialization->setLexicalDeclContext(CurContext);
8993 CurContext->addDecl(Specialization);
8994
8995 // Syntax is now OK, so return if it has no other effect on semantics.
8996 if (HasNoEffect) {
8997 // Set the template specialization kind.
8998 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00008999 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00009000 }
Douglas Gregora1f49972009-05-13 00:25:59 +00009001
9002 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00009003 // A definition of a class template or class member template
9004 // shall be in scope at the point of the explicit instantiation of
9005 // the class template or class member template.
9006 //
9007 // This check comes when we actually try to perform the
9008 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00009009 ClassTemplateSpecializationDecl *Def
9010 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009011 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00009012 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00009013 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00009014 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00009015 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00009016 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
9017 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00009018
Douglas Gregor1d957a32009-10-27 18:42:08 +00009019 // Instantiate the members of this class template specialization.
9020 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009021 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00009022 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00009023 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00009024 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
9025 // TSK_ExplicitInstantiationDefinition
9026 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborga86a83b2016-05-26 19:42:56 +00009027 (TSK == TSK_ExplicitInstantiationDefinition ||
9028 DLLImportExplicitInstantiationDef)) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00009029 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00009030 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00009031
Hans Wennborgc0875502015-06-09 00:39:05 +00009032 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
Shoaib Meenaiab3f96c2016-11-09 23:52:20 +00009033 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
9034 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
Hans Wennborgc0875502015-06-09 00:39:05 +00009035 // In the MS ABI, an explicit instantiation definition can add a dll
9036 // attribute to a template with a previous instantiation declaration.
9037 // MinGW doesn't allow this.
Hans Wennborg17f9b442015-05-27 00:06:45 +00009038 auto *A = cast<InheritableAttr>(
9039 getDLLAttr(Specialization)->clone(getASTContext()));
9040 A->setInherited(true);
9041 Def->addAttr(A);
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00009042 dllExportImportClassTemplateSpecialization(*this, Def);
Hans Wennborg17f9b442015-05-27 00:06:45 +00009043 }
9044 }
9045
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00009046 // Fix a TSK_ImplicitInstantiation followed by a
9047 // TSK_ExplicitInstantiationDefinition
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00009048 bool NewlyDLLExported =
9049 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
9050 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00009051 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
9052 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
9053 // In the MS ABI, an explicit instantiation definition can add a dll
9054 // attribute to a template with a previous implicit instantiation.
9055 // MinGW doesn't allow this. We limit clang to only adding dllexport, to
9056 // avoid potentially strange codegen behavior. For example, if we extend
9057 // this conditional to dllimport, and we have a source file calling a
9058 // method on an implicitly instantiated template class instance and then
9059 // declaring a dllimport explicit instantiation definition for the same
9060 // template class, the codegen for the method call will not respect the
9061 // dllimport, while it will with cl. The Def will already have the DLL
9062 // attribute, since the Def and Specialization will be the same in the
9063 // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
9064 // attribute to the Specialization; we just need to make it take effect.
9065 assert(Def == Specialization &&
9066 "Def and Specialization should match for implicit instantiation");
9067 dllExportImportClassTemplateSpecialization(*this, Def);
9068 }
9069
Martin Storsjo5be69bc2019-04-26 08:09:51 +00009070 // In MinGW mode, export the template instantiation if the declaration
9071 // was marked dllexport.
9072 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
9073 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
9074 PrevDecl->hasAttr<DLLExportAttr>()) {
9075 dllExportImportClassTemplateSpecialization(*this, Def);
9076 }
9077
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00009078 // Set the template specialization kind. Make sure it is set before
9079 // instantiating the members which will trigger ASTConsumer callbacks.
9080 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregor12e49d32009-10-15 22:53:21 +00009081 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00009082 } else {
9083
9084 // Set the template specialization kind.
9085 Specialization->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00009086 }
Douglas Gregora1f49972009-05-13 00:25:59 +00009087
John McCall48871652010-08-21 09:40:31 +00009088 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00009089}
9090
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009091// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00009092DeclResult
Erich Keanec480f302018-07-12 21:09:05 +00009093Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
9094 SourceLocation TemplateLoc, unsigned TagSpec,
9095 SourceLocation KWLoc, CXXScopeSpec &SS,
9096 IdentifierInfo *Name, SourceLocation NameLoc,
9097 const ParsedAttributesView &Attr) {
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009098
Douglas Gregord6ab8742009-05-28 23:31:59 +00009099 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00009100 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00009101 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00009102 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00009103 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00009104 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00009105 SourceLocation(), false, TypeResult(),
Akira Hatanaka12ddcee2017-06-26 18:46:12 +00009106 /*IsTypeSpecifier*/false,
9107 /*IsTemplateParamOrArg*/false);
John McCall7f41d982009-09-11 04:59:25 +00009108 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
9109
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009110 if (!TagD)
9111 return true;
9112
John McCall48871652010-08-21 09:40:31 +00009113 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00009114 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009115
Douglas Gregorb8006faf2009-05-27 17:30:49 +00009116 if (Tag->isInvalidDecl())
9117 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009118
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009119 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
9120 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
9121 if (!Pattern) {
9122 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
9123 << Context.getTypeDeclType(Record);
9124 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
9125 return true;
9126 }
9127
Douglas Gregore47f5a72009-10-14 23:41:34 +00009128 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009129 // If the explicit instantiation is for a class or member class, the
9130 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00009131 // simple-template-id.
9132 //
9133 // C++98 has the same restriction, just worded differently.
9134 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00009135 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00009136 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009137
Douglas Gregore47f5a72009-10-14 23:41:34 +00009138 // C++0x [temp.explicit]p2:
9139 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009140 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00009141 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00009142 TemplateSpecializationKind TSK
9143 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
9144 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009145
Richard Smith0d923af2019-04-26 01:51:07 +00009146 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009147
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009148 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009149 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00009150 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009151 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00009152 PrevDecl = Record;
9153 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009154 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00009155 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009156 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009157 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009158 PrevDecl,
9159 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009160 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00009161 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009162 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00009163 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009164 return TagD;
9165 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009166
Douglas Gregor12e49d32009-10-15 22:53:21 +00009167 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009168 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00009169 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00009170 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009171 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00009172 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009173 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009174 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00009175 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00009176 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
9177 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00009178 Diag(Pattern->getLocation(), diag::note_forward_declaration)
9179 << Pattern;
9180 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00009181 } else {
9182 if (InstantiateClass(NameLoc, Record, Def,
9183 getTemplateInstantiationArgs(Record),
9184 TSK))
9185 return true;
9186
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009187 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00009188 if (!RecordDef)
9189 return true;
9190 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009191 }
9192
Douglas Gregor1d957a32009-10-27 18:42:08 +00009193 // Instantiate all of the members of the class.
9194 InstantiateClassMembers(NameLoc, RecordDef,
9195 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009196
Douglas Gregor88d292c2010-05-13 16:44:06 +00009197 if (TSK == TSK_ExplicitInstantiationDefinition)
9198 MarkVTableUsed(NameLoc, RecordDef, true);
9199
Mike Stump87c57ac2009-05-16 07:39:55 +00009200 // FIXME: We don't have any representation for explicit instantiations of
9201 // member classes. Such a representation is not needed for compilation, but it
9202 // should be available for clients that want to see all of the declarations in
9203 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009204 return TagD;
9205}
9206
John McCallfaf5fb42010-08-26 23:41:50 +00009207DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
9208 SourceLocation ExternLoc,
9209 SourceLocation TemplateLoc,
9210 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00009211 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009212 // TODO: check if/when DNInfo should replace Name.
9213 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9214 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00009215 if (!Name) {
9216 if (!D.isInvalidType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009217 Diag(D.getDeclSpec().getBeginLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00009218 diag::err_explicit_instantiation_requires_name)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009219 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009220
Douglas Gregor450f00842009-09-25 18:43:00 +00009221 return true;
9222 }
9223
9224 // The scope passed in may not be a decl scope. Zip up the scope tree until
9225 // we find one that is.
9226 while ((S->getFlags() & Scope::DeclScope) == 0 ||
9227 (S->getFlags() & Scope::TemplateParamScope) != 0)
9228 S = S->getParent();
9229
9230 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00009231 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
9232 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00009233 if (R.isNull())
9234 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009235
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009236 // C++ [dcl.stc]p1:
Simon Pilgrim6905d222016-12-30 22:55:33 +00009237 // A storage-class-specifier shall not be specified in [...] an explicit
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009238 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00009239 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00009240 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
9241 << Name;
9242 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009243 } else if (D.getDeclSpec().getStorageClassSpec()
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009244 != DeclSpec::SCS_unspecified) {
9245 // Complain about then remove the storage class specifier.
9246 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
9247 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009248
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009249 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00009250 }
9251
Douglas Gregor3c74d412009-10-14 20:14:33 +00009252 // C++0x [temp.explicit]p1:
9253 // [...] An explicit instantiation of a function template shall not use the
9254 // inline or constexpr specifiers.
9255 // Presumably, this also applies to member functions of class templates as
9256 // well.
Richard Smith83c19292011-10-18 03:44:03 +00009257 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009258 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009259 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00009260 diag::err_explicit_instantiation_inline :
9261 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00009262 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00009263 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00009264 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
9265 // not already specified.
9266 Diag(D.getDeclSpec().getConstexprSpecLoc(),
9267 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009268
Richard Smith19a311a2017-02-09 22:47:51 +00009269 // A deduction guide is not on the list of entities that can be explicitly
9270 // instantiated.
9271 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009272 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
9273 << /*explicit instantiation*/ 0;
Richard Smith19a311a2017-02-09 22:47:51 +00009274 return true;
9275 }
9276
Douglas Gregore47f5a72009-10-14 23:41:34 +00009277 // C++0x [temp.explicit]p2:
9278 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009279 // definition and an explicit instantiation declaration. An explicit
9280 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00009281 TemplateSpecializationKind TSK
9282 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
9283 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009284
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009285 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00009286 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00009287
9288 if (!R->isFunctionType()) {
9289 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009290 // A [...] static data member of a class template can be explicitly
9291 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00009292 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00009293 // C++1y [temp.explicit]p1:
9294 // A [...] variable [...] template specialization can be explicitly
9295 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00009296 if (Previous.isAmbiguous())
9297 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009298
John McCall67c00872009-12-02 08:25:40 +00009299 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00009300 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009301
Larisse Voufo39a1e502013-08-06 01:03:05 +00009302 if (!PrevTemplate) {
9303 if (!Prev || !Prev->isStaticDataMember()) {
Richard Smitha6b41d72019-05-03 23:51:38 +00009304 // We expect to see a static data member here.
Larisse Voufo39a1e502013-08-06 01:03:05 +00009305 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
9306 << Name;
9307 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9308 P != PEnd; ++P)
9309 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
9310 return true;
9311 }
9312
9313 if (!Prev->getInstantiatedFromStaticDataMember()) {
9314 // FIXME: Check for explicit specialization?
9315 Diag(D.getIdentifierLoc(),
9316 diag::err_explicit_instantiation_data_member_not_instantiated)
9317 << Prev;
9318 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
9319 // FIXME: Can we provide a note showing where this was declared?
9320 return true;
9321 }
9322 } else {
9323 // Explicitly instantiate a variable template.
9324
9325 // C++1y [dcl.spec.auto]p6:
9326 // ... A program that uses auto or decltype(auto) in a context not
9327 // explicitly allowed in this section is ill-formed.
9328 //
9329 // This includes auto-typed variable template instantiations.
9330 if (R->isUndeducedType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009331 Diag(T->getTypeLoc().getBeginLoc(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00009332 diag::err_auto_not_allowed_var_inst);
9333 return true;
9334 }
9335
Faisal Vali2ab8c152017-12-30 04:15:27 +00009336 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
Richard Smithef985ac2013-09-18 02:10:12 +00009337 // C++1y [temp.explicit]p3:
9338 // If the explicit instantiation is for a variable, the unqualified-id
9339 // in the declaration shall be a template-id.
9340 Diag(D.getIdentifierLoc(),
9341 diag::err_explicit_instantiation_without_template_id)
9342 << PrevTemplate;
9343 Diag(PrevTemplate->getLocation(),
9344 diag::note_explicit_instantiation_here);
9345 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00009346 }
9347
Richard Smithef985ac2013-09-18 02:10:12 +00009348 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00009349 TemplateArgumentListInfo TemplateArgs =
9350 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00009351
Larisse Voufo39a1e502013-08-06 01:03:05 +00009352 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
9353 D.getIdentifierLoc(), TemplateArgs);
9354 if (Res.isInvalid())
9355 return true;
9356
9357 // Ignore access control bits, we don't need them for redeclaration
9358 // checking.
9359 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00009360 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009361
Douglas Gregore47f5a72009-10-14 23:41:34 +00009362 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009363 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00009364 // or a static data member of a class template specialization, the name of
9365 // the class template specialization in the qualified-id for the member
9366 // name shall be a simple-template-id.
9367 //
9368 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00009369 //
Richard Smith5977d872013-09-18 21:55:14 +00009370 // This does not apply to variable template specializations, where the
9371 // template-id is in the unqualified-id instead.
9372 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009373 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00009374 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00009375 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009376
Richard Smith0d923af2019-04-26 01:51:07 +00009377 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009378
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009379 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00009380 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
9381 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00009382 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00009383 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00009384 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009385 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009386
Larisse Voufo39a1e502013-08-06 01:03:05 +00009387 if (!HasNoEffect) {
9388 // Instantiate static data member or variable template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00009389 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Louis Dionnee6e81752018-10-10 15:32:29 +00009390 // Merge attributes.
9391 ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
Larisse Voufo39a1e502013-08-06 01:03:05 +00009392 if (TSK == TSK_ExplicitInstantiationDefinition)
9393 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
9394 }
9395
9396 // Check the new variable specialization against the parsed input.
9397 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009398 Diag(T->getTypeLoc().getBeginLoc(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00009399 diag::err_invalid_var_template_spec_type)
9400 << 0 << PrevTemplate << R << Prev->getType();
9401 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
9402 << 2 << PrevTemplate->getDeclName();
9403 return true;
9404 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009405
Douglas Gregor450f00842009-09-25 18:43:00 +00009406 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00009407 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009408 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009409
9410 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00009411 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00009412 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00009413 TemplateArgumentListInfo TemplateArgs;
Faisal Vali2ab8c152017-12-30 04:15:27 +00009414 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00009415 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00009416 HasExplicitTemplateArgs = true;
9417 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009418
Douglas Gregor450f00842009-09-25 18:43:00 +00009419 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009420 // A [...] function [...] can be explicitly instantiated from its template.
9421 // A member function [...] of a class template can be explicitly
9422 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00009423 // template.
John McCall27c11dd2017-06-07 23:00:05 +00009424 UnresolvedSet<8> TemplateMatches;
9425 FunctionDecl *NonTemplateMatch = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009426 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00009427 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9428 P != PEnd; ++P) {
9429 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00009430 if (!HasExplicitTemplateArgs) {
9431 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Richard Smithbaa47832016-12-01 02:11:49 +00009432 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
9433 /*AdjustExceptionSpec*/true);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00009434 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
John McCall27c11dd2017-06-07 23:00:05 +00009435 if (Method->getPrimaryTemplate()) {
9436 TemplateMatches.addDecl(Method, P.getAccess());
9437 } else {
9438 // FIXME: Can this assert ever happen? Needs a test.
9439 assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
9440 NonTemplateMatch = Method;
9441 }
Douglas Gregord90fd522009-09-25 21:45:23 +00009442 }
Douglas Gregor450f00842009-09-25 18:43:00 +00009443 }
9444 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009445
Douglas Gregor450f00842009-09-25 18:43:00 +00009446 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
9447 if (!FunTmpl)
9448 continue;
9449
Larisse Voufo98b20f12013-07-19 23:00:19 +00009450 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00009451 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009452 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009453 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00009454 (HasExplicitTemplateArgs ? &TemplateArgs
9455 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00009456 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009457 // Keep track of almost-matches.
9458 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +00009459 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +00009460 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00009461 (void)TDK;
9462 continue;
9463 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009464
Artem Belevich64135c32016-12-08 19:38:13 +00009465 // Target attributes are part of the cuda function signature, so
9466 // the cuda target of the instantiated function must match that of its
9467 // template. Given that C++ template deduction does not take
9468 // target attributes into account, we reject candidates here that
9469 // have a different target.
9470 if (LangOpts.CUDA &&
9471 IdentifyCUDATarget(Specialization,
9472 /* IgnoreImplicitHDAttributes = */ true) !=
Erich Keanec480f302018-07-12 21:09:05 +00009473 IdentifyCUDATarget(D.getDeclSpec().getAttributes())) {
Artem Belevich64135c32016-12-08 19:38:13 +00009474 FailedCandidates.addCandidate().set(
9475 P.getPair(), FunTmpl->getTemplatedDecl(),
9476 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
9477 continue;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00009478 }
9479
John McCall27c11dd2017-06-07 23:00:05 +00009480 TemplateMatches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00009481 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009482
John McCall27c11dd2017-06-07 23:00:05 +00009483 FunctionDecl *Specialization = NonTemplateMatch;
9484 if (!Specialization) {
9485 // Find the most specialized function template specialization.
9486 UnresolvedSetIterator Result = getMostSpecialized(
9487 TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
9488 D.getIdentifierLoc(),
9489 PDiag(diag::err_explicit_instantiation_not_known) << Name,
9490 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
9491 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00009492
John McCall27c11dd2017-06-07 23:00:05 +00009493 if (Result == TemplateMatches.end())
9494 return true;
John McCall58cc69d2010-01-27 01:50:18 +00009495
John McCall27c11dd2017-06-07 23:00:05 +00009496 // Ignore access control bits, we don't need them for redeclaration checking.
9497 Specialization = cast<FunctionDecl>(*Result);
9498 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009499
Alexey Bataev73983912014-11-06 10:10:50 +00009500 // C++11 [except.spec]p4
9501 // In an explicit instantiation an exception-specification may be specified,
9502 // but is not required.
9503 // If an exception-specification is specified in an explicit instantiation
9504 // directive, it shall be compatible with the exception-specifications of
9505 // other declarations of that function.
9506 if (auto *FPT = R->getAs<FunctionProtoType>())
9507 if (FPT->hasExceptionSpec()) {
9508 unsigned DiagID =
9509 diag::err_mismatched_exception_spec_explicit_instantiation;
9510 if (getLangOpts().MicrosoftExt)
9511 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
9512 bool Result = CheckEquivalentExceptionSpec(
9513 PDiag(DiagID) << Specialization->getType(),
9514 PDiag(diag::note_explicit_instantiation_here),
9515 Specialization->getType()->getAs<FunctionProtoType>(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009516 Specialization->getLocation(), FPT, D.getBeginLoc());
Alexey Bataev73983912014-11-06 10:10:50 +00009517 // In Microsoft mode, mismatching exception specifications just cause a
9518 // warning.
9519 if (!getLangOpts().MicrosoftExt && Result)
9520 return true;
9521 }
9522
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009523 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009524 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00009525 diag::err_explicit_instantiation_member_function_not_instantiated)
9526 << Specialization
9527 << (Specialization->getTemplateSpecializationKind() ==
9528 TSK_ExplicitSpecialization);
9529 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
9530 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009531 }
9532
Douglas Gregorec9fd132012-01-14 16:38:05 +00009533 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00009534 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
9535 PrevDecl = Specialization;
9536
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009537 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00009538 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00009539 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009540 PrevDecl,
9541 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009542 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00009543 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009544 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009545
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009546 // FIXME: We may still want to build some representation of this
9547 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00009548 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00009549 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009550 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00009551
Richard Smith0d923af2019-04-26 01:51:07 +00009552 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
9553 // functions
9554 // valarray<size_t>::valarray(size_t) and
9555 // valarray<size_t>::~valarray()
9556 // that it declared to have internal linkage with the internal_linkage
9557 // attribute. Ignore the explicit instantiation declaration in this case.
9558 if (Specialization->hasAttr<InternalLinkageAttr>() &&
9559 TSK == TSK_ExplicitInstantiationDeclaration) {
9560 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
9561 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
9562 RD->isInStdNamespace())
9563 return (Decl*) nullptr;
9564 }
9565
Erich Keanec480f302018-07-12 21:09:05 +00009566 ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009567
Hans Wennborgb8304a62017-11-29 23:44:11 +00009568 // In MSVC mode, dllimported explicit instantiation definitions are treated as
9569 // instantiation declarations.
9570 if (TSK == TSK_ExplicitInstantiationDefinition &&
9571 Specialization->hasAttr<DLLImportAttr>() &&
9572 Context.getTargetInfo().getCXXABI().isMicrosoft())
9573 TSK = TSK_ExplicitInstantiationDeclaration;
9574
9575 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9576
Richard Smitheb36ddf2014-04-24 22:45:46 +00009577 if (Specialization->isDefined()) {
9578 // Let the ASTConsumer know that this function has been explicitly
9579 // instantiated now, and its linkage might have changed.
9580 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
9581 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00009582 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009583
Douglas Gregore47f5a72009-10-14 23:41:34 +00009584 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009585 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00009586 // or a static data member of a class template specialization, the name of
9587 // the class template specialization in the qualified-id for the member
9588 // name shall be a simple-template-id.
9589 //
9590 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009591 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Faisal Vali2ab8c152017-12-30 04:15:27 +00009592 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009593 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00009594 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009595 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00009596 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00009597 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009598
Richard Smith0d923af2019-04-26 01:51:07 +00009599 CheckExplicitInstantiation(
9600 *this,
9601 FunTmpl ? (NamedDecl *)FunTmpl
9602 : Specialization->getInstantiatedFromMemberFunction(),
9603 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009604
Douglas Gregor450f00842009-09-25 18:43:00 +00009605 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00009606 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009607}
9608
John McCallfaf5fb42010-08-26 23:41:50 +00009609TypeResult
Faisal Vali090da2d2018-01-01 18:23:28 +00009610Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
John McCall7f41d982009-09-11 04:59:25 +00009611 const CXXScopeSpec &SS, IdentifierInfo *Name,
9612 SourceLocation TagLoc, SourceLocation NameLoc) {
9613 // This has to hold, because SS is expected to be defined.
9614 assert(Name && "Expected a name in a dependent tag");
9615
Aaron Ballman4a979672014-01-03 13:56:08 +00009616 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00009617 if (!NNS)
9618 return true;
9619
Abramo Bagnara6150c882010-05-11 21:36:43 +00009620 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00009621
Douglas Gregorba41d012010-04-24 16:38:41 +00009622 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
9623 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00009624 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00009625 return true;
9626 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00009627
Douglas Gregore7c20652011-03-02 00:47:37 +00009628 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00009629 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00009630 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009631
Douglas Gregore7c20652011-03-02 00:47:37 +00009632 // Create type-source location information for this type.
9633 TypeLocBuilder TLB;
9634 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009635 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00009636 TL.setQualifierLoc(SS.getWithLocInContext(Context));
9637 TL.setNameLoc(NameLoc);
9638 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00009639}
9640
John McCallfaf5fb42010-08-26 23:41:50 +00009641TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009642Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
9643 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00009644 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009645 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00009646 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009647
Richard Smith0bf8a4922011-10-18 20:49:44 +00009648 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9649 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009650 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00009651 diag::warn_cxx98_compat_typename_outside_of_template :
9652 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009653 << FixItHint::CreateRemoval(TypenameLoc);
9654
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009655 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00009656 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
9657 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00009658 if (T.isNull())
9659 return true;
John McCall99b2fe52010-04-29 23:50:39 +00009660
9661 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9662 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00009663 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009664 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009665 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00009666 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00009667 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00009668 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009669 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009670 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00009671 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00009672 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009673
John McCallba7bf592010-08-24 05:47:05 +00009674 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00009675}
9676
John McCallfaf5fb42010-08-26 23:41:50 +00009677TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009678Sema::ActOnTypenameType(Scope *S,
9679 SourceLocation TypenameLoc,
9680 const CXXScopeSpec &SS,
9681 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00009682 TemplateTy TemplateIn,
Richard Smith74f02342017-01-19 21:00:13 +00009683 IdentifierInfo *TemplateII,
9684 SourceLocation TemplateIILoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00009685 SourceLocation LAngleLoc,
9686 ASTTemplateArgsPtr TemplateArgsIn,
9687 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00009688 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9689 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009690 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00009691 diag::warn_cxx98_compat_typename_outside_of_template :
9692 diag::ext_typename_outside_of_template)
9693 << FixItHint::CreateRemoval(TypenameLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009694
Richard Smith74f02342017-01-19 21:00:13 +00009695 // Strangely, non-type results are not ignored by this lookup, so the
9696 // program is ill-formed if it finds an injected-class-name.
Richard Smith62559bd2017-02-01 21:36:38 +00009697 if (TypenameLoc.isValid()) {
9698 auto *LookupRD =
9699 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
9700 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
9701 Diag(TemplateIILoc,
9702 diag::ext_out_of_line_qualified_id_type_names_constructor)
9703 << TemplateII << 0 /*injected-class-name used as template name*/
9704 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
9705 }
Richard Smith74f02342017-01-19 21:00:13 +00009706 }
9707
Douglas Gregorb09518c2011-02-27 22:46:49 +00009708 // Translate the parser's template argument list in our AST format.
9709 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9710 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009711
Douglas Gregorb09518c2011-02-27 22:46:49 +00009712 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009713 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
9714 // Construct a dependent template specialization type.
9715 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00009716 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009717 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
9718 DTN->getQualifier(),
9719 DTN->getIdentifier(),
9720 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009721
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009722 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00009723 TypeLocBuilder Builder;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009724 DependentTemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009725 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009726 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
9727 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00009728 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00009729 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009730 SpecTL.setLAngleLoc(LAngleLoc);
9731 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009732 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9733 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009734 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00009735 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009736
Richard Smith74f02342017-01-19 21:00:13 +00009737 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009738 if (T.isNull())
9739 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009740
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009741 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00009742 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009743 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009744 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009745 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00009746 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009747 SpecTL.setLAngleLoc(LAngleLoc);
9748 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009749 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9750 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009751
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009752 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
9753 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009754 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009755 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Simon Pilgrim6905d222016-12-30 22:55:33 +00009756
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009757 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
9758 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00009759}
9760
Douglas Gregorb09518c2011-02-27 22:46:49 +00009761
Richard Smith6f8d2c62012-05-09 05:17:00 +00009762/// Determine whether this failed name lookup should be treated as being
9763/// disabled by a usage of std::enable_if.
9764static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009765 SourceRange &CondRange, Expr *&Cond) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00009766 // We must be looking for a ::type...
9767 if (!II.isStr("type"))
9768 return false;
9769
9770 // ... within an explicitly-written template specialization...
9771 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
9772 return false;
9773 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00009774 TemplateSpecializationTypeLoc EnableIfTSTLoc =
9775 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
9776 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00009777 return false;
George Burgess IV00f70bd2018-03-01 05:43:23 +00009778 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009779
9780 // ... which names a complete class template declaration...
9781 const TemplateDecl *EnableIfDecl =
9782 EnableIfTST->getTemplateName().getAsTemplateDecl();
9783 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
9784 return false;
9785
9786 // ... called "enable_if".
9787 const IdentifierInfo *EnableIfII =
9788 EnableIfDecl->getDeclName().getAsIdentifierInfo();
9789 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
9790 return false;
9791
9792 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00009793 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009794
9795 // Dig out the condition.
9796 Cond = nullptr;
9797 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
9798 != TemplateArgument::Expression)
9799 return true;
9800
9801 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
9802
9803 // Ignore Boolean literals; they add no value.
9804 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
9805 Cond = nullptr;
9806
Richard Smith6f8d2c62012-05-09 05:17:00 +00009807 return true;
9808}
9809
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009810/// Build the type that describes a C++ typename specifier,
Douglas Gregor333489b2009-03-27 23:10:48 +00009811/// e.g., "typename T::type".
9812QualType
Simon Pilgrim6905d222016-12-30 22:55:33 +00009813Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009814 SourceLocation KeywordLoc,
Simon Pilgrim6905d222016-12-30 22:55:33 +00009815 NestedNameSpecifierLoc QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009816 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00009817 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00009818 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009819 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00009820
John McCall0b66eb32010-05-01 00:40:08 +00009821 DeclContext *Ctx = computeDeclContext(SS);
9822 if (!Ctx) {
9823 // If the nested-name-specifier is dependent and couldn't be
9824 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009825 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009826 return Context.getDependentNameType(Keyword,
9827 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009828 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00009829 }
Douglas Gregor333489b2009-03-27 23:10:48 +00009830
John McCall0b66eb32010-05-01 00:40:08 +00009831 // If the nested-name-specifier refers to the current instantiation,
9832 // the "typename" keyword itself is superfluous. In C++03, the
9833 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
9834 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00009835 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00009836
John McCall0b66eb32010-05-01 00:40:08 +00009837 if (RequireCompleteDeclContext(SS, Ctx))
9838 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00009839
9840 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00009841 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00009842 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00009843 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00009844 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00009845 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00009846 case LookupResult::NotFound: {
9847 // If we're looking up 'type' within a template named 'enable_if', produce
9848 // a more specific diagnostic.
9849 SourceRange CondRange;
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009850 Expr *Cond = nullptr;
9851 if (isEnableIf(QualifierLoc, II, CondRange, Cond)) {
9852 // If we have a condition, narrow it down to the specific failed
9853 // condition.
9854 if (Cond) {
9855 Expr *FailedCond;
9856 std::string FailedDescription;
9857 std::tie(FailedCond, FailedDescription) =
Clement Courbetf44c6f42018-12-11 08:39:11 +00009858 findFailedBooleanCondition(Cond);
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009859
9860 Diag(FailedCond->getExprLoc(),
9861 diag::err_typename_nested_not_found_requirement)
9862 << FailedDescription
9863 << FailedCond->getSourceRange();
9864 return QualType();
9865 }
9866
Richard Smith6f8d2c62012-05-09 05:17:00 +00009867 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009868 << Ctx << CondRange;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009869 return QualType();
9870 }
9871
Douglas Gregore40876a2009-10-13 21:16:44 +00009872 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00009873 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009874 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009875
9876 case LookupResult::FoundUnresolvedValue: {
9877 // We found a using declaration that is a value. Most likely, the using
9878 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009879 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009880 IILoc);
9881 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
9882 << Name << Ctx << FullRange;
9883 if (UnresolvedUsingValueDecl *Using
9884 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009885 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009886 Diag(Loc, diag::note_using_value_decl_missing_typename)
9887 << FixItHint::CreateInsertion(Loc, "typename ");
9888 }
9889 }
9890 // Fall through to create a dependent typename type, from which we can recover
9891 // better.
Galina Kistanova3779cb32017-06-07 06:25:05 +00009892 LLVM_FALLTHROUGH;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009893
Douglas Gregord0d2ee02010-01-15 01:44:47 +00009894 case LookupResult::NotFoundInCurrentInstantiation:
9895 // Okay, it's a member of an unknown instantiation.
Simon Pilgrim6905d222016-12-30 22:55:33 +00009896 return Context.getDependentNameType(Keyword,
9897 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009898 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00009899
9900 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009901 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Richard Smith74f02342017-01-19 21:00:13 +00009902 // C++ [class.qual]p2:
9903 // In a lookup in which function names are not ignored and the
9904 // nested-name-specifier nominates a class C, if the name specified
9905 // after the nested-name-specifier, when looked up in C, is the
9906 // injected-class-name of C [...] then the name is instead considered
9907 // to name the constructor of class C.
9908 //
9909 // Unlike in an elaborated-type-specifier, function names are not ignored
9910 // in typename-specifier lookup. However, they are ignored in all the
9911 // contexts where we form a typename type with no keyword (that is, in
9912 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
9913 //
9914 // FIXME: That's not strictly true: mem-initializer-id lookup does not
9915 // ignore functions, but that appears to be an oversight.
9916 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
9917 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
9918 if (Keyword == ETK_Typename && LookupRD && FoundRD &&
9919 FoundRD->isInjectedClassName() &&
9920 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
9921 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
9922 << &II << 1 << 0 /*'typename' keyword used*/;
9923
Abramo Bagnara6150c882010-05-11 21:36:43 +00009924 // We found a type. Build an ElaboratedType, since the
9925 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00009926 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Richard Smith74f02342017-01-19 21:00:13 +00009927 return Context.getElaboratedType(Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009928 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00009929 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00009930 }
9931
Richard Smithee579842017-01-30 20:39:26 +00009932 // C++ [dcl.type.simple]p2:
9933 // A type-specifier of the form
9934 // typename[opt] nested-name-specifier[opt] template-name
9935 // is a placeholder for a deduced class type [...].
Aaron Ballmanc351fba2017-12-04 20:27:34 +00009936 if (getLangOpts().CPlusPlus17) {
Richard Smithee579842017-01-30 20:39:26 +00009937 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
9938 return Context.getElaboratedType(
9939 Keyword, QualifierLoc.getNestedNameSpecifier(),
9940 Context.getDeducedTemplateSpecializationType(TemplateName(TD),
9941 QualType(), false));
9942 }
9943 }
Richard Smith600b5262017-01-26 20:40:47 +00009944
Douglas Gregor333489b2009-03-27 23:10:48 +00009945 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00009946 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00009947 break;
9948
9949 case LookupResult::FoundOverloaded:
9950 DiagID = diag::err_typename_nested_not_type;
9951 Referenced = *Result.begin();
9952 break;
9953
John McCall6538c932009-10-10 05:48:19 +00009954 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00009955 return QualType();
9956 }
9957
9958 // If we get here, it's because name lookup did not find a
9959 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009960 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00009961 IILoc);
9962 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00009963 if (Referenced)
9964 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
9965 << Name;
9966 return QualType();
9967}
Douglas Gregor15acfb92009-08-06 16:20:37 +00009968
9969namespace {
9970 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00009971 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00009972 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00009973 SourceLocation Loc;
9974 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00009975
Douglas Gregor15acfb92009-08-06 16:20:37 +00009976 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00009977 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009978
Mike Stump11289f42009-09-09 15:08:12 +00009979 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00009980 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00009981 DeclarationName Entity)
9982 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00009983 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00009984
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009985 /// Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00009986 /// transformed.
9987 ///
9988 /// For the purposes of type reconstruction, a type has already been
9989 /// transformed if it is NULL or if it is not dependent.
9990 bool AlreadyTransformed(QualType T) {
9991 return T.isNull() || !T->isDependentType();
9992 }
Mike Stump11289f42009-09-09 15:08:12 +00009993
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009994 /// Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00009995 /// rebuilt.
9996 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00009997
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009998 /// Returns the name of the entity whose type is being rebuilt.
Douglas Gregor15acfb92009-08-06 16:20:37 +00009999 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +000010000
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010001 /// Sets the "base" location and entity when that
Douglas Gregoref6ab412009-10-27 06:26:26 +000010002 /// information is known based on another transformation.
10003 void setBase(SourceLocation Loc, DeclarationName Entity) {
10004 this->Loc = Loc;
10005 this->Entity = Entity;
10006 }
Simon Pilgrim6905d222016-12-30 22:55:33 +000010007
Douglas Gregor0c46b2b2012-02-13 22:00:16 +000010008 ExprResult TransformLambdaExpr(LambdaExpr *E) {
10009 // Lambdas never need to be transformed.
10010 return E;
10011 }
Douglas Gregor15acfb92009-08-06 16:20:37 +000010012 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010013} // end anonymous namespace
Douglas Gregor15acfb92009-08-06 16:20:37 +000010014
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010015/// Rebuilds a type within the context of the current instantiation.
Douglas Gregor15acfb92009-08-06 16:20:37 +000010016///
Mike Stump11289f42009-09-09 15:08:12 +000010017/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +000010018/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +000010019/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +000010020/// partial specialization thereof). This routine will rebuild that type now
10021/// that we have entered the declarator's scope, which may produce different
10022/// canonical types, e.g.,
10023///
10024/// \code
10025/// template<typename T>
10026/// struct X {
10027/// typedef T* pointer;
10028/// pointer data();
10029/// };
10030///
10031/// template<typename T>
10032/// typename X<T>::pointer X<T>::data() { ... }
10033/// \endcode
10034///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +000010035/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +000010036/// since we do not know that we can look into X<T> when we parsed the type.
10037/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +000010038/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +000010039/// as the canonical type of T*, allowing the return types of the out-of-line
10040/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +000010041TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
10042 SourceLocation Loc,
10043 DeclarationName Name) {
10044 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +000010045 return T;
Mike Stump11289f42009-09-09 15:08:12 +000010046
Douglas Gregor15acfb92009-08-06 16:20:37 +000010047 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
10048 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +000010049}
Douglas Gregorbe999392009-09-15 16:23:51 +000010050
John McCalldadc5752010-08-24 06:29:42 +000010051ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +000010052 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
10053 DeclarationName());
10054 return Rebuilder.TransformExpr(E);
10055}
10056
John McCall99b2fe52010-04-29 23:50:39 +000010057bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Simon Pilgrim6905d222016-12-30 22:55:33 +000010058 if (SS.isInvalid())
Douglas Gregor10176412011-02-25 16:07:42 +000010059 return true;
John McCall2408e322010-04-27 00:57:59 +000010060
Douglas Gregor10176412011-02-25 16:07:42 +000010061 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +000010062 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
10063 DeclarationName());
Simon Pilgrim6905d222016-12-30 22:55:33 +000010064 NestedNameSpecifierLoc Rebuilt
Douglas Gregor10176412011-02-25 16:07:42 +000010065 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +000010066 if (!Rebuilt)
Douglas Gregor10176412011-02-25 16:07:42 +000010067 return true;
John McCall99b2fe52010-04-29 23:50:39 +000010068
Douglas Gregor10176412011-02-25 16:07:42 +000010069 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +000010070 return false;
John McCall2408e322010-04-27 00:57:59 +000010071}
10072
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010073/// Rebuild the template parameters now that we know we're in a current
Douglas Gregor041b0842011-10-14 15:31:12 +000010074/// instantiation.
10075bool Sema::RebuildTemplateParamsInCurrentInstantiation(
10076 TemplateParameterList *Params) {
10077 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
10078 Decl *Param = Params->getParam(I);
Simon Pilgrim6905d222016-12-30 22:55:33 +000010079
Douglas Gregor041b0842011-10-14 15:31:12 +000010080 // There is nothing to rebuild in a type parameter.
10081 if (isa<TemplateTypeParmDecl>(Param))
10082 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +000010083
Douglas Gregor041b0842011-10-14 15:31:12 +000010084 // Rebuild the template parameter list of a template template parameter.
Simon Pilgrim6905d222016-12-30 22:55:33 +000010085 if (TemplateTemplateParmDecl *TTP
Douglas Gregor041b0842011-10-14 15:31:12 +000010086 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
10087 if (RebuildTemplateParamsInCurrentInstantiation(
10088 TTP->getTemplateParameters()))
10089 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +000010090
Douglas Gregor041b0842011-10-14 15:31:12 +000010091 continue;
10092 }
Simon Pilgrim6905d222016-12-30 22:55:33 +000010093
Douglas Gregor041b0842011-10-14 15:31:12 +000010094 // Rebuild the type of a non-type template parameter.
10095 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
Simon Pilgrim6905d222016-12-30 22:55:33 +000010096 TypeSourceInfo *NewTSI
10097 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
10098 NTTP->getLocation(),
Douglas Gregor041b0842011-10-14 15:31:12 +000010099 NTTP->getDeclName());
10100 if (!NewTSI)
10101 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +000010102
Erik Pilkington9f9462a2018-08-07 22:59:02 +000010103 if (NewTSI->getType()->isUndeducedType()) {
10104 // C++17 [temp.dep.expr]p3:
10105 // An id-expression is type-dependent if it contains
10106 // - an identifier associated by name lookup with a non-type
10107 // template-parameter declared with a type that contains a
10108 // placeholder type (7.1.7.4),
10109 NewTSI = SubstAutoTypeSourceInfo(NewTSI, Context.DependentTy);
10110 }
10111
Douglas Gregor041b0842011-10-14 15:31:12 +000010112 if (NewTSI != NTTP->getTypeSourceInfo()) {
10113 NTTP->setTypeSourceInfo(NewTSI);
10114 NTTP->setType(NewTSI->getType());
10115 }
10116 }
Simon Pilgrim6905d222016-12-30 22:55:33 +000010117
Douglas Gregor041b0842011-10-14 15:31:12 +000010118 return false;
10119}
10120
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010121/// Produces a formatted string that describes the binding of
Douglas Gregorbe999392009-09-15 16:23:51 +000010122/// template parameters to template arguments.
10123std::string
10124Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
10125 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +000010126 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +000010127}
10128
10129std::string
10130Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
10131 const TemplateArgument *Args,
10132 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000010133 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +000010134 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +000010135
Douglas Gregore62e6a02009-11-11 19:13:48 +000010136 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +000010137 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010138
Douglas Gregorbe999392009-09-15 16:23:51 +000010139 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +000010140 if (I >= NumArgs)
10141 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010142
Douglas Gregorbe999392009-09-15 16:23:51 +000010143 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +000010144 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +000010145 else
Douglas Gregor0192c232010-12-20 16:52:59 +000010146 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010147
Douglas Gregorbe999392009-09-15 16:23:51 +000010148 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +000010149 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +000010150 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +000010151 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +000010152 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010153
Douglas Gregor0192c232010-12-20 16:52:59 +000010154 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +000010155 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +000010156 }
Douglas Gregor0192c232010-12-20 16:52:59 +000010157
10158 Out << ']';
10159 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +000010160}
Francois Pichet1c229c02011-04-22 22:18:13 +000010161
Richard Smithe40f2ba2013-08-07 21:41:30 +000010162void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
10163 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +000010164 if (!FD)
10165 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +000010166
Justin Lebar28f09c52016-10-10 16:26:08 +000010167 auto LPT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +000010168
10169 // Take tokens to avoid allocations
10170 LPT->Toks.swap(Toks);
10171 LPT->D = FnD;
Justin Lebar28f09c52016-10-10 16:26:08 +000010172 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +000010173
10174 FD->setLateTemplateParsed(true);
10175}
10176
10177void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
10178 if (!FD)
10179 return;
10180 FD->setLateTemplateParsed(false);
10181}
Francois Pichet1c229c02011-04-22 22:18:13 +000010182
10183bool Sema::IsInsideALocalClassWithinATemplateFunction() {
10184 DeclContext *DC = CurContext;
10185
10186 while (DC) {
10187 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
10188 const FunctionDecl *FD = RD->isLocalClass();
10189 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
10190 } else if (DC->isTranslationUnit() || DC->isNamespace())
10191 return false;
10192
10193 DC = DC->getParent();
10194 }
10195 return false;
10196}
Richard Smith6739a102016-05-05 00:56:12 +000010197
Benjamin Kramera0a13c32016-08-06 11:21:04 +000010198namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010199/// Walk the path from which a declaration was instantiated, and check
Richard Smith6739a102016-05-05 00:56:12 +000010200/// that every explicit specialization along that path is visible. This enforces
10201/// C++ [temp.expl.spec]/6:
10202///
10203/// If a template, a member template or a member of a class template is
10204/// explicitly specialized then that specialization shall be declared before
10205/// the first use of that specialization that would cause an implicit
10206/// instantiation to take place, in every translation unit in which such a
10207/// use occurs; no diagnostic is required.
10208///
10209/// and also C++ [temp.class.spec]/1:
10210///
10211/// A partial specialization shall be declared before the first use of a
10212/// class template specialization that would make use of the partial
10213/// specialization as the result of an implicit or explicit instantiation
10214/// in every translation unit in which such a use occurs; no diagnostic is
10215/// required.
10216class ExplicitSpecializationVisibilityChecker {
10217 Sema &S;
10218 SourceLocation Loc;
10219 llvm::SmallVector<Module *, 8> Modules;
10220
10221public:
10222 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
10223 : S(S), Loc(Loc) {}
10224
10225 void check(NamedDecl *ND) {
10226 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10227 return checkImpl(FD);
10228 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
10229 return checkImpl(RD);
10230 if (auto *VD = dyn_cast<VarDecl>(ND))
10231 return checkImpl(VD);
10232 if (auto *ED = dyn_cast<EnumDecl>(ND))
10233 return checkImpl(ED);
10234 }
10235
10236private:
10237 void diagnose(NamedDecl *D, bool IsPartialSpec) {
10238 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
10239 : Sema::MissingImportKind::ExplicitSpecialization;
10240 const bool Recover = true;
10241
10242 // If we got a custom set of modules (because only a subset of the
10243 // declarations are interesting), use them, otherwise let
10244 // diagnoseMissingImport intelligently pick some.
10245 if (Modules.empty())
10246 S.diagnoseMissingImport(Loc, D, Kind, Recover);
10247 else
10248 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
10249 }
10250
10251 // Check a specific declaration. There are three problematic cases:
10252 //
10253 // 1) The declaration is an explicit specialization of a template
10254 // specialization.
10255 // 2) The declaration is an explicit specialization of a member of an
10256 // templated class.
10257 // 3) The declaration is an instantiation of a template, and that template
10258 // is an explicit specialization of a member of a templated class.
10259 //
10260 // We don't need to go any deeper than that, as the instantiation of the
10261 // surrounding class / etc is not triggered by whatever triggered this
10262 // instantiation, and thus should be checked elsewhere.
10263 template<typename SpecDecl>
10264 void checkImpl(SpecDecl *Spec) {
10265 bool IsHiddenExplicitSpecialization = false;
10266 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
10267 IsHiddenExplicitSpecialization =
10268 Spec->getMemberSpecializationInfo()
10269 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
Richard Smith54f04402017-05-18 02:29:20 +000010270 : !S.hasVisibleExplicitSpecialization(Spec, &Modules);
Richard Smith6739a102016-05-05 00:56:12 +000010271 } else {
10272 checkInstantiated(Spec);
10273 }
10274
10275 if (IsHiddenExplicitSpecialization)
10276 diagnose(Spec->getMostRecentDecl(), false);
10277 }
10278
10279 void checkInstantiated(FunctionDecl *FD) {
10280 if (auto *TD = FD->getPrimaryTemplate())
10281 checkTemplate(TD);
10282 }
10283
10284 void checkInstantiated(CXXRecordDecl *RD) {
10285 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
10286 if (!SD)
10287 return;
10288
10289 auto From = SD->getSpecializedTemplateOrPartial();
10290 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
10291 checkTemplate(TD);
10292 else if (auto *TD =
10293 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
10294 if (!S.hasVisibleDeclaration(TD))
10295 diagnose(TD, true);
10296 checkTemplate(TD);
10297 }
10298 }
10299
10300 void checkInstantiated(VarDecl *RD) {
10301 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
10302 if (!SD)
10303 return;
10304
10305 auto From = SD->getSpecializedTemplateOrPartial();
10306 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
10307 checkTemplate(TD);
10308 else if (auto *TD =
10309 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
10310 if (!S.hasVisibleDeclaration(TD))
10311 diagnose(TD, true);
10312 checkTemplate(TD);
10313 }
10314 }
10315
10316 void checkInstantiated(EnumDecl *FD) {}
10317
10318 template<typename TemplDecl>
10319 void checkTemplate(TemplDecl *TD) {
10320 if (TD->isMemberSpecialization()) {
10321 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
10322 diagnose(TD->getMostRecentDecl(), false);
10323 }
10324 }
10325};
Benjamin Kramera0a13c32016-08-06 11:21:04 +000010326} // end anonymous namespace
Richard Smith6739a102016-05-05 00:56:12 +000010327
10328void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
10329 if (!getLangOpts().Modules)
10330 return;
10331
10332 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
10333}
10334
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010335/// Check whether a template partial specialization that we've discovered
Richard Smith6739a102016-05-05 00:56:12 +000010336/// is hidden, and produce suitable diagnostics if so.
10337void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
10338 NamedDecl *Spec) {
10339 llvm::SmallVector<Module *, 8> Modules;
10340 if (!hasVisibleDeclaration(Spec, &Modules))
10341 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
10342 MissingImportKind::PartialSpecialization,
10343 /*Recover*/true);
10344}