blob: c58c446e52c6c0233b28d8f90856c0cbb555c7fe [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
Hans Wennborgd2b9fc82019-05-06 09:51:10 +00001159 if (DS.isExplicitSpecified())
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
Hans Wennborgd2b9fc82019-05-06 09:51:10 +00001839 return buildDeductionGuide(TemplateParams, CD->isExplicit(), NewTInfo,
1840 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
Hans Wennborgd2b9fc82019-05-06 09:51:10 +00001869 return buildDeductionGuide(Template->getTemplateParameters(), false, TSI,
1870 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,
Hans Wennborgd2b9fc82019-05-06 09:51:10 +00002020 bool Explicit, 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 =
Hans Wennborgd2b9fc82019-05-06 09:51:10 +00002029 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, Explicit,
2030 Name, 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) {
2055 DeclContext *DC = Template->getDeclContext();
2056 if (DC->isDependentContext())
2057 return;
2058
2059 ConvertConstructorToDeductionGuideTransform Transform(
2060 *this, cast<ClassTemplateDecl>(Template));
2061 if (!isCompleteType(Loc, Transform.DeducedType))
2062 return;
2063
2064 // Check whether we've already declared deduction guides for this template.
2065 // FIXME: Consider storing a flag on the template to indicate this.
2066 auto Existing = DC->lookup(Transform.DeductionGuideName);
2067 for (auto *D : Existing)
2068 if (D->isImplicit())
2069 return;
2070
2071 // In case we were expanding a pack when we attempted to declare deduction
2072 // guides, turn off pack expansion for everything we're about to do.
2073 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2074 // Create a template instantiation record to track the "instantiation" of
2075 // constructors into deduction guides.
2076 // FIXME: Add a kind for this to give more meaningful diagnostics. But can
2077 // this substitution process actually fail?
2078 InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
Volodymyr Sapsai2f649f32018-05-14 22:49:44 +00002079 if (BuildingDeductionGuides.isInvalid())
2080 return;
Richard Smith32918772017-02-14 00:25:28 +00002081
2082 // Convert declared constructors into deduction guide templates.
2083 // FIXME: Skip constructors for which deduction must necessarily fail (those
2084 // for which some class template parameter without a default argument never
2085 // appears in a deduced context).
2086 bool AddedAny = false;
Richard Smith32918772017-02-14 00:25:28 +00002087 for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
2088 D = D->getUnderlyingDecl();
2089 if (D->isInvalidDecl() || D->isImplicit())
2090 continue;
2091 D = cast<NamedDecl>(D->getCanonicalDecl());
2092
2093 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
Richard Smithbc491202017-02-17 20:05:37 +00002094 auto *CD =
2095 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
Richard Smith32918772017-02-14 00:25:28 +00002096 // Class-scope explicit specializations (MS extension) do not result in
2097 // deduction guides.
Richard Smithbc491202017-02-17 20:05:37 +00002098 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
Richard Smith32918772017-02-14 00:25:28 +00002099 continue;
2100
Richard Smithbc491202017-02-17 20:05:37 +00002101 Transform.transformConstructor(FTD, CD);
Richard Smith32918772017-02-14 00:25:28 +00002102 AddedAny = true;
Richard Smith32918772017-02-14 00:25:28 +00002103 }
2104
Faisal Vali81b756e2017-10-22 14:45:08 +00002105 // C++17 [over.match.class.deduct]
2106 // -- If C is not defined or does not declare any constructors, an
2107 // additional function template derived as above from a hypothetical
2108 // constructor C().
Richard Smith32918772017-02-14 00:25:28 +00002109 if (!AddedAny)
2110 Transform.buildSimpleDeductionGuide(None);
2111
Faisal Vali81b756e2017-10-22 14:45:08 +00002112 // -- An additional function template derived as above from a hypothetical
2113 // constructor C(C), called the copy deduction candidate.
2114 cast<CXXDeductionGuideDecl>(
2115 cast<FunctionTemplateDecl>(
2116 Transform.buildSimpleDeductionGuide(Transform.DeducedType))
2117 ->getTemplatedDecl())
2118 ->setIsCopyDeductionCandidate();
Richard Smith32918772017-02-14 00:25:28 +00002119}
2120
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002121/// Diagnose the presence of a default template argument on a
Douglas Gregored5731f2009-11-25 17:50:39 +00002122/// template parameter, which is ill-formed in certain contexts.
2123///
2124/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002125static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00002126 Sema::TemplateParamListContext TPC,
2127 SourceLocation ParamLoc,
2128 SourceRange DefArgRange) {
2129 switch (TPC) {
2130 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00002131 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00002132 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00002133 return false;
2134
2135 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00002136 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002137 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00002138 // A default template-argument shall not be specified in a
2139 // function template declaration or a function template
2140 // definition [...]
Simon Pilgrim6905d222016-12-30 22:55:33 +00002141 // If a friend function template declaration specifies a default
Douglas Gregora99fb4c2011-02-04 04:20:44 +00002142 // template-argument, that declaration shall be a definition and shall be
2143 // the only declaration of the function template in the translation unit.
2144 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002145 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002146 diag::warn_cxx98_compat_template_parameter_default_in_function_template
2147 : diag::ext_template_parameter_default_in_function_template)
2148 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00002149 return false;
2150
2151 case Sema::TPC_ClassTemplateMember:
2152 // C++0x [temp.param]p9:
2153 // A default template-argument shall not be specified in the
2154 // template-parameter-lists of the definition of a member of a
2155 // class template that appears outside of the member's class.
2156 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2157 << DefArgRange;
2158 return true;
2159
David Majnemerba8f17a2013-06-25 22:08:55 +00002160 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00002161 case Sema::TPC_FriendFunctionTemplate:
2162 // C++ [temp.param]p9:
2163 // A default template-argument shall not be specified in a
2164 // friend template declaration.
2165 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2166 << DefArgRange;
2167 return true;
2168
2169 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2170 // for friend function templates if there is only a single
2171 // declaration (and it is a definition). Strange!
2172 }
2173
David Blaikie8a40f702012-01-17 06:56:22 +00002174 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00002175}
2176
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002177/// Check for unexpanded parameter packs within the template parameters
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002178/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00002179static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2180 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00002181 // A template template parameter which is a parameter pack is also a pack
2182 // expansion.
2183 if (TTP->isParameterPack())
2184 return false;
2185
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002186 TemplateParameterList *Params = TTP->getTemplateParameters();
2187 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2188 NamedDecl *P = Params->getParam(I);
2189 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00002190 if (!NTTP->isParameterPack() &&
2191 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002192 NTTP->getTypeSourceInfo(),
2193 Sema::UPPC_NonTypeTemplateParameterType))
2194 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002195
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002196 continue;
2197 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002198
2199 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002200 = dyn_cast<TemplateTemplateParmDecl>(P))
2201 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2202 return true;
2203 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002204
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002205 return false;
2206}
2207
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002208/// Checks the validity of a template parameter list, possibly
Douglas Gregordba32632009-02-10 19:49:53 +00002209/// considering the template parameter list from a previous
2210/// declaration.
2211///
2212/// If an "old" template parameter list is provided, it must be
2213/// equivalent (per TemplateParameterListsAreEqual) to the "new"
2214/// template parameter list.
2215///
2216/// \param NewParams Template parameter list for a new template
2217/// declaration. This template parameter list will be updated with any
2218/// default arguments that are carried through from the previous
2219/// template parameter list.
2220///
2221/// \param OldParams If provided, template parameter list from a
2222/// previous declaration of the same template. Default template
2223/// arguments will be merged from the old template parameter list to
2224/// the new template parameter list.
2225///
Douglas Gregored5731f2009-11-25 17:50:39 +00002226/// \param TPC Describes the context in which we are checking the given
2227/// template parameter list.
2228///
Richard Smithc4577662018-09-12 02:13:47 +00002229/// \param SkipBody If we might have already made a prior merged definition
2230/// of this template visible, the corresponding body-skipping information.
2231/// Default argument redefinition is not an error when skipping such a body,
2232/// because (under the ODR) we can assume the default arguments are the same
2233/// as the prior merged definition.
2234///
Douglas Gregordba32632009-02-10 19:49:53 +00002235/// \returns true if an error occurred, false otherwise.
2236bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00002237 TemplateParameterList *OldParams,
Richard Smithc4577662018-09-12 02:13:47 +00002238 TemplateParamListContext TPC,
2239 SkipBodyInfo *SkipBody) {
Douglas Gregordba32632009-02-10 19:49:53 +00002240 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00002241
Douglas Gregordba32632009-02-10 19:49:53 +00002242 // C++ [temp.param]p10:
2243 // The set of default template-arguments available for use with a
2244 // template declaration or definition is obtained by merging the
2245 // default arguments from the definition (if in scope) and all
2246 // declarations in scope in the same way default function
2247 // arguments are (8.3.6).
2248 bool SawDefaultArgument = false;
2249 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00002250
Mike Stumpc89c8e32009-02-11 23:03:27 +00002251 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00002252 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00002253 if (OldParams)
2254 OldParam = OldParams->begin();
2255
Douglas Gregor0693def2011-01-27 01:40:17 +00002256 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00002257 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2258 NewParamEnd = NewParams->end();
2259 NewParam != NewParamEnd; ++NewParam) {
2260 // Variables used to diagnose redundant default arguments
2261 bool RedundantDefaultArg = false;
2262 SourceLocation OldDefaultLoc;
2263 SourceLocation NewDefaultLoc;
2264
David Blaikie651c73c2011-10-19 05:19:50 +00002265 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00002266 bool MissingDefaultArg = false;
2267
David Blaikie651c73c2011-10-19 05:19:50 +00002268 // Variable used to diagnose non-final parameter packs
2269 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00002270
Douglas Gregordba32632009-02-10 19:49:53 +00002271 if (TemplateTypeParmDecl *NewTypeParm
2272 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00002273 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002274 if (NewTypeParm->hasDefaultArgument() &&
2275 DiagnoseDefaultTemplateArgument(*this, TPC,
2276 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002277 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002278 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00002279 NewTypeParm->removeDefaultArgument();
2280
2281 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00002282 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002283 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Anders Carlsson327865d2009-06-12 23:20:15 +00002284 if (NewTypeParm->isParameterPack()) {
2285 assert(!NewTypeParm->hasDefaultArgument() &&
2286 "Parameter packs can't have a default argument!");
2287 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002288 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
Richard Smithc4577662018-09-12 02:13:47 +00002289 NewTypeParm->hasDefaultArgument() &&
2290 (!SkipBody || !SkipBody->ShouldSkip)) {
Douglas Gregordba32632009-02-10 19:49:53 +00002291 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2292 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2293 SawDefaultArgument = true;
2294 RedundantDefaultArg = true;
2295 PreviousDefaultArgLoc = NewDefaultLoc;
2296 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2297 // Merge the default argument from the old declaration to the
2298 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002299 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00002300 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2301 } else if (NewTypeParm->hasDefaultArgument()) {
2302 SawDefaultArgument = true;
2303 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2304 } else if (SawDefaultArgument)
2305 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00002306 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00002307 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002308 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002309 if (!NewNonTypeParm->isParameterPack() &&
2310 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002311 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002312 UPPC_NonTypeTemplateParameterType)) {
2313 Invalid = true;
2314 continue;
2315 }
2316
Douglas Gregored5731f2009-11-25 17:50:39 +00002317 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002318 if (NewNonTypeParm->hasDefaultArgument() &&
2319 DiagnoseDefaultTemplateArgument(*this, TPC,
2320 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002321 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00002322 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00002323 }
2324
Mike Stump12b8ce12009-08-04 21:02:39 +00002325 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00002326 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002327 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00002328 if (NewNonTypeParm->isParameterPack()) {
2329 assert(!NewNonTypeParm->hasDefaultArgument() &&
2330 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00002331 if (!NewNonTypeParm->isPackExpansion())
2332 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002333 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
Richard Smithc4577662018-09-12 02:13:47 +00002334 NewNonTypeParm->hasDefaultArgument() &&
2335 (!SkipBody || !SkipBody->ShouldSkip)) {
Douglas Gregordba32632009-02-10 19:49:53 +00002336 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2337 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2338 SawDefaultArgument = true;
2339 RedundantDefaultArg = true;
2340 PreviousDefaultArgLoc = NewDefaultLoc;
2341 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2342 // Merge the default argument from the old declaration to the
2343 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002344 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00002345 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2346 } else if (NewNonTypeParm->hasDefaultArgument()) {
2347 SawDefaultArgument = true;
2348 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2349 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002350 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00002351 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00002352 TemplateTemplateParmDecl *NewTemplateParm
2353 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002354
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002355 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00002356 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00002357 Invalid = true;
2358 continue;
2359 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002360
David Blaikie651c73c2011-10-19 05:19:50 +00002361 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002362 if (NewTemplateParm->hasDefaultArgument() &&
2363 DiagnoseDefaultTemplateArgument(*this, TPC,
2364 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00002365 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00002366 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00002367
2368 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00002369 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00002370 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00002371 if (NewTemplateParm->isParameterPack()) {
2372 assert(!NewTemplateParm->hasDefaultArgument() &&
2373 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00002374 if (!NewTemplateParm->isPackExpansion())
2375 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00002376 } else if (OldTemplateParm &&
2377 hasVisibleDefaultArgument(OldTemplateParm) &&
Richard Smithc4577662018-09-12 02:13:47 +00002378 NewTemplateParm->hasDefaultArgument() &&
2379 (!SkipBody || !SkipBody->ShouldSkip)) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002380 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2381 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002382 SawDefaultArgument = true;
2383 RedundantDefaultArg = true;
2384 PreviousDefaultArgLoc = NewDefaultLoc;
2385 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2386 // Merge the default argument from the old declaration to the
2387 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00002388 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002389 PreviousDefaultArgLoc
2390 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002391 } else if (NewTemplateParm->hasDefaultArgument()) {
2392 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002393 PreviousDefaultArgLoc
2394 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00002395 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002396 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00002397 }
2398
Richard Smith1fde8ec2012-09-07 02:06:42 +00002399 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00002400 // If a template parameter of a primary class template or alias template
2401 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002402 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00002403 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2404 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00002405 Diag((*NewParam)->getLocation(),
2406 diag::err_template_param_pack_must_be_last_template_parameter);
2407 Invalid = true;
2408 }
2409
Douglas Gregordba32632009-02-10 19:49:53 +00002410 if (RedundantDefaultArg) {
2411 // C++ [temp.param]p12:
2412 // A template-parameter shall not be given default arguments
2413 // by two different declarations in the same scope.
2414 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2415 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2416 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00002417 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00002418 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002419 // If a template-parameter of a class template has a default
2420 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00002421 // have a default template-argument supplied or be a template parameter
2422 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00002423 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00002424 diag::err_template_param_default_arg_missing);
2425 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2426 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00002427 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00002428 }
2429
2430 // If we have an old template parameter list that we're merging
2431 // in, move on to the next parameter.
2432 if (OldParams)
2433 ++OldParam;
2434 }
2435
Douglas Gregor0693def2011-01-27 01:40:17 +00002436 // We were missing some default arguments at the end of the list, so remove
2437 // all of the default arguments.
2438 if (RemoveDefaultArguments) {
2439 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2440 NewParamEnd = NewParams->end();
2441 NewParam != NewParamEnd; ++NewParam) {
2442 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2443 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002444 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00002445 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2446 NTTP->removeDefaultArgument();
2447 else
2448 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2449 }
2450 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002451
Douglas Gregordba32632009-02-10 19:49:53 +00002452 return Invalid;
2453}
Douglas Gregord32e0282009-02-09 23:23:08 +00002454
John McCalla020a012010-10-20 05:44:58 +00002455namespace {
2456
2457/// A class which looks for a use of a certain level of template
2458/// parameter.
2459struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2460 typedef RecursiveASTVisitor<DependencyChecker> super;
2461
2462 unsigned Depth;
Richard Smith57aae072016-12-28 02:37:25 +00002463
2464 // Whether we're looking for a use of a template parameter that makes the
2465 // overall construct type-dependent / a dependent type. This is strictly
2466 // best-effort for now; we may fail to match at all for a dependent type
2467 // in some cases if this is set.
2468 bool IgnoreNonTypeDependent;
2469
John McCalla020a012010-10-20 05:44:58 +00002470 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00002471 SourceLocation MatchLoc;
2472
Richard Smith13894182017-04-13 21:37:24 +00002473 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2474 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2475 Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00002476
Richard Smith57aae072016-12-28 02:37:25 +00002477 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
Richard Smith13894182017-04-13 21:37:24 +00002478 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2479 NamedDecl *ND = Params->getParam(0);
2480 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2481 Depth = PD->getDepth();
2482 } else if (NonTypeTemplateParmDecl *PD =
2483 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2484 Depth = PD->getDepth();
2485 } else {
2486 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2487 }
2488 }
John McCalla020a012010-10-20 05:44:58 +00002489
Richard Smith6056d5e2014-02-09 00:54:43 +00002490 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
Richard Smith13894182017-04-13 21:37:24 +00002491 if (ParmDepth >= Depth) {
John McCalla020a012010-10-20 05:44:58 +00002492 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00002493 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00002494 return true;
2495 }
2496 return false;
2497 }
2498
Richard Smith57aae072016-12-28 02:37:25 +00002499 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2500 // Prune out non-type-dependent expressions if requested. This can
2501 // sometimes result in us failing to find a template parameter reference
2502 // (if a value-dependent expression creates a dependent type), but this
2503 // mode is best-effort only.
2504 if (auto *E = dyn_cast_or_null<Expr>(S))
2505 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2506 return true;
2507 return super::TraverseStmt(S, Q);
2508 }
2509
2510 bool TraverseTypeLoc(TypeLoc TL) {
2511 if (IgnoreNonTypeDependent && !TL.isNull() &&
2512 !TL.getType()->isDependentType())
2513 return true;
2514 return super::TraverseTypeLoc(TL);
2515 }
2516
Richard Smith6056d5e2014-02-09 00:54:43 +00002517 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2518 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2519 }
2520
John McCalla020a012010-10-20 05:44:58 +00002521 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
Richard Smith57aae072016-12-28 02:37:25 +00002522 // For a best-effort search, keep looking until we find a location.
2523 return IgnoreNonTypeDependent || !Matches(T->getDepth());
John McCalla020a012010-10-20 05:44:58 +00002524 }
2525
2526 bool TraverseTemplateName(TemplateName N) {
2527 if (TemplateTemplateParmDecl *PD =
2528 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00002529 if (Matches(PD->getDepth()))
2530 return false;
John McCalla020a012010-10-20 05:44:58 +00002531 return super::TraverseTemplateName(N);
2532 }
2533
2534 bool VisitDeclRefExpr(DeclRefExpr *E) {
2535 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00002536 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2537 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00002538 return false;
John McCalla020a012010-10-20 05:44:58 +00002539 return super::VisitDeclRefExpr(E);
2540 }
Richard Smith6056d5e2014-02-09 00:54:43 +00002541
2542 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2543 return TraverseType(T->getReplacementType());
2544 }
2545
2546 bool
2547 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2548 return TraverseTemplateArgument(T->getArgumentPack());
2549 }
2550
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00002551 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2552 return TraverseType(T->getInjectedSpecializationType());
2553 }
John McCalla020a012010-10-20 05:44:58 +00002554};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002555} // end anonymous namespace
John McCalla020a012010-10-20 05:44:58 +00002556
Douglas Gregor972fe532011-05-10 18:27:06 +00002557/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00002558/// list.
2559static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00002560DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
Richard Smith57aae072016-12-28 02:37:25 +00002561 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
Douglas Gregor972fe532011-05-10 18:27:06 +00002562 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00002563 return Checker.Match;
2564}
2565
Douglas Gregor972fe532011-05-10 18:27:06 +00002566// Find the source range corresponding to the named type in the given
2567// nested-name-specifier, if any.
2568static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2569 QualType T,
2570 const CXXScopeSpec &SS) {
2571 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2572 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2573 if (const Type *CurType = NNS->getAsType()) {
2574 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2575 return NNSLoc.getTypeLoc().getSourceRange();
2576 } else
2577 break;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002578
Douglas Gregor972fe532011-05-10 18:27:06 +00002579 NNSLoc = NNSLoc.getPrefix();
2580 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002581
Douglas Gregor972fe532011-05-10 18:27:06 +00002582 return SourceRange();
2583}
2584
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002585/// Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00002586/// specifier, returning the template parameter list that applies to the
2587/// name.
2588///
2589/// \param DeclStartLoc the start of the declaration that has a scope
2590/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00002591///
Douglas Gregor972fe532011-05-10 18:27:06 +00002592/// \param DeclLoc The location of the declaration itself.
2593///
Douglas Gregord8d297c2009-07-21 23:53:31 +00002594/// \param SS the scope specifier that will be matched to the given template
2595/// parameter lists. This scope specifier precedes a qualified name that is
2596/// being declared.
2597///
Richard Smith4b55a9c2014-04-17 03:29:33 +00002598/// \param TemplateId The template-id following the scope specifier, if there
2599/// is one. Used to check for a missing 'template<>'.
2600///
Douglas Gregord8d297c2009-07-21 23:53:31 +00002601/// \param ParamLists the template parameter lists, from the outermost to the
2602/// innermost template parameter lists.
2603///
John McCalle820e5e2010-04-13 20:37:33 +00002604/// \param IsFriend Whether to apply the slightly different rules for
2605/// matching template parameters to scope specifiers in friend
2606/// declarations.
2607///
Richard Smithf445f192017-02-09 21:04:43 +00002608/// \param IsMemberSpecialization will be set true if the scope specifier
2609/// denotes a fully-specialized type, and therefore this is a declaration of
2610/// a member specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002611///
Mike Stump11289f42009-09-09 15:08:12 +00002612/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00002613/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00002614/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00002615/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00002616/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00002617/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002618TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2619 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00002620 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002621 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
Richard Smithf445f192017-02-09 21:04:43 +00002622 bool &IsMemberSpecialization, bool &Invalid) {
2623 IsMemberSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00002624 Invalid = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002625
Douglas Gregor972fe532011-05-10 18:27:06 +00002626 // The sequence of nested types to which we will match up the template
2627 // parameter lists. We first build this list by starting with the type named
2628 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002629 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00002630 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00002631 if (SS.getScopeRep()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002632 if (CXXRecordDecl *Record
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00002633 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2634 T = Context.getTypeDeclType(Record);
2635 else
2636 T = QualType(SS.getScopeRep()->getAsType(), 0);
2637 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002638
Douglas Gregor972fe532011-05-10 18:27:06 +00002639 // If we found an explicit specialization that prevents us from needing
2640 // 'template<>' headers, this will be set to the location of that
2641 // explicit specialization.
2642 SourceLocation ExplicitSpecLoc;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002643
Douglas Gregor972fe532011-05-10 18:27:06 +00002644 while (!T.isNull()) {
2645 NestedTypes.push_back(T);
Simon Pilgrim6905d222016-12-30 22:55:33 +00002646
Douglas Gregor972fe532011-05-10 18:27:06 +00002647 // Retrieve the parent of a record type.
2648 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2649 // If this type is an explicit specialization, we're done.
2650 if (ClassTemplateSpecializationDecl *Spec
2651 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002652 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002653 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2654 ExplicitSpecLoc = Spec->getLocation();
2655 break;
Douglas Gregor65911492009-11-23 12:11:45 +00002656 }
Douglas Gregor972fe532011-05-10 18:27:06 +00002657 } else if (Record->getTemplateSpecializationKind()
2658 == TSK_ExplicitSpecialization) {
2659 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00002660 break;
2661 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002662
Douglas Gregor972fe532011-05-10 18:27:06 +00002663 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2664 T = Context.getTypeDeclType(Parent);
2665 else
2666 T = QualType();
2667 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002668 }
2669
Douglas Gregor972fe532011-05-10 18:27:06 +00002670 if (const TemplateSpecializationType *TST
2671 = T->getAs<TemplateSpecializationType>()) {
2672 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2673 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2674 T = Context.getTypeDeclType(Parent);
2675 else
2676 T = QualType();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002677 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002678 }
Douglas Gregor972fe532011-05-10 18:27:06 +00002679 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002680
Douglas Gregor972fe532011-05-10 18:27:06 +00002681 // Look one step prior in a dependent template specialization type.
2682 if (const DependentTemplateSpecializationType *DependentTST
2683 = T->getAs<DependentTemplateSpecializationType>()) {
2684 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2685 T = QualType(NNS->getAsType(), 0);
2686 else
2687 T = QualType();
2688 continue;
2689 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002690
Douglas Gregor972fe532011-05-10 18:27:06 +00002691 // Look one step prior in a dependent name type.
2692 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2693 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2694 T = QualType(NNS->getAsType(), 0);
2695 else
2696 T = QualType();
2697 continue;
2698 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002699
Douglas Gregor972fe532011-05-10 18:27:06 +00002700 // Retrieve the parent of an enumeration type.
2701 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2702 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2703 // check here.
2704 EnumDecl *Enum = EnumT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002705
Douglas Gregor972fe532011-05-10 18:27:06 +00002706 // Get to the parent type.
2707 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2708 T = Context.getTypeDeclType(Parent);
2709 else
Simon Pilgrim6905d222016-12-30 22:55:33 +00002710 T = QualType();
Douglas Gregor972fe532011-05-10 18:27:06 +00002711 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002712 }
Mike Stump11289f42009-09-09 15:08:12 +00002713
Douglas Gregor972fe532011-05-10 18:27:06 +00002714 T = QualType();
2715 }
2716 // Reverse the nested types list, since we want to traverse from the outermost
2717 // to the innermost while checking template-parameter-lists.
2718 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00002719
Douglas Gregor972fe532011-05-10 18:27:06 +00002720 // C++0x [temp.expl.spec]p17:
2721 // A member or a member template may be nested within many
2722 // enclosing class templates. In an explicit specialization for
2723 // such a member, the member declaration shall be preceded by a
2724 // template<> for each enclosing class template that is
2725 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002726 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00002727
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002728 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00002729 if (SawNonEmptyTemplateParameterList) {
2730 Diag(DeclLoc, diag::err_specialize_member_of_template)
2731 << !Recovery << Range;
2732 Invalid = true;
Richard Smithf445f192017-02-09 21:04:43 +00002733 IsMemberSpecialization = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00002734 return true;
2735 }
2736
2737 return false;
2738 };
2739
2740 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2741 // Check that we can have an explicit specialization here.
2742 if (CheckExplicitSpecialization(Range, true))
2743 return true;
2744
2745 // We don't have a template header, but we should.
2746 SourceLocation ExpectedTemplateLoc;
2747 if (!ParamLists.empty())
2748 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2749 else
2750 ExpectedTemplateLoc = DeclStartLoc;
2751
2752 Diag(DeclLoc, diag::err_template_spec_needs_header)
2753 << Range
2754 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2755 return false;
2756 };
2757
Douglas Gregor972fe532011-05-10 18:27:06 +00002758 unsigned ParamIdx = 0;
2759 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2760 ++TypeIdx) {
2761 T = NestedTypes[TypeIdx];
Simon Pilgrim6905d222016-12-30 22:55:33 +00002762
Douglas Gregor972fe532011-05-10 18:27:06 +00002763 // Whether we expect a 'template<>' header.
2764 bool NeedEmptyTemplateHeader = false;
2765
2766 // Whether we expect a template header with parameters.
2767 bool NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002768
Douglas Gregor972fe532011-05-10 18:27:06 +00002769 // For a dependent type, the set of template parameters that we
2770 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00002771 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002772
Douglas Gregor373af9b2011-05-11 23:26:17 +00002773 // C++0x [temp.expl.spec]p15:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002774 // A member or a member template may be nested within many enclosing
2775 // class templates. In an explicit specialization for such a member, the
2776 // member declaration shall be preceded by a template<> for each
Douglas Gregor373af9b2011-05-11 23:26:17 +00002777 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00002778 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2779 if (ClassTemplatePartialSpecializationDecl *Partial
2780 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2781 ExpectedTemplateParams = Partial->getTemplateParameters();
2782 NeedNonemptyTemplateHeader = true;
2783 } else if (Record->isDependentType()) {
2784 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00002785 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00002786 ->getTemplateParameters();
2787 NeedNonemptyTemplateHeader = true;
2788 }
2789 } else if (ClassTemplateSpecializationDecl *Spec
2790 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2791 // C++0x [temp.expl.spec]p4:
2792 // Members of an explicitly specialized class template are defined
Simon Pilgrim6905d222016-12-30 22:55:33 +00002793 // in the same manner as members of normal classes, and not using
2794 // the template<> syntax.
Douglas Gregor972fe532011-05-10 18:27:06 +00002795 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2796 NeedEmptyTemplateHeader = true;
2797 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00002798 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002799 } else if (Record->getTemplateSpecializationKind()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002800 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00002801 != TSK_ExplicitSpecialization &&
2802 TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002803 IsMemberSpecialization = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002804
Douglas Gregor373af9b2011-05-11 23:26:17 +00002805 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002806 }
2807 } else if (const TemplateSpecializationType *TST
2808 = T->getAs<TemplateSpecializationType>()) {
Nico Weber28900612015-01-30 02:35:21 +00002809 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002810 ExpectedTemplateParams = Template->getTemplateParameters();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002811 NeedNonemptyTemplateHeader = true;
Douglas Gregor972fe532011-05-10 18:27:06 +00002812 }
2813 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2814 // FIXME: We actually could/should check the template arguments here
2815 // against the corresponding template parameter list.
2816 NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002817 }
2818
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002819 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002820 // In an explicit specialization declaration for a member of a class
2821 // template or a member template that ap- pears in namespace scope, the
2822 // member template and some of its enclosing class templates may remain
2823 // unspecialized, except that the declaration shall not explicitly
2824 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002825 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002826 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002827 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002828 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2829 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002830 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002831 } else
2832 SawNonEmptyTemplateParameterList = true;
2833 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002834
Douglas Gregor972fe532011-05-10 18:27:06 +00002835 if (NeedEmptyTemplateHeader) {
2836 // If we're on the last of the types, and we need a 'template<>' header
Richard Smithf445f192017-02-09 21:04:43 +00002837 // here, then it's a member specialization.
Douglas Gregor972fe532011-05-10 18:27:06 +00002838 if (TypeIdx == NumTypes - 1)
Richard Smithf445f192017-02-09 21:04:43 +00002839 IsMemberSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002840
2841 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002842 if (ParamLists[ParamIdx]->size() > 0) {
2843 // The header has template parameters when it shouldn't. Complain.
Simon Pilgrim6905d222016-12-30 22:55:33 +00002844 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregor972fe532011-05-10 18:27:06 +00002845 diag::err_template_param_list_matches_nontemplate)
2846 << T
2847 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2848 ParamLists[ParamIdx]->getRAngleLoc())
2849 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2850 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002851 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002852 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002853
Douglas Gregor972fe532011-05-10 18:27:06 +00002854 // Consume this template header.
2855 ++ParamIdx;
2856 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002857 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002858
2859 if (!IsFriend)
2860 if (DiagnoseMissingExplicitSpecialization(
2861 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00002862 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002863
Douglas Gregor972fe532011-05-10 18:27:06 +00002864 continue;
2865 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002866
Douglas Gregor972fe532011-05-10 18:27:06 +00002867 if (NeedNonemptyTemplateHeader) {
2868 // In friend declarations we can have template-ids which don't
2869 // depend on the corresponding template parameter lists. But
2870 // assume that empty parameter lists are supposed to match this
2871 // template-id.
2872 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002873 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002874 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00002875 ExpectedTemplateParams = nullptr;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002876 else
Douglas Gregor972fe532011-05-10 18:27:06 +00002877 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002878 }
Douglas Gregored5731f2009-11-25 17:50:39 +00002879
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002880 if (ParamIdx < ParamLists.size()) {
2881 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00002882 if (ExpectedTemplateParams &&
2883 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2884 ExpectedTemplateParams,
2885 true, TPL_TemplateMatch))
2886 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002887
Douglas Gregor972fe532011-05-10 18:27:06 +00002888 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00002889 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00002890 TPC_ClassTemplateMember))
2891 Invalid = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002892
Douglas Gregor972fe532011-05-10 18:27:06 +00002893 ++ParamIdx;
2894 continue;
2895 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002896
Douglas Gregor972fe532011-05-10 18:27:06 +00002897 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2898 << T
2899 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2900 Invalid = true;
2901 continue;
2902 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00002903 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00002904
Douglas Gregord8d297c2009-07-21 23:53:31 +00002905 // If there were at least as many template-ids as there were template
2906 // parameter lists, then there are no template parameter lists remaining for
2907 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00002908 if (ParamIdx >= ParamLists.size()) {
2909 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00002910 // We don't have a template header for the declaration itself, but we
2911 // should.
Richard Smith11a80dc2014-04-17 03:52:20 +00002912 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2913 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00002914
2915 // Fabricate an empty template parameter list for the invented header.
2916 return TemplateParameterList::Create(Context, SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +00002917 SourceLocation(), None,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00002918 SourceLocation(), nullptr);
Richard Smith4b55a9c2014-04-17 03:29:33 +00002919 }
2920
Craig Topperc3ec1492014-05-26 06:22:03 +00002921 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002922 }
Mike Stump11289f42009-09-09 15:08:12 +00002923
Douglas Gregord8d297c2009-07-21 23:53:31 +00002924 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002925 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002926 bool HasAnyExplicitSpecHeader = false;
2927 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002928 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002929 if (ParamLists[I]->size() == 0)
2930 HasAnyExplicitSpecHeader = true;
2931 else
2932 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002933 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002934
Douglas Gregor972fe532011-05-10 18:27:06 +00002935 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002936 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2937 : diag::err_template_spec_extra_headers)
2938 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2939 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00002940
2941 // If there was a specialization somewhere, such that 'template<>' is
2942 // not required, and there were any 'template<>' headers, note where the
2943 // specialization occurred.
2944 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
Simon Pilgrim6905d222016-12-30 22:55:33 +00002945 Diag(ExplicitSpecLoc,
Douglas Gregor972fe532011-05-10 18:27:06 +00002946 diag::note_explicit_template_spec_does_not_need_header)
2947 << NestedTypes.back();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002948
Douglas Gregor972fe532011-05-10 18:27:06 +00002949 // We have a template parameter list with no corresponding scope, which
2950 // means that the resulting template declaration can't be instantiated
2951 // properly (we'll end up with dependent nodes when we shouldn't).
2952 if (!AllExplicitSpecHeaders)
2953 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002954 }
Mike Stump11289f42009-09-09 15:08:12 +00002955
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002956 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002957 // In an explicit specialization declaration for a member of a class
2958 // template or a member template that ap- pears in namespace scope, the
2959 // member template and some of its enclosing class templates may remain
2960 // unspecialized, except that the declaration shall not explicitly
2961 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002962 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00002963 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002964 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2965 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002966 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002967
Douglas Gregord8d297c2009-07-21 23:53:31 +00002968 // Return the last template parameter list, which corresponds to the
2969 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002970 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00002971}
2972
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002973void Sema::NoteAllFoundTemplates(TemplateName Name) {
2974 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2975 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002976 << (isa<FunctionTemplateDecl>(Template)
2977 ? 0
2978 : isa<ClassTemplateDecl>(Template)
2979 ? 1
2980 : isa<VarTemplateDecl>(Template)
2981 ? 2
2982 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2983 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002984 return;
2985 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002986
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002987 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002988 for (OverloadedTemplateStorage::iterator I = OST->begin(),
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002989 IEnd = OST->end();
2990 I != IEnd; ++I)
2991 Diag((*I)->getLocation(), diag::note_template_declared_here)
2992 << 0 << (*I)->getDeclName();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002993
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002994 return;
2995 }
2996}
2997
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002998static QualType
2999checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
3000 const SmallVectorImpl<TemplateArgument> &Converted,
3001 SourceLocation TemplateLoc,
3002 TemplateArgumentListInfo &TemplateArgs) {
3003 ASTContext &Context = SemaRef.getASTContext();
3004 switch (BTD->getBuiltinTemplateKind()) {
Eric Fiselier6ad68552016-07-01 01:24:09 +00003005 case BTK__make_integer_seq: {
David Majnemerd9b1a4f2015-11-04 03:40:30 +00003006 // Specializations of __make_integer_seq<S, T, N> are treated like
3007 // S<T, 0, ..., N-1>.
3008
3009 // C++14 [inteseq.intseq]p1:
3010 // T shall be an integer type.
3011 if (!Converted[1].getAsType()->isIntegralType(Context)) {
3012 SemaRef.Diag(TemplateArgs[1].getLocation(),
3013 diag::err_integer_sequence_integral_element_type);
3014 return QualType();
3015 }
3016
3017 // C++14 [inteseq.make]p1:
3018 // If N is negative the program is ill-formed.
3019 TemplateArgument NumArgsArg = Converted[2];
3020 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
3021 if (NumArgs < 0) {
3022 SemaRef.Diag(TemplateArgs[2].getLocation(),
3023 diag::err_integer_sequence_negative_length);
3024 return QualType();
3025 }
3026
3027 QualType ArgTy = NumArgsArg.getIntegralType();
3028 TemplateArgumentListInfo SyntheticTemplateArgs;
3029 // The type argument gets reused as the first template argument in the
3030 // synthetic template argument list.
3031 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
3032 // Expand N into 0 ... N-1.
3033 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3034 I < NumArgs; ++I) {
3035 TemplateArgument TA(Context, I, ArgTy);
Richard Smith7873de02016-08-11 22:25:46 +00003036 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3037 TA, ArgTy, TemplateArgs[2].getLocation()));
David Majnemerd9b1a4f2015-11-04 03:40:30 +00003038 }
3039 // The first template argument will be reused as the template decl that
3040 // our synthetic template arguments will be applied to.
3041 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
3042 TemplateLoc, SyntheticTemplateArgs);
3043 }
Eric Fiselier6ad68552016-07-01 01:24:09 +00003044
3045 case BTK__type_pack_element:
3046 // Specializations of
3047 // __type_pack_element<Index, T_1, ..., T_N>
3048 // are treated like T_Index.
3049 assert(Converted.size() == 2 &&
3050 "__type_pack_element should be given an index and a parameter pack");
3051
3052 // If the Index is out of bounds, the program is ill-formed.
3053 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3054 llvm::APSInt Index = IndexArg.getAsIntegral();
3055 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3056 "type std::size_t, and hence be non-negative");
3057 if (Index >= Ts.pack_size()) {
3058 SemaRef.Diag(TemplateArgs[0].getLocation(),
3059 diag::err_type_pack_element_out_of_bounds);
3060 return QualType();
3061 }
3062
3063 // We simply return the type at index `Index`.
3064 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
3065 return Nth->getAsType();
3066 }
David Majnemerd9b1a4f2015-11-04 03:40:30 +00003067 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3068}
3069
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003070/// Determine whether this alias template is "enable_if_t".
3071static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3072 return AliasTemplate->getName().equals("enable_if_t");
3073}
3074
3075/// Collect all of the separable terms in the given condition, which
3076/// might be a conjunction.
3077///
3078/// FIXME: The right answer is to convert the logical expression into
3079/// disjunctive normal form, so we can find the first failed term
3080/// within each possible clause.
3081static void collectConjunctionTerms(Expr *Clause,
3082 SmallVectorImpl<Expr *> &Terms) {
3083 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3084 if (BinOp->getOpcode() == BO_LAnd) {
3085 collectConjunctionTerms(BinOp->getLHS(), Terms);
3086 collectConjunctionTerms(BinOp->getRHS(), Terms);
3087 }
3088
3089 return;
3090 }
3091
3092 Terms.push_back(Clause);
3093}
3094
Douglas Gregorbb33f572017-07-05 20:20:15 +00003095// The ranges-v3 library uses an odd pattern of a top-level "||" with
3096// a left-hand side that is value-dependent but never true. Identify
3097// the idiom and ignore that term.
3098static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3099 // Top-level '||'.
3100 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3101 if (!BinOp) return Cond;
3102
3103 if (BinOp->getOpcode() != BO_LOr) return Cond;
3104
3105 // With an inner '==' that has a literal on the right-hand side.
3106 Expr *LHS = BinOp->getLHS();
Douglas Gregorc0fe1f22017-07-05 21:12:37 +00003107 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
Douglas Gregorbb33f572017-07-05 20:20:15 +00003108 if (!InnerBinOp) return Cond;
3109
3110 if (InnerBinOp->getOpcode() != BO_EQ ||
3111 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3112 return Cond;
3113
3114 // If the inner binary operation came from a macro expansion named
3115 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3116 // of the '||', which is the real, user-provided condition.
Douglas Gregorc0fe1f22017-07-05 21:12:37 +00003117 SourceLocation Loc = InnerBinOp->getExprLoc();
Douglas Gregorbb33f572017-07-05 20:20:15 +00003118 if (!Loc.isMacroID()) return Cond;
3119
3120 StringRef MacroName = PP.getImmediateMacroName(Loc);
3121 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3122 return BinOp->getRHS();
3123
3124 return Cond;
3125}
3126
Clement Courbetf44c6f42018-12-11 08:39:11 +00003127namespace {
3128
3129// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3130// within failing boolean expression, such as substituting template parameters
3131// for actual types.
3132class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3133public:
3134 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3135 : Policy(P) {}
3136
3137 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3138 const auto *DR = dyn_cast<DeclRefExpr>(E);
3139 if (DR && DR->getQualifier()) {
3140 // If this is a qualified name, expand the template arguments in nested
3141 // qualifiers.
3142 DR->getQualifier()->print(OS, Policy, true);
3143 // Then print the decl itself.
3144 const ValueDecl *VD = DR->getDecl();
3145 OS << VD->getName();
3146 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3147 // This is a template variable, print the expanded template arguments.
3148 printTemplateArgumentList(OS, IV->getTemplateArgs().asArray(), Policy);
3149 }
3150 return true;
Clement Courbet9d432e02018-12-04 07:59:57 +00003151 }
Clement Courbetf44c6f42018-12-11 08:39:11 +00003152 return false;
Clement Courbet9d432e02018-12-04 07:59:57 +00003153 }
Clement Courbetf44c6f42018-12-11 08:39:11 +00003154
3155private:
3156 const PrintingPolicy Policy;
3157};
3158
3159} // end anonymous namespace
Clement Courbet9d432e02018-12-04 07:59:57 +00003160
Douglas Gregor672281a2017-09-14 23:38:42 +00003161std::pair<Expr *, std::string>
Clement Courbetf44c6f42018-12-11 08:39:11 +00003162Sema::findFailedBooleanCondition(Expr *Cond) {
Douglas Gregor672281a2017-09-14 23:38:42 +00003163 Cond = lookThroughRangesV3Condition(PP, Cond);
Douglas Gregorbb33f572017-07-05 20:20:15 +00003164
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003165 // Separate out all of the terms in a conjunction.
3166 SmallVector<Expr *, 4> Terms;
3167 collectConjunctionTerms(Cond, Terms);
3168
3169 // Determine which term failed.
3170 Expr *FailedCond = nullptr;
3171 for (Expr *Term : Terms) {
Douglas Gregor672281a2017-09-14 23:38:42 +00003172 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3173
Clement Courbetd8720412018-12-10 08:53:17 +00003174 // Literals are uninteresting.
3175 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3176 isa<IntegerLiteral>(TermAsWritten))
3177 continue;
3178
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003179 // The initialization of the parameter from the argument is
3180 // a constant-evaluated context.
3181 EnterExpressionEvaluationContext ConstantEvaluated(
Douglas Gregor672281a2017-09-14 23:38:42 +00003182 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003183
3184 bool Succeeded;
Douglas Gregor672281a2017-09-14 23:38:42 +00003185 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003186 !Succeeded) {
Douglas Gregor672281a2017-09-14 23:38:42 +00003187 FailedCond = TermAsWritten;
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003188 break;
3189 }
3190 }
Clement Courbetf44c6f42018-12-11 08:39:11 +00003191 if (!FailedCond)
Clement Courbetd8720412018-12-10 08:53:17 +00003192 FailedCond = Cond->IgnoreParenImpCasts();
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003193
3194 std::string Description;
3195 {
3196 llvm::raw_string_ostream Out(Description);
Clement Courbetfb2c74d2018-12-20 09:05:15 +00003197 PrintingPolicy Policy = getPrintingPolicy();
3198 Policy.PrintCanonicalTypes = true;
3199 FailedBooleanConditionPrinterHelper Helper(Policy);
3200 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003201 }
3202 return { FailedCond, Description };
3203}
3204
Douglas Gregordc572a32009-03-30 22:58:21 +00003205QualType Sema::CheckTemplateIdType(TemplateName Name,
3206 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003207 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00003208 DependentTemplateName *DTN
3209 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00003210 if (DTN && DTN->isIdentifier())
3211 // When building a template-id where the template-name is dependent,
3212 // assume the template is a type template. Either our assumption is
3213 // correct, or the code is ill-formed and will be diagnosed when the
3214 // dependent name is substituted.
3215 return Context.getDependentTemplateSpecializationType(ETK_None,
3216 DTN->getQualifier(),
3217 DTN->getIdentifier(),
3218 TemplateArgs);
3219
Douglas Gregordc572a32009-03-30 22:58:21 +00003220 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00003221 if (!Template || isa<FunctionTemplateDecl>(Template) ||
Faisal Valia534f072018-04-26 00:42:40 +00003222 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00003223 // We might have a substituted template template parameter pack. If so,
3224 // build a template specialization type for it.
3225 if (Name.getAsSubstTemplateTemplateParmPack())
3226 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003227
Douglas Gregor8b6070b2011-03-04 21:37:14 +00003228 Diag(TemplateLoc, diag::err_template_id_not_a_type)
3229 << Name;
3230 NoteAllFoundTemplates(Name);
3231 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00003232 }
Douglas Gregordc572a32009-03-30 22:58:21 +00003233
Douglas Gregorc40290e2009-03-09 23:48:35 +00003234 // Check that the template argument list is well-formed for this
3235 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003236 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00003237 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00003238 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00003239 return QualType();
3240
Douglas Gregorc40290e2009-03-09 23:48:35 +00003241 QualType CanonType;
3242
Douglas Gregor678d76c2011-07-01 01:22:09 +00003243 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00003244 if (TypeAliasTemplateDecl *AliasTemplate =
3245 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00003246 // Find the canonical type for this type alias template specialization.
3247 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3248 if (Pattern->isInvalidDecl())
3249 return QualType();
3250
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003251 TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack,
3252 Converted);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003253
3254 // Only substitute for the innermost template argument list.
3255 MultiLevelTemplateArgumentList TemplateArgLists;
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003256 TemplateArgLists.addOuterTemplateArguments(&StackTemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00003257 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
3258 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00003259 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003260
Richard Smith802c4b72012-08-23 06:16:52 +00003261 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003262 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003263 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003264 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00003265
Richard Smith3f1b5d02011-05-05 21:57:07 +00003266 CanonType = SubstType(Pattern->getUnderlyingType(),
3267 TemplateArgLists, AliasTemplate->getLocation(),
3268 AliasTemplate->getDeclName());
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003269 if (CanonType.isNull()) {
3270 // If this was enable_if and we failed to find the nested type
3271 // within enable_if in a SFINAE context, dig out the specific
3272 // enable_if condition that failed and present that instead.
3273 if (isEnableIfAliasTemplate(AliasTemplate)) {
3274 if (auto DeductionInfo = isSFINAEContext()) {
3275 if (*DeductionInfo &&
3276 (*DeductionInfo)->hasSFINAEDiagnostic() &&
3277 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3278 diag::err_typename_nested_not_found_enable_if &&
3279 TemplateArgs[0].getArgument().getKind()
3280 == TemplateArgument::Expression) {
3281 Expr *FailedCond;
3282 std::string FailedDescription;
3283 std::tie(FailedCond, FailedDescription) =
Clement Courbetf44c6f42018-12-11 08:39:11 +00003284 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003285
3286 // Remove the old SFINAE diagnostic.
3287 PartialDiagnosticAt OldDiag =
3288 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3289 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3290
3291 // Add a new SFINAE diagnostic specifying which condition
3292 // failed.
3293 (*DeductionInfo)->addSFINAEDiagnostic(
3294 OldDiag.first,
3295 PDiag(diag::err_typename_nested_not_found_requirement)
3296 << FailedDescription
3297 << FailedCond->getSourceRange());
3298 }
3299 }
3300 }
3301
Richard Smith3f1b5d02011-05-05 21:57:07 +00003302 return QualType();
Douglas Gregor00fa10b2017-07-05 20:20:14 +00003303 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00003304 } else if (Name.isDependent() ||
3305 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00003306 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00003307 // This class template specialization is a dependent
3308 // type. Therefore, its canonical type is another class template
3309 // specialization type that contains all of the converted
3310 // arguments in canonical form. This ensures that, e.g., A<T> and
3311 // A<T, T> have identical types when A is declared as:
3312 //
3313 // template<typename T, typename U = T> struct A;
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00003314 CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
John McCall2408e322010-04-27 00:57:59 +00003315
3316 // This might work out to be a current instantiation, in which
3317 // case the canonical type needs to be the InjectedClassNameType.
3318 //
3319 // TODO: in theory this could be a simple hashtable lookup; most
3320 // changes to CurContext don't change the set of current
3321 // instantiations.
3322 if (isa<ClassTemplateDecl>(Template)) {
3323 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3324 // If we get out to a namespace, we're done.
3325 if (Ctx->isFileContext()) break;
3326
3327 // If this isn't a record, keep looking.
3328 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3329 if (!Record) continue;
3330
3331 // Look for one of the two cases with InjectedClassNameTypes
3332 // and check whether it's the same template.
3333 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3334 !Record->getDescribedClassTemplate())
3335 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003336
John McCall2408e322010-04-27 00:57:59 +00003337 // Fetch the injected class name type and check whether its
3338 // injected type is equal to the type we just built.
3339 QualType ICNT = Context.getTypeDeclType(Record);
3340 QualType Injected = cast<InjectedClassNameType>(ICNT)
3341 ->getInjectedSpecializationType();
3342
3343 if (CanonType != Injected->getCanonicalTypeInternal())
3344 continue;
3345
3346 // If so, the canonical type of this TST is the injected
3347 // class name type of the record we just found.
3348 assert(ICNT.isCanonical());
3349 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00003350 break;
3351 }
3352 }
Mike Stump11289f42009-09-09 15:08:12 +00003353 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00003354 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00003355 // Find the class template specialization declaration that
3356 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00003357 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00003358 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00003359 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003360 if (!Decl) {
3361 // This is the first time we have referenced this class template
3362 // specialization. Create the canonical declaration and add it to
3363 // the set of specializations.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003364 Decl = ClassTemplateSpecializationDecl::Create(
3365 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3366 ClassTemplate->getDeclContext(),
3367 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3368 ClassTemplate->getLocation(), ClassTemplate, Converted, nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003369 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00003370 if (ClassTemplate->isOutOfLine())
3371 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00003372 }
3373
Erich Keanea32910d2017-03-23 18:51:54 +00003374 if (Decl->getSpecializationKind() == TSK_Undeclared) {
3375 MultiLevelTemplateArgumentList TemplateArgLists;
3376 TemplateArgLists.addOuterTemplateArguments(Converted);
3377 InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(),
3378 Decl);
3379 }
3380
Chandler Carruth2acfb222013-09-27 22:14:40 +00003381 // Diagnose uses of this specialization.
3382 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3383
Douglas Gregorc40290e2009-03-09 23:48:35 +00003384 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00003385 assert(isa<RecordType>(CanonType) &&
3386 "type of non-dependent specialization is not a RecordType");
David Majnemerd9b1a4f2015-11-04 03:40:30 +00003387 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3388 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
3389 TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003390 }
Mike Stump11289f42009-09-09 15:08:12 +00003391
Douglas Gregorc40290e2009-03-09 23:48:35 +00003392 // Build the fully-sugared type for this class template
3393 // specialization, which refers back to the class template
3394 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00003395 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003396}
3397
Richard Smithb23c5e82019-05-09 03:31:27 +00003398void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,
3399 TemplateNameKind &TNK,
3400 SourceLocation NameLoc,
3401 IdentifierInfo *&II) {
3402 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
3403
3404 TemplateName Name = ParsedName.get();
3405 auto *ATN = Name.getAsAssumedTemplateName();
3406 assert(ATN && "not an assumed template name");
3407 II = ATN->getDeclName().getAsIdentifierInfo();
3408
3409 if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
3410 // Resolved to a type template name.
3411 ParsedName = TemplateTy::make(Name);
3412 TNK = TNK_Type_template;
3413 }
3414}
3415
3416bool Sema::resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
3417 SourceLocation NameLoc,
3418 bool Diagnose) {
3419 // We assumed this undeclared identifier to be an (ADL-only) function
3420 // template name, but it was used in a context where a type was required.
3421 // Try to typo-correct it now.
3422 AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
3423 assert(ATN && "not an assumed template name");
3424
3425 LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
3426 struct CandidateCallback : CorrectionCandidateCallback {
3427 bool ValidateCandidate(const TypoCorrection &TC) override {
3428 return TC.getCorrectionDecl() &&
3429 getAsTypeTemplateDecl(TC.getCorrectionDecl());
3430 }
3431 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3432 return llvm::make_unique<CandidateCallback>(*this);
3433 }
3434 } FilterCCC;
3435
3436 TypoCorrection Corrected =
3437 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
3438 FilterCCC, CTK_ErrorRecovery);
3439 if (Corrected && Corrected.getFoundDecl()) {
3440 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
3441 << ATN->getDeclName());
3442 Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>());
3443 return false;
3444 }
3445
3446 if (Diagnose)
3447 Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
3448 return true;
3449}
3450
3451TypeResult Sema::ActOnTemplateIdType(
3452 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3453 TemplateTy TemplateD, IdentifierInfo *TemplateII,
3454 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
3455 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
3456 bool IsCtorOrDtorName, bool IsClassName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00003457 if (SS.isInvalid())
3458 return true;
3459
Richard Smith62559bd2017-02-01 21:36:38 +00003460 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3461 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3462
3463 // C++ [temp.res]p3:
3464 // A qualified-id that refers to a type and in which the
3465 // nested-name-specifier depends on a template-parameter (14.6.2)
3466 // shall be prefixed by the keyword typename to indicate that the
3467 // qualified-id denotes a type, forming an
3468 // elaborated-type-specifier (7.1.5.3).
3469 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
Richard Smith3411fbf2017-02-01 21:41:18 +00003470 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
Richard Smith62559bd2017-02-01 21:36:38 +00003471 << SS.getScopeRep() << TemplateII->getName();
3472 // Recover as if 'typename' were specified.
3473 // FIXME: This is not quite correct recovery as we don't transform SS
3474 // into the corresponding dependent form (and we don't diagnose missing
3475 // 'template' keywords within SS as a result).
3476 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3477 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3478 TemplateArgsIn, RAngleLoc);
3479 }
3480
3481 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3482 // it's not actually allowed to be used as a type in most cases. Because
3483 // we annotate it before we know whether it's valid, we have to check for
3484 // this case here.
3485 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
Richard Smith74f02342017-01-19 21:00:13 +00003486 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3487 Diag(TemplateIILoc,
3488 TemplateKWLoc.isInvalid()
3489 ? diag::err_out_of_line_qualified_id_type_names_constructor
3490 : diag::ext_out_of_line_qualified_id_type_names_constructor)
3491 << TemplateII << 0 /*injected-class-name used as template name*/
3492 << 1 /*if any keyword was present, it was 'template'*/;
3493 }
3494 }
3495
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003496 TemplateName Template = TemplateD.get();
Richard Smithb23c5e82019-05-09 03:31:27 +00003497 if (Template.getAsAssumedTemplateName() &&
3498 resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
3499 return true;
Douglas Gregor8bf42052009-02-09 18:46:07 +00003500
Douglas Gregorc40290e2009-03-09 23:48:35 +00003501 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003502 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003503 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00003504
Douglas Gregor5a064722011-02-28 17:23:35 +00003505 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00003506 QualType T
3507 = Context.getDependentTemplateSpecializationType(ETK_None,
3508 DTN->getQualifier(),
3509 DTN->getIdentifier(),
3510 TemplateArgs);
3511 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00003512 TypeLocBuilder TLB;
3513 DependentTemplateSpecializationTypeLoc SpecTL
3514 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003515 SpecTL.setElaboratedKeywordLoc(SourceLocation());
3516 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00003517 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00003518 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00003519 SpecTL.setLAngleLoc(LAngleLoc);
3520 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00003521 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3522 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3523 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3524 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003525
Richard Smith74f02342017-01-19 21:00:13 +00003526 QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003527 if (Result.isNull())
3528 return true;
3529
Douglas Gregore7c20652011-03-02 00:47:37 +00003530 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003531 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00003532 TemplateSpecializationTypeLoc SpecTL
3533 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003534 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00003535 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003536 SpecTL.setLAngleLoc(LAngleLoc);
3537 SpecTL.setRAngleLoc(RAngleLoc);
3538 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3539 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00003540
Abramo Bagnara4244b432012-01-27 08:46:19 +00003541 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
3542 // constructor or destructor name (in such a case, the scope specifier
3543 // will be attached to the enclosing Decl or Expr node).
3544 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00003545 // Create an elaborated-type-specifier containing the nested-name-specifier.
3546 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
3547 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00003548 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00003549 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3550 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003551
Douglas Gregore7c20652011-03-02 00:47:37 +00003552 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00003553}
John McCall06f6fe8d2009-09-04 01:14:41 +00003554
Douglas Gregore7c20652011-03-02 00:47:37 +00003555TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00003556 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00003557 SourceLocation TagLoc,
3558 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003559 SourceLocation TemplateKWLoc,
3560 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00003561 SourceLocation TemplateLoc,
3562 SourceLocation LAngleLoc,
3563 ASTTemplateArgsPtr TemplateArgsIn,
3564 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003565 TemplateName Template = TemplateD.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00003566
Douglas Gregore7c20652011-03-02 00:47:37 +00003567 // Translate the parser's template argument list in our AST format.
3568 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3569 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003570
Douglas Gregore7c20652011-03-02 00:47:37 +00003571 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00003572 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00003573 ElaboratedTypeKeyword Keyword
3574 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00003575
Douglas Gregore7c20652011-03-02 00:47:37 +00003576 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3577 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
Simon Pilgrim6905d222016-12-30 22:55:33 +00003578 DTN->getQualifier(),
3579 DTN->getIdentifier(),
Douglas Gregore7c20652011-03-02 00:47:37 +00003580 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003581
3582 // Build type-source information.
Douglas Gregore7c20652011-03-02 00:47:37 +00003583 TypeLocBuilder TLB;
3584 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003585 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3586 SpecTL.setElaboratedKeywordLoc(TagLoc);
3587 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00003588 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003589 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003590 SpecTL.setLAngleLoc(LAngleLoc);
3591 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003592 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3593 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3594 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3595 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00003596
3597 if (TypeAliasTemplateDecl *TAT =
3598 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3599 // C++0x [dcl.type.elab]p2:
3600 // If the identifier resolves to a typedef-name or the simple-template-id
3601 // resolves to an alias template specialization, the
3602 // elaborated-type-specifier is ill-formed.
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00003603 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3604 << TAT << NTK_TypeAliasTemplate << TagKind;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003605 Diag(TAT->getLocation(), diag::note_declared_at);
3606 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003607
Douglas Gregore7c20652011-03-02 00:47:37 +00003608 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3609 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00003610 return TypeResult(true);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003611
Douglas Gregore7c20652011-03-02 00:47:37 +00003612 // Check the tag kind
3613 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00003614 RecordDecl *D = RT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00003615
John McCalld8fe9af2009-09-08 17:47:29 +00003616 IdentifierInfo *Id = D->getIdentifier();
3617 assert(Id && "templated class must have an identifier");
Simon Pilgrim6905d222016-12-30 22:55:33 +00003618
Richard Trieucaa33d32011-06-10 03:11:26 +00003619 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00003620 TagLoc, Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00003621 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00003622 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00003623 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00003624 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00003625 }
3626 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003627
Douglas Gregore7c20652011-03-02 00:47:37 +00003628 // Provide source-location information for the template specialization.
3629 TypeLocBuilder TLB;
3630 TemplateSpecializationTypeLoc SpecTL
3631 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003632 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003633 SpecTL.setTemplateNameLoc(TemplateLoc);
3634 SpecTL.setLAngleLoc(LAngleLoc);
3635 SpecTL.setRAngleLoc(RAngleLoc);
3636 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3637 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00003638
Douglas Gregore7c20652011-03-02 00:47:37 +00003639 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003640 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00003641 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3642 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00003643 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00003644 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3645 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003646}
3647
Larisse Voufo39a1e502013-08-06 01:03:05 +00003648static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3649 NamedDecl *PrevDecl,
3650 SourceLocation Loc,
3651 bool IsPartialSpecialization);
3652
3653static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003654
Richard Smith300e0c32013-09-24 04:49:23 +00003655static bool isTemplateArgumentTemplateParameter(
3656 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3657 switch (Arg.getKind()) {
3658 case TemplateArgument::Null:
3659 case TemplateArgument::NullPtr:
3660 case TemplateArgument::Integral:
3661 case TemplateArgument::Declaration:
3662 case TemplateArgument::Pack:
3663 case TemplateArgument::TemplateExpansion:
3664 return false;
3665
3666 case TemplateArgument::Type: {
3667 QualType Type = Arg.getAsType();
3668 const TemplateTypeParmType *TPT =
3669 Arg.getAsType()->getAs<TemplateTypeParmType>();
3670 return TPT && !Type.hasQualifiers() &&
3671 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3672 }
3673
3674 case TemplateArgument::Expression: {
3675 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3676 if (!DRE || !DRE->getDecl())
3677 return false;
3678 const NonTypeTemplateParmDecl *NTTP =
3679 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3680 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3681 }
3682
3683 case TemplateArgument::Template:
3684 const TemplateTemplateParmDecl *TTP =
3685 dyn_cast_or_null<TemplateTemplateParmDecl>(
3686 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
3687 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3688 }
3689 llvm_unreachable("unexpected kind of template argument");
3690}
3691
3692static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
3693 ArrayRef<TemplateArgument> Args) {
3694 if (Params->size() != Args.size())
3695 return false;
3696
3697 unsigned Depth = Params->getDepth();
3698
3699 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3700 TemplateArgument Arg = Args[I];
3701
3702 // If the parameter is a pack expansion, the argument must be a pack
3703 // whose only element is a pack expansion.
3704 if (Params->getParam(I)->isParameterPack()) {
3705 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3706 !Arg.pack_begin()->isPackExpansion())
3707 return false;
3708 Arg = Arg.pack_begin()->getPackExpansionPattern();
3709 }
3710
3711 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3712 return false;
3713 }
3714
3715 return true;
3716}
3717
Richard Smith4b55a9c2014-04-17 03:29:33 +00003718/// Convert the parser's template argument list representation into our form.
3719static TemplateArgumentListInfo
3720makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
3721 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
3722 TemplateId.RAngleLoc);
3723 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
3724 TemplateId.NumArgs);
3725 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
3726 return TemplateArgs;
3727}
3728
Richard Smith0e617ec2016-12-27 07:56:27 +00003729template<typename PartialSpecDecl>
3730static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3731 if (Partial->getDeclContext()->isDependentContext())
3732 return;
3733
3734 // FIXME: Get the TDK from deduction in order to provide better diagnostics
3735 // for non-substitution-failure issues?
3736 TemplateDeductionInfo Info(Partial->getLocation());
3737 if (S.isMoreSpecializedThanPrimary(Partial, Info))
3738 return;
3739
3740 auto *Template = Partial->getSpecializedTemplate();
3741 S.Diag(Partial->getLocation(),
Richard Smithfa4a09d2016-12-27 20:03:09 +00003742 diag::ext_partial_spec_not_more_specialized_than_primary)
3743 << isa<VarTemplateDecl>(Template);
Richard Smith0e617ec2016-12-27 07:56:27 +00003744
3745 if (Info.hasSFINAEDiagnostic()) {
3746 PartialDiagnosticAt Diag = {SourceLocation(),
3747 PartialDiagnostic::NullDiagnostic()};
3748 Info.takeSFINAEDiagnostic(Diag);
3749 SmallString<128> SFINAEArgString;
3750 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3751 S.Diag(Diag.first,
3752 diag::note_partial_spec_not_more_specialized_than_primary)
3753 << SFINAEArgString;
3754 }
3755
3756 S.Diag(Template->getLocation(), diag::note_template_decl_here);
3757}
3758
Richard Smith4e05eaa2017-02-16 00:36:47 +00003759static void
3760noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
3761 const llvm::SmallBitVector &DeducibleParams) {
3762 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3763 if (!DeducibleParams[I]) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00003764 NamedDecl *Param = TemplateParams->getParam(I);
Richard Smith4e05eaa2017-02-16 00:36:47 +00003765 if (Param->getDeclName())
3766 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3767 << Param->getDeclName();
3768 else
3769 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3770 << "(anonymous)";
3771 }
3772 }
3773}
3774
3775
Richard Smith57aae072016-12-28 02:37:25 +00003776template<typename PartialSpecDecl>
3777static void checkTemplatePartialSpecialization(Sema &S,
3778 PartialSpecDecl *Partial) {
3779 // C++1z [temp.class.spec]p8: (DR1495)
3780 // - The specialization shall be more specialized than the primary
3781 // template (14.5.5.2).
3782 checkMoreSpecializedThanPrimary(S, Partial);
3783
3784 // C++ [temp.class.spec]p8: (DR1315)
3785 // - Each template-parameter shall appear at least once in the
3786 // template-id outside a non-deduced context.
3787 // C++1z [temp.class.spec.match]p3 (P0127R2)
3788 // If the template arguments of a partial specialization cannot be
3789 // deduced because of the structure of its template-parameter-list
3790 // and the template-id, the program is ill-formed.
3791 auto *TemplateParams = Partial->getTemplateParameters();
3792 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3793 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3794 TemplateParams->getDepth(), DeducibleParams);
3795
3796 if (!DeducibleParams.all()) {
3797 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3798 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3799 << isa<VarTemplatePartialSpecializationDecl>(Partial)
3800 << (NumNonDeducible > 1)
3801 << SourceRange(Partial->getLocation(),
3802 Partial->getTemplateArgsAsWritten()->RAngleLoc);
Richard Smith4e05eaa2017-02-16 00:36:47 +00003803 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
Richard Smith57aae072016-12-28 02:37:25 +00003804 }
3805}
3806
3807void Sema::CheckTemplatePartialSpecialization(
3808 ClassTemplatePartialSpecializationDecl *Partial) {
3809 checkTemplatePartialSpecialization(*this, Partial);
3810}
3811
3812void Sema::CheckTemplatePartialSpecialization(
3813 VarTemplatePartialSpecializationDecl *Partial) {
3814 checkTemplatePartialSpecialization(*this, Partial);
3815}
3816
Richard Smith4e05eaa2017-02-16 00:36:47 +00003817void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
3818 // C++1z [temp.param]p11:
3819 // A template parameter of a deduction guide template that does not have a
3820 // default-argument shall be deducible from the parameter-type-list of the
3821 // deduction guide template.
3822 auto *TemplateParams = TD->getTemplateParameters();
3823 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3824 MarkDeducedTemplateParameters(TD, DeducibleParams);
3825 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3826 // A parameter pack is deducible (to an empty pack).
3827 auto *Param = TemplateParams->getParam(I);
3828 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3829 DeducibleParams[I] = true;
3830 }
3831
3832 if (!DeducibleParams.all()) {
3833 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3834 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3835 << (NumNonDeducible > 1);
3836 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3837 }
3838}
3839
Larisse Voufo39a1e502013-08-06 01:03:05 +00003840DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00003841 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00003842 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00003843 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003844 // D must be variable template id.
Faisal Vali2ab8c152017-12-30 04:15:27 +00003845 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00003846 "Variable template specialization is declared with a template it.");
3847
3848 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00003849 TemplateArgumentListInfo TemplateArgs =
3850 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003851 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3852 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3853 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00003854
Richard Smithbeef3452014-01-16 23:39:20 +00003855 TemplateName Name = TemplateId->Template.get();
3856
3857 // The template-id must name a variable template.
3858 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00003859 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3860 if (!VarTemplate) {
3861 NamedDecl *FnTemplate;
3862 if (auto *OTS = Name.getAsOverloadedTemplate())
3863 FnTemplate = *OTS->begin();
3864 else
3865 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3866 if (FnTemplate)
3867 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3868 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00003869 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3870 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00003871 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003872
3873 // Check for unexpanded parameter packs in any of the template arguments.
3874 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3875 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3876 UPPC_PartialSpecialization))
3877 return true;
3878
3879 // Check that the template argument list is well-formed for this
3880 // template.
3881 SmallVector<TemplateArgument, 4> Converted;
3882 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
3883 false, Converted))
3884 return true;
3885
Larisse Voufo39a1e502013-08-06 01:03:05 +00003886 // Find the variable template (partial) specialization declaration that
3887 // corresponds to these arguments.
3888 if (IsPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00003889 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
3890 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00003891 return true;
3892
Richard Smith57aae072016-12-28 02:37:25 +00003893 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
3894 // also do them during instantiation.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003895 bool InstantiationDependent;
3896 if (!Name.isDependent() &&
3897 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00003898 TemplateArgs.arguments(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00003899 InstantiationDependent)) {
3900 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3901 << VarTemplate->getDeclName();
3902 IsPartialSpecialization = false;
3903 }
Richard Smith300e0c32013-09-24 04:49:23 +00003904
3905 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
3906 Converted)) {
3907 // C++ [temp.class.spec]p9b3:
3908 //
3909 // -- The argument list of the specialization shall not be identical
3910 // to the implicit argument list of the primary template.
3911 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3912 << /*variable template*/ 1
3913 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
3914 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
3915 // FIXME: Recover from this by treating the declaration as a redeclaration
3916 // of the primary template.
3917 return true;
3918 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003919 }
3920
Craig Topperc3ec1492014-05-26 06:22:03 +00003921 void *InsertPos = nullptr;
3922 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003923
3924 if (IsPartialSpecialization)
3925 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00003926 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003927 else
Craig Topper7e0daca2014-06-26 04:58:53 +00003928 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003929
Craig Topperc3ec1492014-05-26 06:22:03 +00003930 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003931
3932 // Check whether we can declare a variable template specialization in
3933 // the current scope.
3934 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
3935 TemplateNameLoc,
3936 IsPartialSpecialization))
3937 return true;
3938
3939 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3940 // Since the only prior variable template specialization with these
3941 // arguments was referenced but not declared, reuse that
3942 // declaration node as our own, updating its source location and
3943 // the list of outer template parameters to reflect our new declaration.
3944 Specialization = PrevDecl;
3945 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00003946 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003947 } else if (IsPartialSpecialization) {
3948 // Create a new class template partial specialization declaration node.
3949 VarTemplatePartialSpecializationDecl *PrevPartial =
3950 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003951 VarTemplatePartialSpecializationDecl *Partial =
3952 VarTemplatePartialSpecializationDecl::Create(
3953 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
3954 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
David Majnemer8b622692016-07-03 21:17:51 +00003955 Converted, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003956
3957 if (!PrevPartial)
3958 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
3959 Specialization = Partial;
3960
3961 // If we are providing an explicit specialization of a member variable
3962 // template specialization, make a note of that.
3963 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00003964 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00003965
Richard Smith57aae072016-12-28 02:37:25 +00003966 CheckTemplatePartialSpecialization(Partial);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003967 } else {
3968 // Create a new class template specialization declaration node for
3969 // this explicit specialization or friend declaration.
3970 Specialization = VarTemplateSpecializationDecl::Create(
3971 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
David Majnemer8b622692016-07-03 21:17:51 +00003972 VarTemplate, DI->getType(), DI, SC, Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003973 Specialization->setTemplateArgsInfo(TemplateArgs);
3974
3975 if (!PrevDecl)
3976 VarTemplate->AddSpecialization(Specialization, InsertPos);
3977 }
3978
3979 // C++ [temp.expl.spec]p6:
3980 // If a template, a member template or the member of a class template is
3981 // explicitly specialized then that specialization shall be declared
3982 // before the first use of that specialization that would cause an implicit
3983 // instantiation to take place, in every translation unit in which such a
3984 // use occurs; no diagnostic is required.
3985 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3986 bool Okay = false;
3987 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
3988 // Is there any previous explicit specialization declaration?
3989 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3990 Okay = true;
3991 break;
3992 }
3993 }
3994
3995 if (!Okay) {
3996 SourceRange Range(TemplateNameLoc, RAngleLoc);
3997 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3998 << Name << Range;
3999
4000 Diag(PrevDecl->getPointOfInstantiation(),
4001 diag::note_instantiation_required_here)
4002 << (PrevDecl->getTemplateSpecializationKind() !=
4003 TSK_ImplicitInstantiation);
4004 return true;
4005 }
4006 }
4007
4008 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
4009 Specialization->setLexicalDeclContext(CurContext);
4010
4011 // Add the specialization into its lexical context, so that it can
4012 // be seen when iterating through the list of declarations in that
4013 // context. However, specializations are not found by name lookup.
4014 CurContext->addDecl(Specialization);
4015
4016 // Note that this is an explicit specialization.
4017 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4018
4019 if (PrevDecl) {
4020 // Check that this isn't a redefinition of this specialization,
4021 // merging with previous declarations.
4022 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00004023 forRedeclarationInCurContext());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004024 PrevSpec.addDecl(PrevDecl);
4025 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00004026 } else if (Specialization->isStaticDataMember() &&
4027 Specialization->isOutOfLine()) {
4028 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004029 }
4030
Larisse Voufo39a1e502013-08-06 01:03:05 +00004031 return Specialization;
4032}
4033
4034namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004035/// A partial specialization whose template arguments have matched
Larisse Voufo39a1e502013-08-06 01:03:05 +00004036/// a given template-id.
4037struct PartialSpecMatchResult {
4038 VarTemplatePartialSpecializationDecl *Partial;
4039 TemplateArgumentList *Args;
4040};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004041} // end anonymous namespace
Larisse Voufo39a1e502013-08-06 01:03:05 +00004042
4043DeclResult
4044Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
4045 SourceLocation TemplateNameLoc,
4046 const TemplateArgumentListInfo &TemplateArgs) {
4047 assert(Template && "A variable template id without template?");
4048
4049 // Check that the template argument list is well-formed for this template.
4050 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004051 if (CheckTemplateArgumentList(
4052 Template, TemplateNameLoc,
4053 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00004054 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00004055 return true;
4056
4057 // Find the variable template specialization declaration that
4058 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00004059 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004060 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Richard Smith6739a102016-05-05 00:56:12 +00004061 Converted, InsertPos)) {
4062 checkSpecializationVisibility(TemplateNameLoc, Spec);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004063 // If we already have a variable template specialization, return it.
4064 return Spec;
Richard Smith6739a102016-05-05 00:56:12 +00004065 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004066
4067 // This is the first time we have referenced this variable template
4068 // specialization. Create the canonical declaration and add it to
4069 // the set of specializations, based on the closest partial specialization
4070 // that it represents. That is,
4071 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4072 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00004073 Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004074 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
4075 bool AmbiguousPartialSpec = false;
4076 typedef PartialSpecMatchResult MatchResult;
4077 SmallVector<MatchResult, 4> Matched;
4078 SourceLocation PointOfInstantiation = TemplateNameLoc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00004079 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4080 /*ForTakingAddress=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004081
4082 // 1. Attempt to find the closest partial specialization that this
4083 // specializes, if any.
4084 // If any of the template arguments is dependent, then this is probably
4085 // a placeholder for an incomplete declarative context; which must be
4086 // complete by instantiation time. Thus, do not search through the partial
4087 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00004088 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4089 // Perhaps better after unification of DeduceTemplateArguments() and
4090 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00004091 bool InstantiationDependent = false;
4092 if (!TemplateSpecializationType::anyDependentTemplateArguments(
4093 TemplateArgs, InstantiationDependent)) {
4094
4095 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4096 Template->getPartialSpecializations(PartialSpecs);
4097
4098 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
4099 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
4100 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4101
4102 if (TemplateDeductionResult Result =
4103 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
4104 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00004105 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00004106 FailedCandidates.addCandidate().set(
4107 DeclAccessPair::make(Template, AS_public), Partial,
4108 MakeDeductionFailureInfo(Context, Result, Info));
Larisse Voufo39a1e502013-08-06 01:03:05 +00004109 (void)Result;
4110 } else {
4111 Matched.push_back(PartialSpecMatchResult());
4112 Matched.back().Partial = Partial;
4113 Matched.back().Args = Info.take();
4114 }
4115 }
4116
Larisse Voufo39a1e502013-08-06 01:03:05 +00004117 if (Matched.size() >= 1) {
4118 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4119 if (Matched.size() == 1) {
4120 // -- If exactly one matching specialization is found, the
4121 // instantiation is generated from that specialization.
4122 // We don't need to do anything for this.
4123 } else {
4124 // -- If more than one matching specialization is found, the
4125 // partial order rules (14.5.4.2) are used to determine
4126 // whether one of the specializations is more specialized
4127 // than the others. If none of the specializations is more
4128 // specialized than all of the other matching
4129 // specializations, then the use of the variable template is
4130 // ambiguous and the program is ill-formed.
4131 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4132 PEnd = Matched.end();
4133 P != PEnd; ++P) {
4134 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4135 PointOfInstantiation) ==
4136 P->Partial)
4137 Best = P;
4138 }
4139
4140 // Determine if the best partial specialization is more specialized than
4141 // the others.
4142 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4143 PEnd = Matched.end();
4144 P != PEnd; ++P) {
4145 if (P != Best && getMoreSpecializedPartialSpecialization(
4146 P->Partial, Best->Partial,
4147 PointOfInstantiation) != Best->Partial) {
4148 AmbiguousPartialSpec = true;
4149 break;
4150 }
4151 }
4152 }
4153
4154 // Instantiate using the best variable template partial specialization.
4155 InstantiationPattern = Best->Partial;
4156 InstantiationArgs = Best->Args;
4157 } else {
4158 // -- If no match is found, the instantiation is generated
4159 // from the primary template.
4160 // InstantiationPattern = Template->getTemplatedDecl();
4161 }
4162 }
4163
Larisse Voufo39a1e502013-08-06 01:03:05 +00004164 // 2. Create the canonical declaration.
Richard Smith6739a102016-05-05 00:56:12 +00004165 // Note that we do not instantiate a definition until we see an odr-use
4166 // in DoMarkVarDeclReferenced().
Larisse Voufo39a1e502013-08-06 01:03:05 +00004167 // FIXME: LateAttrs et al.?
4168 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4169 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
4170 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
4171 if (!Decl)
4172 return true;
4173
4174 if (AmbiguousPartialSpec) {
4175 // Partial ordering did not produce a clear winner. Complain.
4176 Decl->setInvalidDecl();
4177 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4178 << Decl;
4179
4180 // Print the matching partial specializations.
Yaron Keren1cb81462016-11-16 13:45:34 +00004181 for (MatchResult P : Matched)
4182 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4183 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4184 *P.Args);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004185 return true;
4186 }
4187
4188 if (VarTemplatePartialSpecializationDecl *D =
4189 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4190 Decl->setInstantiationOf(D, InstantiationArgs);
4191
Richard Smith6739a102016-05-05 00:56:12 +00004192 checkSpecializationVisibility(TemplateNameLoc, Decl);
4193
Larisse Voufo39a1e502013-08-06 01:03:05 +00004194 assert(Decl && "No variable template specialization?");
4195 return Decl;
4196}
4197
4198ExprResult
4199Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
4200 const DeclarationNameInfo &NameInfo,
4201 VarTemplateDecl *Template, SourceLocation TemplateLoc,
4202 const TemplateArgumentListInfo *TemplateArgs) {
4203
4204 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4205 *TemplateArgs);
4206 if (Decl.isInvalid())
4207 return ExprError();
4208
4209 VarDecl *Var = cast<VarDecl>(Decl.get());
4210 if (!Var->getTemplateSpecializationKind())
4211 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
4212 NameInfo.getLoc());
4213
4214 // Build an ordinary singleton decl ref.
4215 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00004216 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004217}
4218
Richard Smithecad88d2018-04-26 01:08:00 +00004219void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4220 SourceLocation Loc) {
4221 Diag(Loc, diag::err_template_missing_args)
4222 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4223 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4224 Diag(TD->getLocation(), diag::note_template_decl_here)
4225 << TD->getTemplateParameters()->getSourceRange();
4226 }
4227}
4228
John McCalldadc5752010-08-24 06:29:42 +00004229ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004230 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00004231 LookupResult &R,
4232 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00004233 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00004234 // FIXME: Can we do any checking at this point? I guess we could check the
4235 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00004236 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00004237 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00004238 // foo<int> could identify a single function unambiguously
4239 // This approach does NOT work, since f<int>(1);
4240 // gets resolved prior to resorting to overload resolution
4241 // i.e., template<class T> void f(double);
4242 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00004243
4244 // These should be filtered out by our callers.
John McCalle66edc12009-11-24 19:00:30 +00004245 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4246
Richard Smith04100942018-04-26 02:10:22 +00004247 // Non-function templates require a template argument list.
4248 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4249 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4250 diagnoseMissingTemplateArguments(TemplateName(TD), R.getNameLoc());
4251 return ExprError();
4252 }
4253 }
4254
Richard Smith0bf96f92018-04-25 22:58:55 +00004255 auto AnyDependentArguments = [&]() -> bool {
4256 bool InstantiationDependent;
4257 return TemplateArgs &&
4258 TemplateSpecializationType::anyDependentTemplateArguments(
4259 *TemplateArgs, InstantiationDependent);
4260 };
4261
Larisse Voufo39a1e502013-08-06 01:03:05 +00004262 // In C++1y, check variable template ids.
Richard Smith0bf96f92018-04-25 22:58:55 +00004263 if (R.getAsSingle<VarTemplateDecl>() && !AnyDependentArguments()) {
Richard Smithd7d11ef2014-02-03 20:09:56 +00004264 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
4265 R.getAsSingle<VarTemplateDecl>(),
4266 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004267 }
4268
John McCall58cc69d2010-01-27 01:50:18 +00004269 // We don't want lookup warnings at this point.
4270 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004271
John McCalle66edc12009-11-24 19:00:30 +00004272 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00004273 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00004274 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00004275 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004276 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004277 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00004278 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00004279
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004280 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00004281}
4282
John McCalle66edc12009-11-24 19:00:30 +00004283// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00004284ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004285Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004286 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004287 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00004288 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004289
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00004290 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00004291 DeclContext *DC;
4292 if (!(DC = computeDeclContext(SS, false)) ||
4293 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00004294 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00004295 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004296
Douglas Gregor786123d2010-05-21 23:18:07 +00004297 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004298 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Richard Smith79810042018-05-11 02:43:08 +00004299 if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(),
4300 /*Entering*/false, MemberOfUnknownSpecialization,
4301 TemplateKWLoc))
4302 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004303
John McCalle66edc12009-11-24 19:00:30 +00004304 if (R.isAmbiguous())
4305 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004306
John McCalle66edc12009-11-24 19:00:30 +00004307 if (R.empty()) {
Richard Smith79810042018-05-11 02:43:08 +00004308 Diag(NameInfo.getLoc(), diag::err_no_member)
4309 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00004310 return ExprError();
4311 }
4312
4313 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004314 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00004315 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00004316 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00004317 Diag(Temp->getLocation(), diag::note_referenced_class_template);
4318 return ExprError();
4319 }
4320
Abramo Bagnara7945c982012-01-27 09:46:47 +00004321 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00004322}
4323
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004324/// Form a dependent template name.
Douglas Gregorb67535d2009-03-31 00:43:58 +00004325///
4326/// This action forms a dependent template name given the template
4327/// name and its (presumably dependent) scope specifier. For
4328/// example, given "MetaFun::template apply", the scope specifier \p
4329/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
4330/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004331TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00004332 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004333 SourceLocation TemplateKWLoc,
Richard Smithc08b6932018-04-27 02:00:13 +00004334 const UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00004335 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00004336 bool EnteringContext,
Richard Smithfd3dae02017-01-20 00:20:39 +00004337 TemplateTy &Result,
4338 bool AllowInjectedClassName) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004339 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4340 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004341 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004342 diag::warn_cxx98_compat_template_outside_of_template :
4343 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004344 << FixItHint::CreateRemoval(TemplateKWLoc);
4345
Craig Topperc3ec1492014-05-26 06:22:03 +00004346 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00004347 if (SS.isSet())
4348 LookupCtx = computeDeclContext(SS, EnteringContext);
4349 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00004350 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00004351 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00004352 // C++0x [temp.names]p5:
4353 // If a name prefixed by the keyword template is not the name of
4354 // a template, the program is ill-formed. [Note: the keyword
4355 // template may not be applied to non-template members of class
4356 // templates. -end note ] [ Note: as is the case with the
4357 // typename prefix, the template prefix is allowed in cases
4358 // where it is not strictly necessary; i.e., when the
4359 // nested-name-specifier or the expression on the left of the ->
4360 // or . is not dependent on a template-parameter, or the use
4361 // does not appear in the scope of a template. -end note]
4362 //
4363 // Note: C++03 was more strict here, because it banned the use of
4364 // the "template" keyword prior to a template-name that was not a
4365 // dependent name. C++ DR468 relaxed this requirement (the
4366 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00004367 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00004368 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00004369 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00004370 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00004371 MemberOfUnknownSpecialization);
Richard Smith79810042018-05-11 02:43:08 +00004372 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization) {
Douglas Gregorbb119652010-06-16 23:00:59 +00004373 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00004374 } else if (TNK == TNK_Non_template) {
Richard Smith79810042018-05-11 02:43:08 +00004375 // Do the lookup again to determine if this is a "nothing found" case or
4376 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
4377 // need to do this.
4378 DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004379 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
Richard Smith79810042018-05-11 02:43:08 +00004380 LookupOrdinaryName);
4381 bool MOUS;
4382 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext,
Richard Smithafcfb6b2019-02-15 21:53:07 +00004383 MOUS, TemplateKWLoc) && !R.isAmbiguous())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004384 Diag(Name.getBeginLoc(), diag::err_no_member)
Richard Smith79810042018-05-11 02:43:08 +00004385 << DNI.getName() << LookupCtx << SS.getRange();
Douglas Gregorbb119652010-06-16 23:00:59 +00004386 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00004387 } else {
4388 // We found something; return it.
Richard Smithfd3dae02017-01-20 00:20:39 +00004389 auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
4390 if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
Faisal Vali2ab8c152017-12-30 04:15:27 +00004391 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4392 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
Richard Smithfd3dae02017-01-20 00:20:39 +00004393 // C++14 [class.qual]p2:
4394 // In a lookup in which function names are not ignored and the
4395 // nested-name-specifier nominates a class C, if the name specified
4396 // [...] is the injected-class-name of C, [...] the name is instead
4397 // considered to name the constructor
4398 //
4399 // We don't get here if naming the constructor would be valid, so we
4400 // just reject immediately and recover by treating the
4401 // injected-class-name as naming the template.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004402 Diag(Name.getBeginLoc(),
Richard Smithfd3dae02017-01-20 00:20:39 +00004403 diag::ext_out_of_line_qualified_id_type_names_constructor)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004404 << Name.Identifier
4405 << 0 /*injected-class-name used as template name*/
4406 << 1 /*'template' keyword was used*/;
Richard Smithfd3dae02017-01-20 00:20:39 +00004407 }
Douglas Gregorbb119652010-06-16 23:00:59 +00004408 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00004409 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00004410 }
4411
Aaron Ballman4a979672014-01-03 13:56:08 +00004412 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004413
Douglas Gregor3cf81312009-11-03 23:16:33 +00004414 switch (Name.getKind()) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00004415 case UnqualifiedIdKind::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004416 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00004417 Name.Identifier));
4418 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004419
Faisal Vali2ab8c152017-12-30 04:15:27 +00004420 case UnqualifiedIdKind::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00004421 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00004422 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00004423 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00004424
Faisal Vali2ab8c152017-12-30 04:15:27 +00004425 case UnqualifiedIdKind::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00004426 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00004427
Douglas Gregor3cf81312009-11-03 23:16:33 +00004428 default:
4429 break;
4430 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004431
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004432 Diag(Name.getBeginLoc(), diag::err_template_kw_refers_to_non_template)
4433 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
4434 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00004435 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00004436}
4437
Mike Stump11289f42009-09-09 15:08:12 +00004438bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00004439 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004440 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00004441 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00004442 QualType ArgType;
4443 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00004444
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004445 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004446 switch(Arg.getKind()) {
4447 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004448 // C++ [temp.arg.type]p1:
4449 // A template-argument for a template-parameter which is a
4450 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00004451 ArgType = Arg.getAsType();
4452 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004453 break;
Richard Smith77a9c602018-02-28 03:02:23 +00004454 case TemplateArgument::Template:
4455 case TemplateArgument::TemplateExpansion: {
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004456 // We have a template type parameter but the template argument
4457 // is a template without any arguments.
4458 SourceRange SR = AL.getSourceRange();
Richard Smith77a9c602018-02-28 03:02:23 +00004459 TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
Richard Smithecad88d2018-04-26 01:08:00 +00004460 diagnoseMissingTemplateArguments(Name, SR.getEnd());
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004461 return true;
4462 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004463 case TemplateArgument::Expression: {
4464 // We have a template type parameter but the template argument is an
4465 // expression; see if maybe it is missing the "typename" keyword.
4466 CXXScopeSpec SS;
4467 DeclarationNameInfo NameInfo;
4468
4469 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
4470 SS.Adopt(ArgExpr->getQualifierLoc());
4471 NameInfo = ArgExpr->getNameInfo();
4472 } else if (DependentScopeDeclRefExpr *ArgExpr =
4473 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4474 SS.Adopt(ArgExpr->getQualifierLoc());
4475 NameInfo = ArgExpr->getNameInfo();
4476 } else if (CXXDependentScopeMemberExpr *ArgExpr =
4477 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00004478 if (ArgExpr->isImplicitAccess()) {
4479 SS.Adopt(ArgExpr->getQualifierLoc());
4480 NameInfo = ArgExpr->getMemberNameInfo();
4481 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004482 }
4483
Reid Kleckner377c1592014-06-10 23:29:48 +00004484 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004485 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4486 LookupParsedName(Result, CurScope, &SS);
4487
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00004488 if (Result.getAsSingle<TypeDecl>() ||
4489 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00004490 LookupResult::NotFoundInCurrentInstantiation) {
4491 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004492 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00004493 Diag(Loc, getLangOpts().MSVCCompat
4494 ? diag::ext_ms_template_type_arg_missing_typename
4495 : diag::err_template_arg_must_be_type_suggest)
4496 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004497 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00004498
4499 // Recover by synthesizing a type using the location information that we
4500 // already have.
4501 ArgType =
4502 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
4503 TypeLocBuilder TLB;
4504 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
4505 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4506 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4507 TL.setNameLoc(NameInfo.getLoc());
4508 TSI = TLB.getTypeSourceInfo(Context, ArgType);
4509
4510 // Overwrite our input TemplateArgumentLoc so that we can recover
4511 // properly.
4512 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
4513 TemplateArgumentLocInfo(TSI));
4514
4515 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004516 }
4517 }
4518 // fallthrough
Galina Kistanova3779cb32017-06-07 06:25:05 +00004519 LLVM_FALLTHROUGH;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00004520 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004521 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004522 // We have a template type parameter but the template argument
4523 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00004524 SourceRange SR = AL.getSourceRange();
4525 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004526 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00004527
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004528 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004529 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00004530 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004531
Reid Kleckner377c1592014-06-10 23:29:48 +00004532 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004533 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004534
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004535 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00004536 ArgType = Context.getCanonicalType(ArgType);
Simon Pilgrim6905d222016-12-30 22:55:33 +00004537
Douglas Gregore46db902011-06-17 22:11:49 +00004538 // Objective-C ARC:
4539 // If an explicitly-specified template argument type is a lifetime type
4540 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004541 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00004542 ArgType->isObjCLifetimeType() &&
4543 !ArgType.getObjCLifetime()) {
4544 Qualifiers Qs;
4545 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
4546 ArgType = Context.getQualifiedType(ArgType, Qs);
4547 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00004548
Douglas Gregore46db902011-06-17 22:11:49 +00004549 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00004550 return false;
4551}
4552
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004553/// Substitute template arguments into the default template argument for
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004554/// the given template type parameter.
4555///
4556/// \param SemaRef the semantic analysis object for which we are performing
4557/// the substitution.
4558///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004559/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004560/// for.
4561///
4562/// \param TemplateLoc the location of the template name that started the
4563/// template-id we are checking.
4564///
4565/// \param RAngleLoc the location of the right angle bracket ('>') that
4566/// terminates the template-id.
4567///
4568/// \param Param the template template parameter whose default we are
4569/// substituting into.
4570///
4571/// \param Converted the list of template arguments provided for template
4572/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004573/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00004574static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004575SubstDefaultTemplateArgument(Sema &SemaRef,
4576 TemplateDecl *Template,
4577 SourceLocation TemplateLoc,
4578 SourceLocation RAngleLoc,
4579 TemplateTypeParmDecl *Param,
Vassil Vassilev2999d0e2017-01-10 09:09:09 +00004580 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00004581 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004582
4583 // If the argument type is dependent, instantiate it now based
4584 // on the previously-computed template arguments.
Erik Pilkingtonba88e212018-11-12 21:31:06 +00004585 if (ArgType->getType()->isInstantiationDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004586 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00004587 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004588 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004589 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00004590 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004591
David Majnemer8b622692016-07-03 21:17:51 +00004592 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004593
4594 // Only substitute for the innermost template argument list.
4595 MultiLevelTemplateArgumentList TemplateArgLists;
4596 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4597 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4598 TemplateArgLists.addOuterTemplateArguments(None);
4599
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00004600 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00004601 ArgType =
4602 SemaRef.SubstType(ArgType, TemplateArgLists,
4603 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004604 }
4605
4606 return ArgType;
4607}
4608
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004609/// Substitute template arguments into the default template argument for
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004610/// the given non-type template parameter.
4611///
4612/// \param SemaRef the semantic analysis object for which we are performing
4613/// the substitution.
4614///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004615/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004616/// for.
4617///
4618/// \param TemplateLoc the location of the template name that started the
4619/// template-id we are checking.
4620///
4621/// \param RAngleLoc the location of the right angle bracket ('>') that
4622/// terminates the template-id.
4623///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004624/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004625/// substituting into.
4626///
4627/// \param Converted the list of template arguments provided for template
4628/// parameters that precede \p Param in the template parameter list.
4629///
4630/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00004631static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004632SubstDefaultTemplateArgument(Sema &SemaRef,
4633 TemplateDecl *Template,
4634 SourceLocation TemplateLoc,
4635 SourceLocation RAngleLoc,
4636 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004637 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004638 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00004639 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004640 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004641 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004642 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004643
David Majnemer8b622692016-07-03 21:17:51 +00004644 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004645
4646 // Only substitute for the innermost template argument list.
4647 MultiLevelTemplateArgumentList TemplateArgLists;
4648 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4649 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4650 TemplateArgLists.addOuterTemplateArguments(None);
4651
Faisal Valid143a0c2017-04-01 21:30:49 +00004652 EnterExpressionEvaluationContext ConstantEvaluated(
4653 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00004654 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00004655}
4656
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004657/// Substitute template arguments into the default template argument for
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004658/// the given template template parameter.
4659///
4660/// \param SemaRef the semantic analysis object for which we are performing
4661/// the substitution.
4662///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004663/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004664/// for.
4665///
4666/// \param TemplateLoc the location of the template name that started the
4667/// template-id we are checking.
4668///
4669/// \param RAngleLoc the location of the right angle bracket ('>') that
4670/// terminates the template-id.
4671///
4672/// \param Param the template template parameter whose default we are
4673/// substituting into.
4674///
4675/// \param Converted the list of template arguments provided for template
4676/// parameters that precede \p Param in the template parameter list.
4677///
Simon Pilgrim6905d222016-12-30 22:55:33 +00004678/// \param QualifierLoc Will be set to the nested-name-specifier (with
Douglas Gregordf846d12011-03-02 18:46:51 +00004679/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00004680///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004681/// \returns the substituted template argument, or NULL if an error occurred.
4682static TemplateName
4683SubstDefaultTemplateArgument(Sema &SemaRef,
4684 TemplateDecl *Template,
4685 SourceLocation TemplateLoc,
4686 SourceLocation RAngleLoc,
4687 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004688 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00004689 NestedNameSpecifierLoc &QualifierLoc) {
Richard Smith54f18e82016-08-31 02:15:21 +00004690 Sema::InstantiatingTemplate Inst(
4691 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
4692 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004693 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004694 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004695
David Majnemer8b622692016-07-03 21:17:51 +00004696 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00004697
4698 // Only substitute for the innermost template argument list.
4699 MultiLevelTemplateArgumentList TemplateArgLists;
4700 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4701 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4702 TemplateArgLists.addOuterTemplateArguments(None);
4703
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00004704 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00004705 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00004706 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00004707 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00004708 QualifierLoc =
4709 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00004710 if (!QualifierLoc)
4711 return TemplateName();
4712 }
David Majnemer89189202013-08-28 23:48:32 +00004713
4714 return SemaRef.SubstTemplateName(
4715 QualifierLoc,
4716 Param->getDefaultArgument().getArgument().getAsTemplate(),
4717 Param->getDefaultArgument().getTemplateNameLoc(),
4718 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004719}
4720
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004721/// If the given template parameter has a default template
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004722/// argument, substitute into that default template argument and
4723/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004724TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004725Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
4726 SourceLocation TemplateLoc,
4727 SourceLocation RAngleLoc,
4728 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00004729 SmallVectorImpl<TemplateArgument>
4730 &Converted,
4731 bool &HasDefaultArg) {
4732 HasDefaultArg = false;
4733
4734 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004735 if (!hasVisibleDefaultArgument(TypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004736 return TemplateArgumentLoc();
4737
Richard Smithc87b9382013-07-04 01:01:24 +00004738 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00004739 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004740 TemplateLoc,
4741 RAngleLoc,
4742 TypeParm,
4743 Converted);
4744 if (DI)
4745 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4746
4747 return TemplateArgumentLoc();
4748 }
4749
4750 if (NonTypeTemplateParmDecl *NonTypeParm
4751 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004752 if (!hasVisibleDefaultArgument(NonTypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004753 return TemplateArgumentLoc();
4754
Richard Smithc87b9382013-07-04 01:01:24 +00004755 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00004756 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00004757 TemplateLoc,
4758 RAngleLoc,
4759 NonTypeParm,
4760 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004761 if (Arg.isInvalid())
4762 return TemplateArgumentLoc();
4763
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004764 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004765 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
4766 }
4767
4768 TemplateTemplateParmDecl *TempTempParm
4769 = cast<TemplateTemplateParmDecl>(Param);
Richard Smith95d83952015-06-10 20:36:34 +00004770 if (!hasVisibleDefaultArgument(TempTempParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004771 return TemplateArgumentLoc();
4772
Richard Smithc87b9382013-07-04 01:01:24 +00004773 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00004774 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004775 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004776 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004777 RAngleLoc,
4778 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00004779 Converted,
4780 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004781 if (TName.isNull())
4782 return TemplateArgumentLoc();
4783
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004784 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00004785 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00004786 TempTempParm->getDefaultArgument().getTemplateNameLoc());
4787}
4788
Richard Smith11255ec2017-01-18 19:19:22 +00004789/// Convert a template-argument that we parsed as a type into a template, if
4790/// possible. C++ permits injected-class-names to perform dual service as
4791/// template template arguments and as template type arguments.
4792static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
4793 // Extract and step over any surrounding nested-name-specifier.
4794 NestedNameSpecifierLoc QualLoc;
4795 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4796 if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
4797 return TemplateArgumentLoc();
4798
4799 QualLoc = ETLoc.getQualifierLoc();
4800 TLoc = ETLoc.getNamedTypeLoc();
4801 }
4802
4803 // If this type was written as an injected-class-name, it can be used as a
4804 // template template argument.
4805 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4806 return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
4807 QualLoc, InjLoc.getNameLoc());
4808
4809 // If this type was written as an injected-class-name, it may have been
4810 // converted to a RecordType during instantiation. If the RecordType is
4811 // *not* wrapped in a TemplateSpecializationType and denotes a class
4812 // template specialization, it must have come from an injected-class-name.
4813 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
4814 if (auto *CTSD =
4815 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
4816 return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
4817 QualLoc, RecLoc.getNameLoc());
4818
4819 return TemplateArgumentLoc();
4820}
4821
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004822/// Check that the given template argument corresponds to the given
Douglas Gregorda0fb532009-11-11 19:31:23 +00004823/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004824///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004825/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004826/// checked.
4827///
Richard Trieu15b66532015-01-24 02:48:32 +00004828/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004829///
4830/// \param Template The template in which the template argument resides.
4831///
4832/// \param TemplateLoc The location of the template name for the template
4833/// whose argument list we're matching.
4834///
4835/// \param RAngleLoc The location of the right angle bracket ('>') that closes
4836/// the template argument list.
4837///
4838/// \param ArgumentPackIndex The index into the argument pack where this
4839/// argument will be placed. Only valid if the parameter is a parameter pack.
4840///
4841/// \param Converted The checked, converted argument will be added to the
4842/// end of this small vector.
4843///
4844/// \param CTAK Describes how we arrived at this particular template argument:
4845/// explicitly written, deduced, etc.
4846///
4847/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004848bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00004849 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00004850 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004851 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004852 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004853 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004854 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00004855 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00004856 // Check template type parameters.
4857 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004858 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004859
Douglas Gregoreebed722009-11-11 19:41:09 +00004860 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004861 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004862 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00004863 // with the template arguments we've seen thus far. But if the
4864 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00004865 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004866 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
4867 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004868
Richard Smith5d331022018-03-08 01:07:33 +00004869 // FIXME: Do we need to substitute into parameters here if they're
4870 // instantiation-dependent but not dependent?
Peter Collingbourne01687632010-12-10 17:08:53 +00004871 if (NTTPType->isDependentType() &&
4872 !isa<TemplateTemplateParmDecl>(Template) &&
4873 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004874 // Do substitution on the type of the non-type template parameter.
4875 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00004876 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00004877 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00004878 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004879 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004880
4881 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00004882 Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004883 NTTPType = SubstType(NTTPType,
4884 MultiLevelTemplateArgumentList(TemplateArgs),
4885 NTTP->getLocation(),
4886 NTTP->getDeclName());
4887 // If that worked, check the non-type template parameter type
4888 // for validity.
4889 if (!NTTPType.isNull())
4890 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
4891 NTTP->getLocation());
4892 if (NTTPType.isNull())
4893 return true;
4894 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004895
Douglas Gregorda0fb532009-11-11 19:31:23 +00004896 switch (Arg.getArgument().getKind()) {
4897 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00004898 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004899
Douglas Gregorda0fb532009-11-11 19:31:23 +00004900 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004901 TemplateArgument Result;
Erich Keanec90bb6d2018-05-07 17:05:20 +00004902 unsigned CurSFINAEErrors = NumSFINAEErrors;
John Wiegley01296292011-04-08 18:41:53 +00004903 ExprResult Res =
4904 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
4905 Result, CTAK);
4906 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00004907 return true;
Erich Keanec90bb6d2018-05-07 17:05:20 +00004908 // If the current template argument causes an error, give up now.
4909 if (CurSFINAEErrors < NumSFINAEErrors)
4910 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004911
Richard Trieu15b66532015-01-24 02:48:32 +00004912 // If the resulting expression is new, then use it in place of the
4913 // old expression in the template argument.
4914 if (Res.get() != Arg.getArgument().getAsExpr()) {
4915 TemplateArgument TA(Res.get());
4916 Arg = TemplateArgumentLoc(TA, Res.get());
4917 }
4918
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004919 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004920 break;
4921 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004922
Douglas Gregorda0fb532009-11-11 19:31:23 +00004923 case TemplateArgument::Declaration:
4924 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00004925 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00004926 // We've already checked this template argument, so just copy
4927 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004928 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00004929 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004930
Douglas Gregorda0fb532009-11-11 19:31:23 +00004931 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004932 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00004933 // We were given a template template argument. It may not be ill-formed;
4934 // see below.
4935 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004936 = Arg.getArgument().getAsTemplateOrTemplatePattern()
4937 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00004938 // We have a template argument such as \c T::template X, which we
4939 // parsed as a template template argument. However, since we now
4940 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004941 // template name into an expression.
4942
4943 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
4944 Arg.getTemplateNameLoc());
4945
Douglas Gregor3a43fd62011-02-25 20:49:16 +00004946 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00004947 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00004948 // FIXME: the template-template arg was a DependentTemplateName,
4949 // so it was provided with a template keyword. However, its source
4950 // location is not stored in the template argument structure.
4951 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004952 ExprResult E = DependentScopeDeclRefExpr::Create(
4953 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
4954 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004955
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004956 // If we parsed the template argument as a pack expansion, create a
4957 // pack expansion expression.
4958 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004959 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00004960 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004961 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004962 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004963
Douglas Gregorda0fb532009-11-11 19:31:23 +00004964 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004965 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00004966 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00004967 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004968
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004969 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00004970 break;
4971 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004972
Douglas Gregorda0fb532009-11-11 19:31:23 +00004973 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00004974 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00004975 // therefore cannot be a non-type template argument.
4976 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
4977 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004978
Douglas Gregorda0fb532009-11-11 19:31:23 +00004979 Diag(Param->getLocation(), diag::note_template_param_here);
4980 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004981
Douglas Gregorda0fb532009-11-11 19:31:23 +00004982 case TemplateArgument::Type: {
4983 // We have a non-type template parameter but the template
4984 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004985
Douglas Gregorda0fb532009-11-11 19:31:23 +00004986 // C++ [temp.arg]p2:
4987 // In a template-argument, an ambiguity between a type-id and
4988 // an expression is resolved to a type-id, regardless of the
4989 // form of the corresponding template-parameter.
4990 //
4991 // We warn specifically about this case, since it can be rather
4992 // confusing for users.
4993 QualType T = Arg.getArgument().getAsType();
4994 SourceRange SR = Arg.getSourceRange();
4995 if (T->isFunctionType())
4996 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
4997 else
4998 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
4999 Diag(Param->getLocation(), diag::note_template_param_here);
5000 return true;
5001 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005002
Douglas Gregorda0fb532009-11-11 19:31:23 +00005003 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005004 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00005005 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005006
Douglas Gregorda0fb532009-11-11 19:31:23 +00005007 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005008 }
5009
5010
Douglas Gregorda0fb532009-11-11 19:31:23 +00005011 // Check template template parameters.
5012 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005013
Richard Smith5d331022018-03-08 01:07:33 +00005014 TemplateParameterList *Params = TempParm->getTemplateParameters();
5015 if (TempParm->isExpandedParameterPack())
5016 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5017
Douglas Gregorda0fb532009-11-11 19:31:23 +00005018 // Substitute into the template parameter list of the template
5019 // template parameter, since previously-supplied template arguments
5020 // may appear within the template template parameter.
Richard Smith5d331022018-03-08 01:07:33 +00005021 //
5022 // FIXME: Skip this if the parameters aren't instantiation-dependent.
Douglas Gregorda0fb532009-11-11 19:31:23 +00005023 {
5024 // Set up a template instantiation context.
5025 LocalInstantiationScope Scope(*this);
5026 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00005027 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00005028 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00005029 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00005030 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005031
David Majnemer8b622692016-07-03 21:17:51 +00005032 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
Richard Smith5d331022018-03-08 01:07:33 +00005033 Params = SubstTemplateParams(Params, CurContext,
5034 MultiLevelTemplateArgumentList(TemplateArgs));
5035 if (!Params)
Douglas Gregorda0fb532009-11-11 19:31:23 +00005036 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00005037 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005038
Richard Smith11255ec2017-01-18 19:19:22 +00005039 // C++1z [temp.local]p1: (DR1004)
5040 // When [the injected-class-name] is used [...] as a template-argument for
5041 // a template template-parameter [...] it refers to the class template
5042 // itself.
5043 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
5044 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
5045 Arg.getTypeSourceInfo()->getTypeLoc());
5046 if (!ConvertedArg.getArgument().isNull())
5047 Arg = ConvertedArg;
5048 }
5049
Douglas Gregorda0fb532009-11-11 19:31:23 +00005050 switch (Arg.getArgument().getKind()) {
5051 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00005052 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005053
Douglas Gregorda0fb532009-11-11 19:31:23 +00005054 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005055 case TemplateArgument::TemplateExpansion:
Richard Smith5d331022018-03-08 01:07:33 +00005056 if (CheckTemplateTemplateArgument(Params, Arg))
Douglas Gregorda0fb532009-11-11 19:31:23 +00005057 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005058
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005059 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00005060 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005061
Douglas Gregorda0fb532009-11-11 19:31:23 +00005062 case TemplateArgument::Expression:
5063 case TemplateArgument::Type:
5064 // We have a template template parameter but the template
5065 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00005066 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005067 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00005068 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005069
Douglas Gregorda0fb532009-11-11 19:31:23 +00005070 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00005071 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00005072 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00005073 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00005074 case TemplateArgument::NullPtr:
5075 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005076
Douglas Gregorda0fb532009-11-11 19:31:23 +00005077 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005078 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00005079 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005080
Douglas Gregorda0fb532009-11-11 19:31:23 +00005081 return false;
5082}
5083
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005084/// Check whether the template parameter is a pack expansion, and if so,
Richard Smith1fde8ec2012-09-07 02:06:42 +00005085/// determine the number of parameters produced by that expansion. For instance:
5086///
5087/// \code
5088/// template<typename ...Ts> struct A {
5089/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
5090/// };
5091/// \endcode
5092///
5093/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
5094/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00005095static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00005096 if (NonTypeTemplateParmDecl *NTTP
5097 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5098 if (NTTP->isExpandedParameterPack())
5099 return NTTP->getNumExpansionTypes();
5100 }
5101
5102 if (TemplateTemplateParmDecl *TTP
5103 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
5104 if (TTP->isExpandedParameterPack())
5105 return TTP->getNumExpansionTemplateParameters();
5106 }
5107
David Blaikie7a30dc52013-02-21 01:47:18 +00005108 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00005109}
5110
Richard Smith35c1df52015-06-17 20:16:32 +00005111/// Diagnose a missing template argument.
5112template<typename TemplateParmDecl>
5113static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
5114 TemplateDecl *TD,
5115 const TemplateParmDecl *D,
5116 TemplateArgumentListInfo &Args) {
5117 // Dig out the most recent declaration of the template parameter; there may be
5118 // declarations of the template that are more recent than TD.
5119 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
5120 ->getTemplateParameters()
5121 ->getParam(D->getIndex()));
5122
5123 // If there's a default argument that's not visible, diagnose that we're
5124 // missing a module import.
5125 llvm::SmallVector<Module*, 8> Modules;
5126 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
5127 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
5128 D->getDefaultArgumentLoc(), Modules,
5129 Sema::MissingImportKind::DefaultArgument,
Richard Smith6739a102016-05-05 00:56:12 +00005130 /*Recover*/true);
Richard Smith35c1df52015-06-17 20:16:32 +00005131 return true;
5132 }
5133
5134 // FIXME: If there's a more recent default argument that *is* visible,
5135 // diagnose that it was declared too late.
5136
Richard Smith4a8f3512018-07-19 19:00:37 +00005137 TemplateParameterList *Params = TD->getTemplateParameters();
5138
5139 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5140 << /*not enough args*/0
5141 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD))
5142 << TD;
5143 S.Diag(TD->getLocation(), diag::note_template_decl_here)
5144 << Params->getSourceRange();
5145 return true;
Richard Smith35c1df52015-06-17 20:16:32 +00005146}
5147
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005148/// Check that the given template argument list is well-formed
Douglas Gregord32e0282009-02-09 23:23:08 +00005149/// for specializing the given template.
Richard Smith11255ec2017-01-18 19:19:22 +00005150bool Sema::CheckTemplateArgumentList(
5151 TemplateDecl *Template, SourceLocation TemplateLoc,
5152 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
5153 SmallVectorImpl<TemplateArgument> &Converted,
5154 bool UpdateArgsWithConversions) {
Richard Trieu15b66532015-01-24 02:48:32 +00005155 // Make a copy of the template arguments for processing. Only make the
5156 // changes at the end when successful in matching the arguments to the
5157 // template.
5158 TemplateArgumentListInfo NewArgs = TemplateArgs;
5159
Erich Keaneaf0795b2017-10-24 01:39:56 +00005160 // Make sure we get the template parameter list from the most
5161 // recentdeclaration, since that is the only one that has is guaranteed to
5162 // have all the default template argument information.
5163 TemplateParameterList *Params =
5164 cast<TemplateDecl>(Template->getMostRecentDecl())
5165 ->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00005166
Richard Trieu15b66532015-01-24 02:48:32 +00005167 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00005168
Mike Stump11289f42009-09-09 15:08:12 +00005169 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00005170 // [...] The type and form of each template-argument specified in
5171 // a template-id shall match the type and form specified for the
5172 // corresponding parameter declared by the template in its
5173 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00005174 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005175 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00005176 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00005177 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00005178 for (TemplateParameterList::iterator Param = Params->begin(),
5179 ParamEnd = Params->end();
5180 Param != ParamEnd; /* increment in loop */) {
5181 // If we have an expanded parameter pack, make sure we don't have too
5182 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00005183 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00005184 if (*Expansions == ArgumentPack.size()) {
5185 // We're done with this parameter pack. Pack up its arguments and add
5186 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00005187 Converted.push_back(
Benjamin Kramercce63472015-08-05 09:40:22 +00005188 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00005189 ArgumentPack.clear();
5190
Richard Smith1fde8ec2012-09-07 02:06:42 +00005191 // This argument is assigned to the next parameter.
5192 ++Param;
5193 continue;
5194 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5195 // Not enough arguments for this parameter pack.
5196 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
Richard Smith4a8f3512018-07-19 19:00:37 +00005197 << /*not enough args*/0
Richard Smith0c062b42017-01-14 02:19:59 +00005198 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
Richard Smith1fde8ec2012-09-07 02:06:42 +00005199 << Template;
5200 Diag(Template->getLocation(), diag::note_template_decl_here)
5201 << Params->getSourceRange();
5202 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00005203 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00005204 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005205
Richard Smith1fde8ec2012-09-07 02:06:42 +00005206 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00005207 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00005208 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005209 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00005210 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00005211 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005212
Richard Smith96d71c32014-11-12 23:38:38 +00005213 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00005214 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00005215 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
5216 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00005217 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00005218 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00005219 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00005220 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00005221 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00005222 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00005223 Diag((*Param)->getLocation(), diag::note_template_param_here);
5224 return true;
5225 }
5226
Richard Smith1fde8ec2012-09-07 02:06:42 +00005227 // We're now done with this argument.
5228 ++ArgIdx;
5229
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005230 if ((*Param)->isTemplateParameterPack()) {
5231 // The template parameter was a template parameter pack, so take the
5232 // deduced argument and place it on the argument pack. Note that we
5233 // stay on the same template parameter so that we can deduce more
5234 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00005235 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005236 } else {
5237 // Move to the next template parameter.
5238 ++Param;
5239 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00005240
Richard Smith96d71c32014-11-12 23:38:38 +00005241 // If we just saw a pack expansion into a non-pack, then directly convert
5242 // the remaining arguments, because we don't know what parameters they'll
5243 // match up with.
5244 if (PackExpansionIntoNonPack) {
5245 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00005246 // If we were part way through filling in an expanded parameter pack,
5247 // fall back to just producing individual arguments.
5248 Converted.insert(Converted.end(),
5249 ArgumentPack.begin(), ArgumentPack.end());
5250 ArgumentPack.clear();
5251 }
5252
5253 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00005254 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00005255 ++ArgIdx;
5256 }
5257
Richard Smith1fde8ec2012-09-07 02:06:42 +00005258 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00005259 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00005260
Douglas Gregor84d49a22009-11-11 21:54:23 +00005261 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005262 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005263
Douglas Gregor2f157c92011-06-03 02:59:40 +00005264 // If we're checking a partial template argument list, we're done.
5265 if (PartialTemplateArgs) {
5266 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
Benjamin Kramercce63472015-08-05 09:40:22 +00005267 Converted.push_back(
5268 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5269
Richard Smith1fde8ec2012-09-07 02:06:42 +00005270 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00005271 }
5272
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005273 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005274 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00005275 if ((*Param)->isTemplateParameterPack()) {
5276 assert(!getExpandedPackSize(*Param) &&
5277 "Should have dealt with this already");
5278
5279 // A non-expanded parameter pack before the end of the parameter list
5280 // only occurs for an ill-formed template parameter list, unless we've
5281 // got a partial argument list for a function template, so just bail out.
5282 if (Param + 1 != ParamEnd)
5283 return true;
5284
Benjamin Kramercce63472015-08-05 09:40:22 +00005285 Converted.push_back(
5286 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00005287 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00005288
5289 ++Param;
5290 continue;
5291 }
5292
Douglas Gregor8e072612012-02-03 07:34:46 +00005293 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00005294 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005295
Douglas Gregor84d49a22009-11-11 21:54:23 +00005296 // Retrieve the default template argument from the template
5297 // parameter. For each kind of template parameter, we substitute the
5298 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005299 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00005300 // the default argument.
5301 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00005302 if (!hasVisibleDefaultArgument(TTP))
Richard Smith35c1df52015-06-17 20:16:32 +00005303 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
5304 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005305
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005306 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00005307 Template,
5308 TemplateLoc,
5309 RAngleLoc,
5310 TTP,
5311 Converted);
5312 if (!ArgType)
5313 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005314
Douglas Gregor84d49a22009-11-11 21:54:23 +00005315 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
5316 ArgType);
5317 } else if (NonTypeTemplateParmDecl *NTTP
5318 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00005319 if (!hasVisibleDefaultArgument(NTTP))
Richard Smith35c1df52015-06-17 20:16:32 +00005320 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
5321 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005322
John McCalldadc5752010-08-24 06:29:42 +00005323 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005324 TemplateLoc,
5325 RAngleLoc,
5326 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00005327 Converted);
5328 if (E.isInvalid())
5329 return true;
5330
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005331 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00005332 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
5333 } else {
5334 TemplateTemplateParmDecl *TempParm
5335 = cast<TemplateTemplateParmDecl>(*Param);
5336
Richard Smith95d83952015-06-10 20:36:34 +00005337 if (!hasVisibleDefaultArgument(TempParm))
Richard Smith35c1df52015-06-17 20:16:32 +00005338 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
5339 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005340
Douglas Gregordf846d12011-03-02 18:46:51 +00005341 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00005342 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005343 TemplateLoc,
5344 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00005345 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00005346 Converted,
5347 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00005348 if (Name.isNull())
5349 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005350
Douglas Gregor9d802122011-03-02 17:09:35 +00005351 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
5352 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00005353 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005354
Douglas Gregor84d49a22009-11-11 21:54:23 +00005355 // Introduce an instantiation record that describes where we are using
Richard Smith54f18e82016-08-31 02:15:21 +00005356 // the default template argument. We're not actually instantiating a
5357 // template here, we just create this object to put a note into the
5358 // context stack.
Alp Tokerd4a72d52013-10-08 08:09:04 +00005359 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
5360 SourceRange(TemplateLoc, RAngleLoc));
5361 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00005362 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005363
Douglas Gregor84d49a22009-11-11 21:54:23 +00005364 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00005365 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00005366 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00005367 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005368
Richard Trieu15b66532015-01-24 02:48:32 +00005369 // Core issue 150 (assumed resolution): if this is a template template
5370 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00005371 // template definition.
5372 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00005373 NewArgs.addArgument(Arg);
5374
Douglas Gregor9abeaf52010-12-20 16:57:52 +00005375 // Move to the next template parameter and argument.
5376 ++Param;
5377 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00005378 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005379
Richard Smith07f79912014-06-06 16:00:50 +00005380 // If we're performing a partial argument substitution, allow any trailing
5381 // pack expansions; they might be empty. This can happen even if
5382 // PartialTemplateArgs is false (the list of arguments is complete but
5383 // still dependent).
5384 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5385 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00005386 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
5387 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00005388 }
5389
Douglas Gregor8e072612012-02-03 07:34:46 +00005390 // If we have any leftover arguments, then there were too many arguments.
5391 // Complain and fail.
Richard Smith4a8f3512018-07-19 19:00:37 +00005392 if (ArgIdx < NumArgs) {
5393 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5394 << /*too many args*/1
5395 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5396 << Template
5397 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
5398 Diag(Template->getLocation(), diag::note_template_decl_here)
5399 << Params->getSourceRange();
5400 return true;
5401 }
Richard Trieu15b66532015-01-24 02:48:32 +00005402
5403 // No problems found with the new argument list, propagate changes back
5404 // to caller.
Richard Smith11255ec2017-01-18 19:19:22 +00005405 if (UpdateArgsWithConversions)
5406 TemplateArgs = std::move(NewArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005407
Richard Smith1fde8ec2012-09-07 02:06:42 +00005408 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00005409}
5410
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005411namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005412 class UnnamedLocalNoLinkageFinder
5413 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005414 {
5415 Sema &S;
5416 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005417
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005418 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005419
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005420 public:
5421 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5422
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005423 bool Visit(QualType T) {
Daniel Jasper5cad6852017-01-02 22:55:45 +00005424 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005425 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005426
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005427#define TYPE(Class, Parent) \
5428 bool Visit##Class##Type(const Class##Type *);
5429#define ABSTRACT_TYPE(Class, Parent) \
5430 bool Visit##Class##Type(const Class##Type *) { return false; }
5431#define NON_CANONICAL_TYPE(Class, Parent) \
5432 bool Visit##Class##Type(const Class##Type *) { return false; }
5433#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005434
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005435 bool VisitTagDecl(const TagDecl *Tag);
5436 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5437 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005438} // end anonymous namespace
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005439
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005440bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005441 return false;
5442}
5443
5444bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5445 return Visit(T->getElementType());
5446}
5447
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005448bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005449 return Visit(T->getPointeeType());
5450}
5451
5452bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005453 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005454 return Visit(T->getPointeeType());
5455}
5456
5457bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005458 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005459 return Visit(T->getPointeeType());
5460}
5461
5462bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005463 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005464 return Visit(T->getPointeeType());
5465}
5466
5467bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005468 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005469 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5470}
5471
5472bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005473 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005474 return Visit(T->getElementType());
5475}
5476
5477bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005478 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005479 return Visit(T->getElementType());
5480}
5481
5482bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005483 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005484 return Visit(T->getElementType());
5485}
5486
5487bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005488 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005489 return Visit(T->getElementType());
5490}
5491
5492bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005493 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005494 return Visit(T->getElementType());
5495}
5496
Andrew Gozillon572bbb02017-10-02 06:25:51 +00005497bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
5498 const DependentAddressSpaceType *T) {
5499 return Visit(T->getPointeeType());
5500}
5501
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005502bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5503 return Visit(T->getElementType());
5504}
5505
Erich Keanef702b022018-07-13 19:46:04 +00005506bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
5507 const DependentVectorType *T) {
5508 return Visit(T->getElementType());
5509}
5510
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005511bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5512 return Visit(T->getElementType());
5513}
5514
5515bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5516 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005517 for (const auto &A : T->param_types()) {
5518 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005519 return true;
5520 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005521
Alp Toker314cc812014-01-25 16:55:45 +00005522 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005523}
5524
5525bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5526 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00005527 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005528}
5529
5530bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5531 const UnresolvedUsingType*) {
5532 return false;
5533}
5534
5535bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5536 return false;
5537}
5538
5539bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5540 return Visit(T->getUnderlyingType());
5541}
5542
5543bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5544 return false;
5545}
5546
Alexis Hunte852b102011-05-24 22:41:36 +00005547bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5548 const UnaryTransformType*) {
5549 return false;
5550}
5551
Richard Smith30482bc2011-02-20 03:19:35 +00005552bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5553 return Visit(T->getDeducedType());
5554}
5555
Richard Smith600b5262017-01-26 20:40:47 +00005556bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5557 const DeducedTemplateSpecializationType *T) {
5558 return Visit(T->getDeducedType());
5559}
5560
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005561bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5562 return VisitTagDecl(T->getDecl());
5563}
5564
5565bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5566 return VisitTagDecl(T->getDecl());
5567}
5568
5569bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5570 const TemplateTypeParmType*) {
5571 return false;
5572}
5573
Douglas Gregorada4b792011-01-14 02:55:32 +00005574bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5575 const SubstTemplateTypeParmPackType *) {
5576 return false;
5577}
5578
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005579bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
5580 const TemplateSpecializationType*) {
5581 return false;
5582}
5583
5584bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
5585 const InjectedClassNameType* T) {
5586 return VisitTagDecl(T->getDecl());
5587}
5588
5589bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
5590 const DependentNameType* T) {
5591 return VisitNestedNameSpecifier(T->getQualifier());
5592}
5593
5594bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
5595 const DependentTemplateSpecializationType* T) {
5596 return VisitNestedNameSpecifier(T->getQualifier());
5597}
5598
Douglas Gregord2fa7662010-12-20 02:24:11 +00005599bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
5600 const PackExpansionType* T) {
5601 return Visit(T->getPattern());
5602}
5603
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005604bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5605 return false;
5606}
5607
5608bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
5609 const ObjCInterfaceType *) {
5610 return false;
5611}
5612
5613bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
5614 const ObjCObjectPointerType *) {
5615 return false;
5616}
5617
Eli Friedman0dfb8892011-10-06 23:00:33 +00005618bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
5619 return Visit(T->getValueType());
5620}
5621
Xiuli Pan9c14e282016-01-09 12:53:17 +00005622bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
5623 return false;
5624}
5625
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005626bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
5627 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005628 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005629 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00005630 diag::warn_cxx98_compat_template_arg_local_type :
5631 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005632 << S.Context.getTypeDeclType(Tag) << SR;
5633 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005634 }
5635
John McCall5ea95772013-03-09 00:54:27 +00005636 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005637 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005638 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00005639 diag::warn_cxx98_compat_template_arg_unnamed_type :
5640 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005641 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
5642 return true;
5643 }
5644
5645 return false;
5646}
5647
5648bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5649 NestedNameSpecifier *NNS) {
5650 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5651 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005652
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005653 switch (NNS->getKind()) {
5654 case NestedNameSpecifier::Identifier:
5655 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005656 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005657 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00005658 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005659 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005660
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005661 case NestedNameSpecifier::TypeSpec:
5662 case NestedNameSpecifier::TypeSpecWithTemplate:
5663 return Visit(QualType(NNS->getAsType(), 0));
5664 }
David Blaikie8a40f702012-01-17 06:56:22 +00005665 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005666}
5667
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005668/// Check a template argument against its corresponding
Douglas Gregord32e0282009-02-09 23:23:08 +00005669/// template type parameter.
5670///
5671/// This routine implements the semantics of C++ [temp.arg.type]. It
5672/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005673bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00005674 TypeSourceInfo *ArgInfo) {
5675 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00005676 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00005677 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00005678
5679 if (Arg->isVariablyModifiedType()) {
5680 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005681 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005682 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00005683 }
5684
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005685 // C++03 [temp.arg.type]p2:
5686 // A local type, a type with no linkage, an unnamed type or a type
5687 // compounded from any of these types shall not be used as a
5688 // template-argument for a template type-parameter.
5689 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00005690 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005691 // a warning.
Daniel Jasper5cad6852017-01-02 22:55:45 +00005692 if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00005693 UnnamedLocalNoLinkageFinder Finder(*this, SR);
5694 (void)Finder.Visit(Context.getCanonicalType(Arg));
5695 }
5696
Douglas Gregord32e0282009-02-09 23:23:08 +00005697 return false;
5698}
5699
Douglas Gregor20fdef32012-04-10 17:08:25 +00005700enum NullPointerValueKind {
5701 NPV_NotNullPointer,
5702 NPV_NullPointer,
5703 NPV_Error
5704};
5705
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005706/// Determine whether the given template argument is a null pointer
Douglas Gregor20fdef32012-04-10 17:08:25 +00005707/// value of the appropriate type.
5708static NullPointerValueKind
5709isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
Reid Klecknercd016d82017-07-07 22:04:29 +00005710 QualType ParamType, Expr *Arg,
5711 Decl *Entity = nullptr) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00005712 if (Arg->isValueDependent() || Arg->isTypeDependent())
5713 return NPV_NotNullPointer;
David Majnemer69c3ddc2015-09-11 20:18:09 +00005714
Reid Klecknercd016d82017-07-07 22:04:29 +00005715 // dllimport'd entities aren't constant but are available inside of template
5716 // arguments.
5717 if (Entity && Entity->hasAttr<DLLImportAttr>())
5718 return NPV_NotNullPointer;
5719
Richard Smithdb0ac552015-12-18 22:40:25 +00005720 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
David Majnemerb54368c2015-09-11 20:55:29 +00005721 llvm_unreachable(
5722 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
David Majnemer69c3ddc2015-09-11 20:18:09 +00005723
David Majnemer5c734ad2014-08-14 00:49:23 +00005724 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00005725 return NPV_NotNullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005726
Douglas Gregor20fdef32012-04-10 17:08:25 +00005727 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00005728 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
5729 if (ArgRV.isInvalid())
5730 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005731 Arg = ArgRV.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005732
Douglas Gregor20fdef32012-04-10 17:08:25 +00005733 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005734 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00005735 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005736 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00005737 EvalResult.HasSideEffects) {
5738 SourceLocation DiagLoc = Arg->getExprLoc();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005739
Douglas Gregor350880c2012-04-10 19:03:30 +00005740 // If our only note is the usual "invalid subexpression" note, just point
5741 // the caret at its location rather than producing an essentially
5742 // redundant note.
5743 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5744 diag::note_invalid_subexpr_in_const_expr) {
5745 DiagLoc = Notes[0].first;
5746 Notes.clear();
5747 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005748
Douglas Gregor350880c2012-04-10 19:03:30 +00005749 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5750 << Arg->getType() << Arg->getSourceRange();
5751 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5752 S.Diag(Notes[I].first, Notes[I].second);
Simon Pilgrim6905d222016-12-30 22:55:33 +00005753
Douglas Gregor350880c2012-04-10 19:03:30 +00005754 S.Diag(Param->getLocation(), diag::note_template_param_here);
5755 return NPV_Error;
5756 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005757
Douglas Gregor20fdef32012-04-10 17:08:25 +00005758 // C++11 [temp.arg.nontype]p1:
5759 // - an address constant expression of type std::nullptr_t
5760 if (Arg->getType()->isNullPtrType())
5761 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005762
Douglas Gregor20fdef32012-04-10 17:08:25 +00005763 // - a constant expression that evaluates to a null pointer value (4.10); or
5764 // - a constant expression that evaluates to a null member pointer value
5765 // (4.11); or
5766 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
5767 (EvalResult.Val.isMemberPointer() &&
5768 !EvalResult.Val.getMemberPointerDecl())) {
5769 // If our expression has an appropriate type, we've succeeded.
5770 bool ObjCLifetimeConversion;
5771 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5772 S.IsQualificationConversion(Arg->getType(), ParamType, false,
5773 ObjCLifetimeConversion))
5774 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005775
Douglas Gregor20fdef32012-04-10 17:08:25 +00005776 // The types didn't match, but we know we got a null pointer; complain,
5777 // then recover as if the types were correct.
5778 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
5779 << Arg->getType() << ParamType << Arg->getSourceRange();
5780 S.Diag(Param->getLocation(), diag::note_template_param_here);
5781 return NPV_NullPointer;
5782 }
5783
5784 // If we don't have a null pointer value, but we do have a NULL pointer
5785 // constant, suggest a cast to the appropriate type.
5786 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
5787 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
5788 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005789 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005790 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getEndLoc()),
Alp Tokerb6cc5922014-05-03 03:45:55 +00005791 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00005792 S.Diag(Param->getLocation(), diag::note_template_param_here);
5793 return NPV_NullPointer;
5794 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005795
Douglas Gregor20fdef32012-04-10 17:08:25 +00005796 // FIXME: If we ever want to support general, address-constant expressions
5797 // as non-type template arguments, we should return the ExprResult here to
5798 // be interpreted by the caller.
5799 return NPV_NotNullPointer;
5800}
5801
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005802/// Checks whether the given template argument is compatible with its
David Majnemer61c39a12013-08-23 05:39:39 +00005803/// template parameter.
5804static bool CheckTemplateArgumentIsCompatibleWithParameter(
5805 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
5806 Expr *Arg, QualType ArgType) {
5807 bool ObjCLifetimeConversion;
5808 if (ParamType->isPointerType() &&
5809 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
5810 S.IsQualificationConversion(ArgType, ParamType, false,
5811 ObjCLifetimeConversion)) {
5812 // For pointer-to-object types, qualification conversions are
5813 // permitted.
5814 } else {
5815 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
5816 if (!ParamRef->getPointeeType()->isFunctionType()) {
5817 // C++ [temp.arg.nontype]p5b3:
5818 // For a non-type template-parameter of type reference to
5819 // object, no conversions apply. The type referred to by the
5820 // reference may be more cv-qualified than the (otherwise
5821 // identical) type of the template- argument. The
5822 // template-parameter is bound directly to the
5823 // template-argument, which shall be an lvalue.
5824
5825 // FIXME: Other qualifiers?
5826 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
5827 unsigned ArgQuals = ArgType.getCVRQualifiers();
5828
5829 if ((ParamQuals | ArgQuals) != ParamQuals) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005830 S.Diag(Arg->getBeginLoc(),
David Majnemer61c39a12013-08-23 05:39:39 +00005831 diag::err_template_arg_ref_bind_ignores_quals)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005832 << ParamType << Arg->getType() << Arg->getSourceRange();
David Majnemer61c39a12013-08-23 05:39:39 +00005833 S.Diag(Param->getLocation(), diag::note_template_param_here);
5834 return true;
5835 }
5836 }
5837 }
5838
5839 // At this point, the template argument refers to an object or
5840 // function with external linkage. We now need to check whether the
5841 // argument and parameter types are compatible.
5842 if (!S.Context.hasSameUnqualifiedType(ArgType,
5843 ParamType.getNonReferenceType())) {
5844 // We can't perform this conversion or binding.
5845 if (ParamType->isReferenceType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005846 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
5847 << ParamType << ArgIn->getType() << Arg->getSourceRange();
David Majnemer61c39a12013-08-23 05:39:39 +00005848 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005849 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
5850 << ArgIn->getType() << ParamType << Arg->getSourceRange();
David Majnemer61c39a12013-08-23 05:39:39 +00005851 S.Diag(Param->getLocation(), diag::note_template_param_here);
5852 return true;
5853 }
5854 }
5855
5856 return false;
5857}
5858
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005859/// Checks whether the given template argument is the address
Douglas Gregorccb07762009-02-11 19:52:55 +00005860/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005861static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00005862CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
5863 NonTypeTemplateParmDecl *Param,
5864 QualType ParamType,
5865 Expr *ArgIn,
5866 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005867 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005868 Expr *Arg = ArgIn;
5869 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00005870
Douglas Gregorb242683d2010-04-01 18:32:35 +00005871 bool AddressTaken = false;
5872 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00005873 if (S.getLangOpts().MicrosoftExt) {
5874 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
5875 // dereference and address-of operators.
5876 Arg = Arg->IgnoreParenCasts();
5877
5878 bool ExtWarnMSTemplateArg = false;
5879 UnaryOperatorKind FirstOpKind;
5880 SourceLocation FirstOpLoc;
5881 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5882 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
5883 if (UnOpKind == UO_Deref)
5884 ExtWarnMSTemplateArg = true;
5885 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
5886 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
5887 if (!AddrOpLoc.isValid()) {
5888 FirstOpKind = UnOpKind;
5889 FirstOpLoc = UnOp->getOperatorLoc();
5890 }
5891 } else
5892 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005893 }
David Majnemer61c39a12013-08-23 05:39:39 +00005894 if (FirstOpLoc.isValid()) {
5895 if (ExtWarnMSTemplateArg)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005896 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
5897 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00005898
David Majnemer61c39a12013-08-23 05:39:39 +00005899 if (FirstOpKind == UO_AddrOf)
5900 AddressTaken = true;
5901 else if (Arg->getType()->isPointerType()) {
5902 // We cannot let pointers get dereferenced here, that is obviously not a
5903 // constant expression.
5904 assert(FirstOpKind == UO_Deref);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005905 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
5906 << Arg->getSourceRange();
David Majnemer61c39a12013-08-23 05:39:39 +00005907 }
5908 }
5909 } else {
5910 // See through any implicit casts we added to fix the type.
5911 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00005912
David Majnemer61c39a12013-08-23 05:39:39 +00005913 // C++ [temp.arg.nontype]p1:
5914 //
5915 // A template-argument for a non-type, non-template
5916 // template-parameter shall be one of: [...]
5917 //
5918 // -- the address of an object or function with external
5919 // linkage, including function templates and function
5920 // template-ids but excluding non-static class members,
5921 // expressed as & id-expression where the & is optional if
5922 // the name refers to a function or array, or if the
5923 // corresponding template-parameter is a reference; or
5924
5925 // In C++98/03 mode, give an extension warning on any extra parentheses.
5926 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5927 bool ExtraParens = false;
5928 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5929 if (!Invalid && !ExtraParens) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005930 S.Diag(Arg->getBeginLoc(),
David Majnemer61c39a12013-08-23 05:39:39 +00005931 S.getLangOpts().CPlusPlus11
5932 ? diag::warn_cxx98_compat_template_arg_extra_parens
5933 : diag::ext_template_arg_extra_parens)
5934 << Arg->getSourceRange();
5935 ExtraParens = true;
5936 }
5937
5938 Arg = Parens->getSubExpr();
5939 }
5940
5941 while (SubstNonTypeTemplateParmExpr *subst =
5942 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5943 Arg = subst->getReplacement()->IgnoreImpCasts();
5944
5945 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5946 if (UnOp->getOpcode() == UO_AddrOf) {
5947 Arg = UnOp->getSubExpr();
5948 AddressTaken = true;
5949 AddrOpLoc = UnOp->getOperatorLoc();
5950 }
5951 }
5952
5953 while (SubstNonTypeTemplateParmExpr *subst =
5954 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5955 Arg = subst->getReplacement()->IgnoreImpCasts();
5956 }
John McCall7c454bb2011-07-15 05:09:51 +00005957
David Majnemer07910d62014-06-26 07:48:46 +00005958 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
5959 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5960
5961 // If our parameter has pointer type, check for a null template value.
5962 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
Reid Klecknercd016d82017-07-07 22:04:29 +00005963 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
5964 Entity)) {
David Majnemer07910d62014-06-26 07:48:46 +00005965 case NPV_NullPointer:
5966 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005967 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5968 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00005969 return false;
5970
5971 case NPV_Error:
5972 return true;
5973
5974 case NPV_NotNullPointer:
5975 break;
5976 }
5977 }
5978
Chandler Carruth724a8a12010-01-31 10:01:20 +00005979 // Stop checking the precise nature of the argument if it is value dependent,
5980 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00005981 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005982 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00005983 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005984 }
David Majnemer61c39a12013-08-23 05:39:39 +00005985
5986 if (isa<CXXUuidofExpr>(Arg)) {
5987 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
5988 ArgIn, Arg, ArgType))
5989 return true;
5990
5991 Converted = TemplateArgument(ArgIn);
5992 return false;
5993 }
5994
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005995 if (!DRE) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005996 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
5997 << Arg->getSourceRange();
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005998 S.Diag(Param->getLocation(), diag::note_template_param_here);
5999 return true;
6000 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00006001
Douglas Gregorccb07762009-02-11 19:52:55 +00006002 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00006003 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006004 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6005 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006006 S.Diag(Param->getLocation(), diag::note_template_param_here);
6007 return true;
6008 }
Douglas Gregorccb07762009-02-11 19:52:55 +00006009
6010 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00006011 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006012 if (!Method->isStatic()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006013 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6014 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006015 S.Diag(Param->getLocation(), diag::note_template_param_here);
6016 return true;
6017 }
Richard Smith9380e0e2012-04-04 21:11:30 +00006018 }
Mike Stump11289f42009-09-09 15:08:12 +00006019
Richard Smith9380e0e2012-04-04 21:11:30 +00006020 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6021 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00006022
Richard Smith9380e0e2012-04-04 21:11:30 +00006023 // A non-type template argument must refer to an object or function.
6024 if (!Func && !Var) {
6025 // We found something, but we don't know specifically what it is.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006026 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6027 << Arg->getSourceRange();
Richard Smith9380e0e2012-04-04 21:11:30 +00006028 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
6029 return true;
6030 }
Douglas Gregorccb07762009-02-11 19:52:55 +00006031
Richard Smith9380e0e2012-04-04 21:11:30 +00006032 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00006033 if (Entity->getFormalLinkage() == InternalLinkage) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006034 S.Diag(Arg->getBeginLoc(),
6035 S.getLangOpts().CPlusPlus11
6036 ? diag::warn_cxx98_compat_template_arg_object_internal
6037 : diag::ext_template_arg_object_internal)
6038 << !Func << Entity << Arg->getSourceRange();
Richard Smith9380e0e2012-04-04 21:11:30 +00006039 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6040 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00006041 } else if (!Entity->hasLinkage()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006042 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6043 << !Func << Entity << Arg->getSourceRange();
Richard Smith9380e0e2012-04-04 21:11:30 +00006044 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6045 << !Func;
6046 return true;
6047 }
6048
6049 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006050 // If the template parameter has pointer type, the function decays.
6051 if (ParamType->isPointerType() && !AddressTaken)
6052 ArgType = S.Context.getPointerType(Func->getType());
6053 else if (AddressTaken && ParamType->isReferenceType()) {
6054 // If we originally had an address-of operator, but the
6055 // parameter has reference type, complain and (if things look
6056 // like they will work) drop the address-of operator.
6057 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
6058 ParamType.getNonReferenceType())) {
6059 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6060 << ParamType;
6061 S.Diag(Param->getLocation(), diag::note_template_param_here);
6062 return true;
6063 }
6064
6065 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6066 << ParamType
6067 << FixItHint::CreateRemoval(AddrOpLoc);
6068 S.Diag(Param->getLocation(), diag::note_template_param_here);
6069
6070 ArgType = Func->getType();
6071 }
Richard Smith9380e0e2012-04-04 21:11:30 +00006072 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006073 // A value of reference type is not an object.
6074 if (Var->getType()->isReferenceType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006075 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6076 << Var->getType() << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006077 S.Diag(Param->getLocation(), diag::note_template_param_here);
6078 return true;
6079 }
6080
Richard Smith9380e0e2012-04-04 21:11:30 +00006081 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00006082 if (Var->getTLSKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006083 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6084 << Arg->getSourceRange();
Richard Smith9380e0e2012-04-04 21:11:30 +00006085 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6086 return true;
6087 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00006088
6089 // If the template parameter has pointer type, we must have taken
6090 // the address of this object.
6091 if (ParamType->isReferenceType()) {
6092 if (AddressTaken) {
6093 // If we originally had an address-of operator, but the
6094 // parameter has reference type, complain and (if things look
6095 // like they will work) drop the address-of operator.
6096 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
6097 ParamType.getNonReferenceType())) {
6098 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6099 << ParamType;
6100 S.Diag(Param->getLocation(), diag::note_template_param_here);
6101 return true;
6102 }
6103
6104 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6105 << ParamType
6106 << FixItHint::CreateRemoval(AddrOpLoc);
6107 S.Diag(Param->getLocation(), diag::note_template_param_here);
6108
6109 ArgType = Var->getType();
6110 }
6111 } else if (!AddressTaken && ParamType->isPointerType()) {
6112 if (Var->getType()->isArrayType()) {
6113 // Array-to-pointer decay.
6114 ArgType = S.Context.getArrayDecayedType(Var->getType());
6115 } else {
6116 // If the template parameter has pointer type but the address of
6117 // this object was not taken, complain and (possibly) recover by
6118 // taking the address of the entity.
6119 ArgType = S.Context.getPointerType(Var->getType());
6120 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006121 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6122 << ParamType;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006123 S.Diag(Param->getLocation(), diag::note_template_param_here);
6124 return true;
6125 }
6126
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006127 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6128 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
Douglas Gregorb242683d2010-04-01 18:32:35 +00006129
6130 S.Diag(Param->getLocation(), diag::note_template_param_here);
6131 }
6132 }
Douglas Gregorccb07762009-02-11 19:52:55 +00006133 }
Mike Stump11289f42009-09-09 15:08:12 +00006134
David Majnemer61c39a12013-08-23 05:39:39 +00006135 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6136 Arg, ArgType))
6137 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006138
6139 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00006140 Converted =
6141 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006142 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00006143 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00006144}
6145
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006146/// Checks whether the given template argument is a pointer to
Douglas Gregorccb07762009-02-11 19:52:55 +00006147/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00006148static bool CheckTemplateArgumentPointerToMember(Sema &S,
6149 NonTypeTemplateParmDecl *Param,
6150 QualType ParamType,
6151 Expr *&ResultArg,
6152 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00006153 bool Invalid = false;
6154
Douglas Gregor20fdef32012-04-10 17:08:25 +00006155 Expr *Arg = ResultArg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006156 bool ObjCLifetimeConversion;
Douglas Gregorccb07762009-02-11 19:52:55 +00006157
6158 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00006159 //
Douglas Gregorccb07762009-02-11 19:52:55 +00006160 // A template-argument for a non-type, non-template
6161 // template-parameter shall be one of: [...]
6162 //
6163 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00006164 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00006165
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00006166 // In C++98/03 mode, give an extension warning on any extra parentheses.
6167 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6168 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00006169 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00006170 if (!Invalid && !ExtraParens) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006171 S.Diag(Arg->getBeginLoc(),
6172 S.getLangOpts().CPlusPlus11
6173 ? diag::warn_cxx98_compat_template_arg_extra_parens
6174 : diag::ext_template_arg_extra_parens)
6175 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00006176 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00006177 }
6178
6179 Arg = Parens->getSubExpr();
6180 }
6181
John McCall7c454bb2011-07-15 05:09:51 +00006182 while (SubstNonTypeTemplateParmExpr *subst =
6183 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6184 Arg = subst->getReplacement()->IgnoreImpCasts();
6185
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006186 // A pointer-to-member constant written &Class::member.
6187 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00006188 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00006189 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
6190 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00006191 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00006192 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006193 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006194 // A constant of pointer-to-member type.
6195 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00006196 ValueDecl *VD = DRE->getDecl();
6197 if (VD->getType()->isMemberPointerType()) {
6198 if (isa<NonTypeTemplateParmDecl>(VD)) {
6199 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6200 Converted = TemplateArgument(Arg);
6201 } else {
6202 VD = cast<ValueDecl>(VD->getCanonicalDecl());
6203 Converted = TemplateArgument(VD, ParamType);
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006204 }
George Burgess IV00f70bd2018-03-01 05:43:23 +00006205 return Invalid;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006206 }
6207 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006208
Craig Topperc3ec1492014-05-26 06:22:03 +00006209 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00006210 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006211
Reid Klecknercd016d82017-07-07 22:04:29 +00006212 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6213
6214 // Check for a null pointer value.
6215 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
6216 Entity)) {
6217 case NPV_Error:
6218 return true;
6219 case NPV_NullPointer:
6220 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6221 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
6222 /*isNullPtr*/true);
6223 return false;
6224 case NPV_NotNullPointer:
6225 break;
6226 }
6227
6228 if (S.IsQualificationConversion(ResultArg->getType(),
6229 ParamType.getNonReferenceType(), false,
6230 ObjCLifetimeConversion)) {
6231 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
6232 ResultArg->getValueKind())
6233 .get();
6234 } else if (!S.Context.hasSameUnqualifiedType(
6235 ResultArg->getType(), ParamType.getNonReferenceType())) {
6236 // We can't perform this conversion.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006237 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
Reid Klecknercd016d82017-07-07 22:04:29 +00006238 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
6239 S.Diag(Param->getLocation(), diag::note_template_param_here);
6240 return true;
6241 }
6242
Douglas Gregorccb07762009-02-11 19:52:55 +00006243 if (!DRE)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006244 return S.Diag(Arg->getBeginLoc(),
Douglas Gregor20fdef32012-04-10 17:08:25 +00006245 diag::err_template_arg_not_pointer_to_member_form)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006246 << Arg->getSourceRange();
Douglas Gregorccb07762009-02-11 19:52:55 +00006247
David Majnemer3ac84e62013-10-22 21:56:38 +00006248 if (isa<FieldDecl>(DRE->getDecl()) ||
6249 isa<IndirectFieldDecl>(DRE->getDecl()) ||
6250 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00006251 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00006252 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00006253 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
6254 "Only non-static member pointers can make it here");
6255
6256 // Okay: this is the address of a non-static member, and therefore
6257 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00006258 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00006259 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00006260 } else {
6261 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00006262 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00006263 }
Douglas Gregorccb07762009-02-11 19:52:55 +00006264 return Invalid;
6265 }
6266
6267 // We found something else, but we don't know specifically what it is.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006268 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
6269 << Arg->getSourceRange();
Douglas Gregor20fdef32012-04-10 17:08:25 +00006270 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00006271 return true;
6272}
6273
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006274/// Check a template argument against its corresponding
Douglas Gregord32e0282009-02-09 23:23:08 +00006275/// non-type template parameter.
6276///
Douglas Gregor463421d2009-03-03 04:44:36 +00006277/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00006278/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00006279/// returns the converted template argument. \p ParamType is the
6280/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00006281ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00006282 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00006283 TemplateArgument &Converted,
6284 CheckTemplateArgumentKind CTAK) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006285 SourceLocation StartLoc = Arg->getBeginLoc();
Douglas Gregorc40290e2009-03-09 23:48:35 +00006286
Richard Smith5f274382016-09-28 23:55:27 +00006287 // If the parameter type somehow involves auto, deduce the type now.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00006288 if (getLangOpts().CPlusPlus17 && ParamType->isUndeducedType()) {
Richard Smith4ae5ec82017-02-22 20:01:55 +00006289 // During template argument deduction, we allow 'decltype(auto)' to
6290 // match an arbitrary dependent argument.
6291 // FIXME: The language rules don't say what happens in this case.
6292 // FIXME: We get an opaque dependent type out of decltype(auto) if the
6293 // expression is merely instantiation-dependent; is this enough?
6294 if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
6295 auto *AT = dyn_cast<AutoType>(ParamType);
6296 if (AT && AT->isDecltypeAuto()) {
6297 Converted = TemplateArgument(Arg);
6298 return Arg;
6299 }
6300 }
6301
Richard Smith87d263e2016-12-25 08:05:23 +00006302 // When checking a deduced template argument, deduce from its type even if
6303 // the type is dependent, in order to check the types of non-type template
6304 // arguments line up properly in partial ordering.
6305 Optional<unsigned> Depth;
6306 if (CTAK != CTAK_Specified)
6307 Depth = Param->getDepth() + 1;
Richard Smith5f274382016-09-28 23:55:27 +00006308 if (DeduceAutoType(
6309 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
Richard Smith87d263e2016-12-25 08:05:23 +00006310 Arg, ParamType, Depth) == DAR_Failed) {
Richard Smith5f274382016-09-28 23:55:27 +00006311 Diag(Arg->getExprLoc(),
6312 diag::err_non_type_template_parm_type_deduction_failure)
6313 << Param->getDeclName() << Param->getType() << Arg->getType()
6314 << Arg->getSourceRange();
6315 Diag(Param->getLocation(), diag::note_template_param_here);
6316 return ExprError();
6317 }
6318 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
6319 // an error. The error message normally references the parameter
6320 // declaration, but here we'll pass the argument location because that's
6321 // where the parameter type is deduced.
6322 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
6323 if (ParamType.isNull()) {
6324 Diag(Param->getLocation(), diag::note_template_param_here);
6325 return ExprError();
6326 }
6327 }
6328
Richard Smithd663fdd2014-12-17 20:42:37 +00006329 // We should have already dropped all cv-qualifiers by now.
6330 assert(!ParamType.hasQualifiers() &&
6331 "non-type template parameter type cannot be qualified");
6332
6333 if (CTAK == CTAK_Deduced &&
Richard Smithd92eddf2016-12-27 06:14:37 +00006334 !Context.hasSameType(ParamType.getNonLValueExprType(Context),
Richard Smith0e617ec2016-12-27 07:56:27 +00006335 Arg->getType())) {
Richard Smith957fbf12017-01-17 02:14:37 +00006336 // FIXME: If either type is dependent, we skip the check. This isn't
6337 // correct, since during deduction we're supposed to have replaced each
6338 // template parameter with some unique (non-dependent) placeholder.
6339 // FIXME: If the argument type contains 'auto', we carry on and fail the
6340 // type check in order to force specific types to be more specialized than
6341 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
6342 // work.
6343 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
6344 !Arg->getType()->getContainedAutoType()) {
6345 Converted = TemplateArgument(Arg);
6346 return Arg;
6347 }
6348 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
6349 // we should actually be checking the type of the template argument in P,
6350 // not the type of the template argument deduced from A, against the
6351 // template parameter type.
Richard Smithd663fdd2014-12-17 20:42:37 +00006352 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
Richard Smith0e617ec2016-12-27 07:56:27 +00006353 << Arg->getType()
Richard Smithd663fdd2014-12-17 20:42:37 +00006354 << ParamType.getUnqualifiedType();
6355 Diag(Param->getLocation(), diag::note_template_param_here);
6356 return ExprError();
6357 }
6358
Richard Smith87d263e2016-12-25 08:05:23 +00006359 // If either the parameter has a dependent type or the argument is
6360 // type-dependent, there's nothing we can check now.
6361 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
6362 // FIXME: Produce a cloned, canonical expression?
6363 Converted = TemplateArgument(Arg);
6364 return Arg;
6365 }
6366
Richard Smithe5945872017-01-06 22:52:53 +00006367 // The initialization of the parameter from the argument is
6368 // a constant-evaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006369 EnterExpressionEvaluationContext ConstantEvaluated(
6370 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Richard Smithe5945872017-01-06 22:52:53 +00006371
Aaron Ballmanc351fba2017-12-04 20:27:34 +00006372 if (getLangOpts().CPlusPlus17) {
6373 // C++17 [temp.arg.nontype]p1:
Richard Smith410cc892014-11-26 03:26:53 +00006374 // A template-argument for a non-type template parameter shall be
6375 // a converted constant expression of the type of the template-parameter.
6376 APValue Value;
6377 ExprResult ArgResult = CheckConvertedConstantExpression(
6378 Arg, ParamType, Value, CCEK_TemplateArg);
6379 if (ArgResult.isInvalid())
6380 return ExprError();
6381
Richard Smith52e624f2016-12-21 21:42:57 +00006382 // For a value-dependent argument, CheckConvertedConstantExpression is
6383 // permitted (and expected) to be unable to determine a value.
6384 if (ArgResult.get()->isValueDependent()) {
Richard Smith01bfa682016-12-27 02:02:09 +00006385 Converted = TemplateArgument(ArgResult.get());
6386 return ArgResult;
Richard Smith52e624f2016-12-21 21:42:57 +00006387 }
6388
Richard Smithd663fdd2014-12-17 20:42:37 +00006389 QualType CanonParamType = Context.getCanonicalType(ParamType);
6390
Richard Smith410cc892014-11-26 03:26:53 +00006391 // Convert the APValue to a TemplateArgument.
6392 switch (Value.getKind()) {
6393 case APValue::Uninitialized:
6394 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00006395 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00006396 break;
6397 case APValue::Int:
6398 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00006399 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00006400 break;
6401 case APValue::MemberPointer: {
6402 assert(ParamType->isMemberPointerType());
6403
6404 // FIXME: We need TemplateArgument representation and mangling for these.
6405 if (!Value.getMemberPointerPath().empty()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006406 Diag(Arg->getBeginLoc(),
Richard Smith410cc892014-11-26 03:26:53 +00006407 diag::err_template_arg_member_ptr_base_derived_not_supported)
6408 << Value.getMemberPointerDecl() << ParamType
6409 << Arg->getSourceRange();
6410 return ExprError();
6411 }
6412
6413 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00006414 Converted = VD ? TemplateArgument(VD, CanonParamType)
6415 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00006416 break;
6417 }
6418 case APValue::LValue: {
6419 // For a non-type template-parameter of pointer or reference type,
6420 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00006421 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
6422 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00006423 // -- a temporary object
6424 // -- a string literal
6425 // -- the result of a typeid expression, or
Eric Christopher0d2c56a2017-03-31 01:45:39 +00006426 // -- a predefined __func__ variable
Richard Smith410cc892014-11-26 03:26:53 +00006427 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
6428 if (isa<CXXUuidofExpr>(E)) {
Bill Wendlingff573072019-01-27 07:24:03 +00006429 Converted = TemplateArgument(ArgResult.get()->IgnoreImpCasts());
Richard Smith410cc892014-11-26 03:26:53 +00006430 break;
6431 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006432 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6433 << Arg->getSourceRange();
Richard Smith410cc892014-11-26 03:26:53 +00006434 return ExprError();
6435 }
6436 auto *VD = const_cast<ValueDecl *>(
6437 Value.getLValueBase().dyn_cast<const ValueDecl *>());
6438 // -- a subobject
6439 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
6440 VD && VD->getType()->isArrayType() &&
6441 Value.getLValuePath()[0].ArrayIndex == 0 &&
6442 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
6443 // Per defect report (no number yet):
6444 // ... other than a pointer to the first element of a complete array
6445 // object.
6446 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
6447 Value.isLValueOnePastTheEnd()) {
6448 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
6449 << Value.getAsString(Context, ParamType);
6450 return ExprError();
6451 }
Richard Smithd663fdd2014-12-17 20:42:37 +00006452 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00006453 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00006454 assert((!VD || !ParamType->isNullPtrType()) &&
6455 "non-null value of type nullptr_t?");
6456 Converted = VD ? TemplateArgument(VD, CanonParamType)
6457 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00006458 break;
6459 }
6460 case APValue::AddrLabelDiff:
6461 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
Leonard Chan86285d22019-01-16 18:53:05 +00006462 case APValue::FixedPoint:
Richard Smith410cc892014-11-26 03:26:53 +00006463 case APValue::Float:
6464 case APValue::ComplexInt:
6465 case APValue::ComplexFloat:
6466 case APValue::Vector:
6467 case APValue::Array:
6468 case APValue::Struct:
6469 case APValue::Union:
6470 llvm_unreachable("invalid kind for template argument");
6471 }
6472
6473 return ArgResult.get();
6474 }
6475
Douglas Gregor86560402009-02-10 23:36:10 +00006476 // C++ [temp.arg.nontype]p5:
6477 // The following conversions are performed on each expression used
6478 // as a non-type template-argument. If a non-type
6479 // template-argument cannot be converted to the type of the
6480 // corresponding template-parameter then the program is
6481 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00006482 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00006483 // C++11:
6484 // -- for a non-type template-parameter of integral or
6485 // enumeration type, conversions permitted in a converted
6486 // constant expression are applied.
6487 //
6488 // C++98:
6489 // -- for a non-type template-parameter of integral or
6490 // enumeration type, integral promotions (4.5) and integral
6491 // conversions (4.7) are applied.
6492
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006493 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00006494 // C++ [temp.arg.nontype]p1:
6495 // A template-argument for a non-type, non-template template-parameter
6496 // shall be one of:
6497 //
6498 // -- for a non-type template-parameter of integral or enumeration
6499 // type, a converted constant expression of the type of the
6500 // template-parameter; or
6501 llvm::APSInt Value;
6502 ExprResult ArgResult =
6503 CheckConvertedConstantExpression(Arg, ParamType, Value,
6504 CCEK_TemplateArg);
6505 if (ArgResult.isInvalid())
6506 return ExprError();
6507
Richard Smith01bfa682016-12-27 02:02:09 +00006508 // We can't check arbitrary value-dependent arguments.
6509 if (ArgResult.get()->isValueDependent()) {
6510 Converted = TemplateArgument(ArgResult.get());
6511 return ArgResult;
6512 }
6513
Richard Smithf8379a02012-01-18 23:55:52 +00006514 // Widen the argument value to sizeof(parameter type). This is almost
6515 // always a no-op, except when the parameter type is bool. In
6516 // that case, this may extend the argument from 1 bit to 8 bits.
6517 QualType IntegerType = ParamType;
6518 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6519 IntegerType = Enum->getDecl()->getIntegerType();
6520 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
6521
Benjamin Kramer6003ad52012-06-07 15:09:51 +00006522 Converted = TemplateArgument(Context, Value,
6523 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00006524 return ArgResult;
6525 }
6526
Richard Smith08b12f12011-10-27 22:11:44 +00006527 ExprResult ArgResult = DefaultLvalueConversion(Arg);
6528 if (ArgResult.isInvalid())
6529 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006530 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00006531
6532 QualType ArgType = Arg->getType();
6533
Douglas Gregor86560402009-02-10 23:36:10 +00006534 // C++ [temp.arg.nontype]p1:
6535 // A template-argument for a non-type, non-template
6536 // template-parameter shall be one of:
6537 //
6538 // -- an integral constant-expression of integral or enumeration
6539 // type; or
6540 // -- the name of a non-type template-parameter; or
Douglas Gregor264ec4f2009-02-17 01:05:43 +00006541 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00006542 if (!ArgType->isIntegralOrEnumerationType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006543 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
6544 << ArgType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00006545 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00006546 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00006547 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00006548 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
6549 QualType T;
Simon Pilgrim6905d222016-12-30 22:55:33 +00006550
Douglas Gregore2b37442012-05-04 22:38:52 +00006551 public:
6552 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00006553
6554 void diagnoseNotICE(Sema &S, SourceLocation Loc,
6555 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00006556 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
6557 }
6558 } Diagnoser(ArgType);
6559
6560 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006561 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00006562 if (!Arg)
6563 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00006564 }
6565
Richard Smithd663fdd2014-12-17 20:42:37 +00006566 // From here on out, all we care about is the unqualified form
6567 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006568 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00006569
6570 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00006571 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00006572 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00006573 } else if (ParamType->isBooleanType()) {
6574 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006575 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00006576 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
6577 !ParamType->isEnumeralType()) {
6578 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006579 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00006580 } else {
6581 // We can't perform this conversion.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006582 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6583 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00006584 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00006585 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00006586 }
6587
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006588 // Add the value of this argument to the list of converted
6589 // arguments. We use the bitwidth and signedness of the template
6590 // parameter.
6591 if (Arg->isValueDependent()) {
6592 // The argument is value-dependent. Create a new
6593 // TemplateArgument with the converted expression.
6594 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006595 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006596 }
6597
Douglas Gregor52aba872009-03-14 00:20:21 +00006598 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00006599 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00006600 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00006601
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006602 if (ParamType->isBooleanType()) {
6603 // Value must be zero or one.
6604 Value = Value != 0;
6605 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6606 if (Value.getBitWidth() != AllowedBits)
6607 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006608 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006609 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006610 llvm::APSInt OldValue = Value;
Simon Pilgrim6905d222016-12-30 22:55:33 +00006611
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006612 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006613 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00006614 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00006615 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006616 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006617 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Simon Pilgrim6905d222016-12-30 22:55:33 +00006618
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006619 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006620 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00006621 && (OldValue.isSigned() && OldValue.isNegative())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006622 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
6623 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6624 << Arg->getSourceRange();
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006625 Diag(Param->getLocation(), diag::note_template_param_here);
6626 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006627
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006628 // Complain if we overflowed the template parameter's type.
6629 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006630 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006631 RequiredBits = OldValue.getActiveBits();
6632 else if (OldValue.isUnsigned())
6633 RequiredBits = OldValue.getActiveBits() + 1;
6634 else
6635 RequiredBits = OldValue.getMinSignedBits();
6636 if (RequiredBits > AllowedBits) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006637 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
6638 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6639 << Arg->getSourceRange();
Douglas Gregorbb3d7862010-03-26 02:38:37 +00006640 Diag(Param->getLocation(), diag::note_template_param_here);
6641 }
Douglas Gregor52aba872009-03-14 00:20:21 +00006642 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00006643
Benjamin Kramer6003ad52012-06-07 15:09:51 +00006644 Converted = TemplateArgument(Context, Value,
Simon Pilgrim6905d222016-12-30 22:55:33 +00006645 ParamType->isEnumeralType()
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00006646 ? Context.getCanonicalType(ParamType)
6647 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006648 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00006649 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006650
Richard Smith08b12f12011-10-27 22:11:44 +00006651 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00006652 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
6653
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006654 // Handle pointer-to-function, reference-to-function, and
6655 // pointer-to-member-function all in (roughly) the same way.
6656 if (// -- For a non-type template-parameter of type pointer to
6657 // function, only the function-to-pointer conversion (4.3) is
6658 // applied. If the template-argument represents a set of
6659 // overloaded functions (or a pointer to such), the matching
6660 // function is selected from the set (13.4).
6661 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006662 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006663 // -- For a non-type template-parameter of type reference to
6664 // function, no conversions apply. If the template-argument
6665 // represents a set of overloaded functions, the matching
6666 // function is selected from the set (13.4).
6667 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006668 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006669 // -- For a non-type template-parameter of type pointer to
6670 // member function, no conversions apply. If the
6671 // template-argument represents a set of overloaded member
6672 // functions, the matching member function is selected from
6673 // the set (13.4).
6674 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006675 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006676 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006677
Douglas Gregor064fdb22010-04-14 23:11:21 +00006678 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006679 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00006680 true,
6681 FoundResult)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006682 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
John Wiegley01296292011-04-08 18:41:53 +00006683 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00006684
6685 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6686 ArgType = Arg->getType();
6687 } else
John Wiegley01296292011-04-08 18:41:53 +00006688 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006689 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006690
John Wiegley01296292011-04-08 18:41:53 +00006691 if (!ParamType->isMemberPointerType()) {
6692 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6693 ParamType,
6694 Arg, Converted))
6695 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006696 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00006697 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00006698
Douglas Gregor20fdef32012-04-10 17:08:25 +00006699 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6700 Converted))
John Wiegley01296292011-04-08 18:41:53 +00006701 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006702 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00006703 }
6704
Chris Lattner696197c2009-02-20 21:37:53 +00006705 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006706 // -- for a non-type template-parameter of type pointer to
6707 // object, qualification conversions (4.4) and the
6708 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00006709 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00006710 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006711 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00006712
John Wiegley01296292011-04-08 18:41:53 +00006713 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6714 ParamType,
6715 Arg, Converted))
6716 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006717 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00006718 }
Mike Stump11289f42009-09-09 15:08:12 +00006719
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006720 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006721 // -- For a non-type template-parameter of type reference to
6722 // object, no conversions apply. The type referred to by the
6723 // reference may be more cv-qualified than the (otherwise
6724 // identical) type of the template-argument. The
6725 // template-parameter is bound directly to the
6726 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00006727 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006728 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00006729
Douglas Gregor064fdb22010-04-14 23:11:21 +00006730 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006731 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
6732 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00006733 true,
6734 FoundResult)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006735 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
John Wiegley01296292011-04-08 18:41:53 +00006736 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00006737
6738 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6739 ArgType = Arg->getType();
6740 } else
John Wiegley01296292011-04-08 18:41:53 +00006741 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006742 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006743
John Wiegley01296292011-04-08 18:41:53 +00006744 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6745 ParamType,
6746 Arg, Converted))
6747 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006748 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006749 }
Douglas Gregor0e558532009-02-11 16:16:59 +00006750
Douglas Gregor20fdef32012-04-10 17:08:25 +00006751 // Deal with parameters of type std::nullptr_t.
6752 if (ParamType->isNullPtrType()) {
6753 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6754 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006755 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006756 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006757
Douglas Gregor20fdef32012-04-10 17:08:25 +00006758 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
6759 case NPV_NotNullPointer:
6760 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
6761 << Arg->getType() << ParamType;
6762 Diag(Param->getLocation(), diag::note_template_param_here);
6763 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00006764
Douglas Gregor20fdef32012-04-10 17:08:25 +00006765 case NPV_Error:
6766 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00006767
Douglas Gregor20fdef32012-04-10 17:08:25 +00006768 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00006769 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00006770 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
6771 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006772 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00006773 }
6774 }
6775
Douglas Gregor0e558532009-02-11 16:16:59 +00006776 // -- For a non-type template-parameter of type pointer to data
6777 // member, qualification conversions (4.4) are applied.
6778 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
6779
Douglas Gregor20fdef32012-04-10 17:08:25 +00006780 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6781 Converted))
John Wiegley01296292011-04-08 18:41:53 +00006782 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006783 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00006784}
6785
Richard Smith26b86ea2016-12-31 21:41:23 +00006786static void DiagnoseTemplateParameterListArityMismatch(
6787 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
6788 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
6789
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006790/// Check a template argument against its corresponding
Douglas Gregord32e0282009-02-09 23:23:08 +00006791/// template template parameter.
6792///
6793/// This routine implements the semantics of C++ [temp.arg.template].
6794/// It returns true if an error occurred, and false otherwise.
Richard Smith5d331022018-03-08 01:07:33 +00006795bool Sema::CheckTemplateTemplateArgument(TemplateParameterList *Params,
6796 TemplateArgumentLoc &Arg) {
Eli Friedmanb826a002012-09-26 02:36:12 +00006797 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006798 TemplateDecl *Template = Name.getAsTemplateDecl();
6799 if (!Template) {
6800 // Any dependent template name is fine.
6801 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
6802 return false;
6803 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00006804
Richard Smith26b86ea2016-12-31 21:41:23 +00006805 if (Template->isInvalidDecl())
6806 return true;
6807
Richard Smith3f1b5d02011-05-05 21:57:07 +00006808 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00006809 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00006810 // the name of a class template or an alias template, expressed as an
6811 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00006812 // primary class templates are considered when matching the
6813 // template template argument with the corresponding parameter;
6814 // partial specializations are not considered even if their
6815 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00006816 //
6817 // Note that we also allow template template parameters here, which
6818 // will happen when we are dealing with, e.g., class template
6819 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00006820 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00006821 !isa<TemplateTemplateParmDecl>(Template) &&
David Majnemerc2406d42016-07-11 17:09:56 +00006822 !isa<TypeAliasTemplateDecl>(Template) &&
6823 !isa<BuiltinTemplateDecl>(Template)) {
6824 assert(isa<FunctionTemplateDecl>(Template) &&
6825 "Only function templates are possible here");
Faisal Valib8b04f82016-03-26 20:46:45 +00006826 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
David Majnemerc2406d42016-07-11 17:09:56 +00006827 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
6828 << Template;
Douglas Gregor85e0f662009-02-10 00:24:35 +00006829 }
6830
Richard Smith26b86ea2016-12-31 21:41:23 +00006831 // C++1z [temp.arg.template]p3: (DR 150)
6832 // A template-argument matches a template template-parameter P when P
6833 // is at least as specialized as the template-argument A.
6834 if (getLangOpts().RelaxedTemplateTemplateArgs) {
6835 // Quick check for the common case:
6836 // If P contains a parameter pack, then A [...] matches P if each of A's
6837 // template parameters matches the corresponding template parameter in
6838 // the template-parameter-list of P.
6839 if (TemplateParameterListsAreEqual(
6840 Template->getTemplateParameters(), Params, false,
6841 TPL_TemplateTemplateArgumentMatch, Arg.getLocation()))
6842 return false;
6843
6844 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
6845 Arg.getLocation()))
6846 return false;
6847 // FIXME: Produce better diagnostics for deduction failures.
6848 }
6849
Douglas Gregor85e0f662009-02-10 00:24:35 +00006850 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00006851 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006852 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00006853 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006854 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00006855}
6856
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006857/// Given a non-type template argument that refers to a
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006858/// declaration and the type of its corresponding non-type template
6859/// parameter, produce an expression that properly refers to that
6860/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006861ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006862Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6863 QualType ParamType,
6864 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00006865 // C++ [temp.param]p8:
6866 //
6867 // A non-type template-parameter of type "array of T" or
6868 // "function returning T" is adjusted to be of type "pointer to
6869 // T" or "pointer to function returning T", respectively.
6870 if (ParamType->isArrayType())
6871 ParamType = Context.getArrayDecayedType(ParamType);
6872 else if (ParamType->isFunctionType())
6873 ParamType = Context.getPointerType(ParamType);
6874
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006875 // For a NULL non-type template argument, return nullptr casted to the
6876 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00006877 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00006878 return ImpCastExprToType(
6879 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
6880 ParamType,
6881 ParamType->getAs<MemberPointerType>()
6882 ? CK_NullToMemberPointer
6883 : CK_NullToPointer);
6884 }
Eli Friedmanb826a002012-09-26 02:36:12 +00006885 assert(Arg.getKind() == TemplateArgument::Declaration &&
6886 "Only declaration template arguments permitted here");
6887
George Burgess IV00f70bd2018-03-01 05:43:23 +00006888 ValueDecl *VD = Arg.getAsDecl();
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006889
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006890 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00006891 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
6892 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006893 // If the value is a class member, we might have a pointer-to-member.
6894 // Determine whether the non-type template template parameter is of
6895 // pointer-to-member type. If so, we need to build an appropriate
6896 // expression for a pointer-to-member, since a "normal" DeclRefExpr
6897 // would refer to the member itself.
6898 if (ParamType->isMemberPointerType()) {
6899 QualType ClassType
6900 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
6901 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00006902 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00006903 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006904 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00006905 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00006906
6907 // The actual value-ness of this is unimportant, but for
6908 // internal consistency's sake, references to instance methods
6909 // are r-values.
6910 ExprValueKind VK = VK_LValue;
6911 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
6912 VK = VK_RValue;
6913
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006914 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00006915 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00006916 VK,
John McCall7decc9e2010-11-18 06:31:45 +00006917 Loc,
6918 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006919 if (RefExpr.isInvalid())
6920 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006921
John McCalle3027922010-08-25 11:45:40 +00006922 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006923
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006924 // We might need to perform a trailing qualification conversion, since
6925 // the element type on the parameter could be more qualified than the
6926 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00006927 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006928 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00006929 ParamType.getUnqualifiedType(), false,
6930 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006931 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006932
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006933 assert(!RefExpr.isInvalid() &&
6934 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00006935 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006936 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006937 }
6938 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006939
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006940 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00006941
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006942 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00006943 // When the non-type template parameter is a pointer, take the
6944 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00006945 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006946 if (RefExpr.isInvalid())
6947 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006948
Richard Smithfc6fca12017-01-28 00:38:35 +00006949 if (!Context.hasSameUnqualifiedType(ParamType->getPointeeType(), T) &&
6950 (T->isFunctionType() || T->isArrayType())) {
6951 // Decay functions and arrays unless we're forming a pointer to array.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006952 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00006953 if (RefExpr.isInvalid())
6954 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00006955
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006956 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006957 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006958
Douglas Gregorb242683d2010-04-01 18:32:35 +00006959 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00006960 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006961 }
6962
John McCall7decc9e2010-11-18 06:31:45 +00006963 ExprValueKind VK = VK_RValue;
6964
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006965 // If the non-type template parameter has reference type, qualify the
6966 // resulting declaration reference with the extra qualifiers on the
6967 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00006968 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
6969 VK = VK_LValue;
6970 T = Context.getQualifiedType(T,
6971 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00006972 } else if (isa<FunctionDecl>(VD)) {
6973 // References to functions are always lvalues.
6974 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00006975 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006976
John McCall7decc9e2010-11-18 06:31:45 +00006977 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006978}
6979
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006980/// Construct a new expression that refers to the given
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006981/// integral template argument with the given source-location
6982/// information.
6983///
6984/// This routine takes care of the mapping from an integral template
6985/// argument (which may have any integral type) to the appropriate
6986/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006987ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00006988Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6989 SourceLocation Loc) {
6990 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00006991 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00006992 QualType OrigT = Arg.getIntegralType();
6993
6994 // If this is an enum type that we're instantiating, we need to use an integer
6995 // type the same size as the enumerator. We don't want to build an
6996 // IntegerLiteral with enum type. The integer type of an enum type can be of
6997 // any integral type with C++11 enum classes, make sure we create the right
6998 // type of literal for it.
6999 QualType T = OrigT;
7000 if (const EnumType *ET = OrigT->getAs<EnumType>())
7001 T = ET->getDecl()->getIntegerType();
7002
7003 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00007004 if (T->isAnyCharacterType()) {
7005 CharacterLiteral::CharacterKind Kind;
7006 if (T->isWideCharType())
7007 Kind = CharacterLiteral::Wide;
Richard Smith3a8244d2018-05-01 05:02:45 +00007008 else if (T->isChar8Type() && getLangOpts().Char8)
7009 Kind = CharacterLiteral::UTF8;
Douglas Gregorfb65e592011-07-27 05:40:30 +00007010 else if (T->isChar16Type())
7011 Kind = CharacterLiteral::UTF16;
7012 else if (T->isChar32Type())
7013 Kind = CharacterLiteral::UTF32;
7014 else
7015 Kind = CharacterLiteral::Ascii;
7016
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00007017 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
7018 Kind, T, Loc);
7019 } else if (T->isBooleanType()) {
7020 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
7021 T, Loc);
7022 } else if (T->isNullPtrType()) {
7023 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
7024 } else {
7025 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00007026 }
7027
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00007028 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00007029 // FIXME: This is a hack. We need a better way to handle substituted
7030 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00007031 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
7032 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00007033 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00007034 Loc, Loc);
7035 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00007036
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007037 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00007038}
7039
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007040/// Match two template parameters within template parameter lists.
Douglas Gregor641040a2011-01-12 23:45:44 +00007041static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
7042 bool Complain,
7043 Sema::TemplateParameterListEqualKind Kind,
7044 SourceLocation TemplateArgLoc) {
7045 // Check the actual kind (type, non-type, template).
7046 if (Old->getKind() != New->getKind()) {
7047 if (Complain) {
7048 unsigned NextDiag = diag::err_template_param_different_kind;
7049 if (TemplateArgLoc.isValid()) {
7050 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7051 NextDiag = diag::note_template_param_different_kind;
7052 }
7053 S.Diag(New->getLocation(), NextDiag)
7054 << (Kind != Sema::TPL_TemplateMatch);
7055 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
7056 << (Kind != Sema::TPL_TemplateMatch);
7057 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007058
Douglas Gregor641040a2011-01-12 23:45:44 +00007059 return false;
7060 }
7061
Richard Smith26b86ea2016-12-31 21:41:23 +00007062 // Check that both are parameter packs or neither are parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007063 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007064 // template template parameter, the template template parameter can have
7065 // a parameter pack where the template template argument does not.
7066 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
7067 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
7068 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00007069 if (Complain) {
7070 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
7071 if (TemplateArgLoc.isValid()) {
7072 S.Diag(TemplateArgLoc,
7073 diag::err_template_arg_template_params_mismatch);
7074 NextDiag = diag::note_template_parameter_pack_non_pack;
7075 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007076
Douglas Gregor641040a2011-01-12 23:45:44 +00007077 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
7078 : isa<NonTypeTemplateParmDecl>(New)? 1
7079 : 2;
7080 S.Diag(New->getLocation(), NextDiag)
7081 << ParamKind << New->isParameterPack();
7082 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
7083 << ParamKind << Old->isParameterPack();
7084 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007085
Douglas Gregor641040a2011-01-12 23:45:44 +00007086 return false;
7087 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007088
Douglas Gregor641040a2011-01-12 23:45:44 +00007089 // For non-type template parameters, check the type of the parameter.
7090 if (NonTypeTemplateParmDecl *OldNTTP
7091 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
7092 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007093
Douglas Gregor641040a2011-01-12 23:45:44 +00007094 // If we are matching a template template argument to a template
7095 // template parameter and one of the non-type template parameter types
Richard Smith13894182017-04-13 21:37:24 +00007096 // is dependent, then we must wait until template instantiation time
7097 // to actually compare the arguments.
Douglas Gregor641040a2011-01-12 23:45:44 +00007098 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
Richard Smith13894182017-04-13 21:37:24 +00007099 (OldNTTP->getType()->isDependentType() ||
7100 NewNTTP->getType()->isDependentType()))
Douglas Gregor641040a2011-01-12 23:45:44 +00007101 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007102
Douglas Gregor641040a2011-01-12 23:45:44 +00007103 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
7104 if (Complain) {
7105 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
7106 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007107 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00007108 diag::err_template_arg_template_params_mismatch);
7109 NextDiag = diag::note_template_nontype_parm_different_type;
7110 }
7111 S.Diag(NewNTTP->getLocation(), NextDiag)
7112 << NewNTTP->getType()
7113 << (Kind != Sema::TPL_TemplateMatch);
7114 S.Diag(OldNTTP->getLocation(),
7115 diag::note_template_nontype_parm_prev_declaration)
7116 << OldNTTP->getType();
7117 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007118
Douglas Gregor641040a2011-01-12 23:45:44 +00007119 return false;
7120 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007121
Douglas Gregor641040a2011-01-12 23:45:44 +00007122 return true;
7123 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007124
Douglas Gregor641040a2011-01-12 23:45:44 +00007125 // For template template parameters, check the template parameter types.
7126 // The template parameter lists of template template
7127 // parameters must agree.
7128 if (TemplateTemplateParmDecl *OldTTP
7129 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007130 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00007131 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
7132 OldTTP->getTemplateParameters(),
7133 Complain,
7134 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007135 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00007136 : Kind),
7137 TemplateArgLoc);
7138 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007139
Douglas Gregor641040a2011-01-12 23:45:44 +00007140 return true;
7141}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00007142
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007143/// Diagnose a known arity mismatch when comparing template argument
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007144/// lists.
7145static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007146void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007147 TemplateParameterList *New,
7148 TemplateParameterList *Old,
7149 Sema::TemplateParameterListEqualKind Kind,
7150 SourceLocation TemplateArgLoc) {
7151 unsigned NextDiag = diag::err_template_param_list_different_arity;
7152 if (TemplateArgLoc.isValid()) {
7153 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7154 NextDiag = diag::note_template_param_list_different_arity;
7155 }
7156 S.Diag(New->getTemplateLoc(), NextDiag)
7157 << (New->size() > Old->size())
7158 << (Kind != Sema::TPL_TemplateMatch)
7159 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
7160 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
7161 << (Kind != Sema::TPL_TemplateMatch)
7162 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
7163}
7164
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007165/// Determine whether the given template parameter lists are
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007166/// equivalent.
7167///
Mike Stump11289f42009-09-09 15:08:12 +00007168/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007169/// source code as part of a new template declaration.
7170///
7171/// \param Old The old template parameter list, typically found via
7172/// name lookup of the template declared with this template parameter
7173/// list.
7174///
7175/// \param Complain If true, this routine will produce a diagnostic if
7176/// the template parameter lists are not equivalent.
7177///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00007178/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00007179///
7180/// \param TemplateArgLoc If this source location is valid, then we
7181/// are actually checking the template parameter list of a template
7182/// argument (New) against the template parameter list of its
7183/// corresponding template template parameter (Old). We produce
7184/// slightly different diagnostics in this scenario.
7185///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007186/// \returns True if the template parameter lists are equal, false
7187/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00007188bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007189Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
7190 TemplateParameterList *Old,
7191 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00007192 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00007193 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007194 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
7195 if (Complain)
7196 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7197 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007198
7199 return false;
7200 }
7201
Douglas Gregor641040a2011-01-12 23:45:44 +00007202 // C++0x [temp.arg.template]p3:
7203 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00007204 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00007205 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00007206 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007207 // template-parameter-list of P. [...]
7208 TemplateParameterList::iterator NewParm = New->begin();
7209 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007210 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007211 OldParmEnd = Old->end();
7212 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00007213 if (Kind != TPL_TemplateTemplateArgumentMatch ||
7214 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007215 if (NewParm == NewParmEnd) {
7216 if (Complain)
7217 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7218 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007219
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007220 return false;
7221 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007222
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007223 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
7224 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007225 return false;
7226
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007227 ++NewParm;
7228 continue;
7229 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007230
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007231 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00007232 // [...] When P's template- parameter-list contains a template parameter
7233 // pack (14.5.3), the template parameter pack will match zero or more
7234 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007235 // template-parameter-list of A with the same type and form as the
7236 // template parameter pack in P (ignoring whether those template
7237 // parameters are template parameter packs).
7238 for (; NewParm != NewParmEnd; ++NewParm) {
7239 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
7240 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007241 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007242 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007243 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007244
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007245 // Make sure we exhausted all of the arguments.
7246 if (NewParm != NewParmEnd) {
7247 if (Complain)
7248 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7249 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007250
Douglas Gregorfd4344b2011-01-13 00:08:50 +00007251 return false;
7252 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007253
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007254 return true;
7255}
7256
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007257/// Check whether a template can be declared within this scope.
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007258///
7259/// If the template declaration is valid in this scope, returns
7260/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00007261bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007262Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00007263 if (!S)
7264 return false;
7265
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007266 // Find the nearest enclosing declaration scope.
7267 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7268 (S->getFlags() & Scope::TemplateParamScope) != 0)
7269 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00007270
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00007271 // C++ [temp]p4:
7272 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007273 DeclContext *Ctx = S->getEntity();
Alex Lorenz560ae562016-11-02 15:46:34 +00007274 if (Ctx && Ctx->isExternCContext()) {
7275 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
7276 << TemplateParams->getSourceRange();
7277 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
7278 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
7279 return true;
7280 }
Richard Smith8df390f2016-09-08 23:14:54 +00007281 Ctx = Ctx->getRedeclContext();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007282
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00007283 // C++ [temp]p2:
7284 // A template-declaration can appear only as a namespace scope or
7285 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00007286 if (Ctx) {
7287 if (Ctx->isFileContext())
7288 return false;
7289 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
7290 // C++ [temp.mem]p2:
7291 // A local class shall not have member templates.
7292 if (RD->isLocalClass())
7293 return Diag(TemplateParams->getTemplateLoc(),
7294 diag::err_template_inside_local_class)
7295 << TemplateParams->getSourceRange();
7296 else
7297 return false;
7298 }
7299 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007300
Mike Stump11289f42009-09-09 15:08:12 +00007301 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007302 diag::err_template_outside_namespace_or_class_scope)
7303 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00007304}
Douglas Gregor67a65642009-02-17 23:15:12 +00007305
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007306/// Determine what kind of template specialization the given declaration
Douglas Gregor54888652009-10-07 00:13:32 +00007307/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007308static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00007309 if (!D)
7310 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007311
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007312 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
7313 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00007314 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
7315 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007316 if (VarDecl *Var = dyn_cast<VarDecl>(D))
7317 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007318
Douglas Gregor54888652009-10-07 00:13:32 +00007319 return TSK_Undeclared;
7320}
7321
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007322/// Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007323/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00007324///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007325/// This routine determines whether a template specialization can be declared
7326/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00007327///
7328/// \param S the semantic analysis object for which this check is being
7329/// performed.
7330///
7331/// \param Specialized the entity being specialized or instantiated, which
7332/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007333/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00007334/// member class).
7335///
7336/// \param PrevDecl the previous declaration of this entity, if any.
7337///
7338/// \param Loc the location of the explicit specialization or instantiation of
7339/// this entity.
7340///
7341/// \param IsPartialSpecialization whether this is a partial specialization of
7342/// a class template.
7343///
Douglas Gregor54888652009-10-07 00:13:32 +00007344/// \returns true if there was an error that we cannot recover from, false
7345/// otherwise.
7346static bool CheckTemplateSpecializationScope(Sema &S,
7347 NamedDecl *Specialized,
7348 NamedDecl *PrevDecl,
7349 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007350 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00007351 // Keep these "kind" numbers in sync with the %select statements in the
7352 // various diagnostics emitted by this routine.
7353 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00007354 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00007355 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007356 else if (isa<VarTemplateDecl>(Specialized))
7357 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00007358 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00007359 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007360 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00007361 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007362 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00007363 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007364 else if (isa<RecordDecl>(Specialized))
7365 EntityKind = 7;
7366 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
7367 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00007368 else {
Richard Smith7d137e32012-03-23 03:33:32 +00007369 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007370 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007371 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00007372 return true;
7373 }
7374
Douglas Gregorf47b9112009-02-25 22:02:03 +00007375 // C++ [temp.expl.spec]p2:
Richard Smithc660c8f2018-03-16 13:36:56 +00007376 // An explicit specialization may be declared in any scope in which
7377 // the corresponding primary template may be defined.
Sebastian Redl50c68252010-08-31 00:36:30 +00007378 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00007379 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007380 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007381 return true;
7382 }
Douglas Gregore4b05162009-10-07 17:21:34 +00007383
7384 // C++ [temp.class.spec]p6:
Richard Smithc660c8f2018-03-16 13:36:56 +00007385 // A class template partial specialization may be declared in any
7386 // scope in which the primary template may be defined.
7387 DeclContext *SpecializedContext =
7388 Specialized->getDeclContext()->getRedeclContext();
7389 DeclContext *DC = S.CurContext->getRedeclContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00007390
Richard Smithc660c8f2018-03-16 13:36:56 +00007391 // Make sure that this redeclaration (or definition) occurs in the same
7392 // scope or an enclosing namespace.
7393 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
7394 : DC->Equals(SpecializedContext))) {
Richard Smitha98f8fc2013-12-07 05:09:50 +00007395 if (isa<TranslationUnitDecl>(SpecializedContext))
7396 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
7397 << EntityKind << Specialized;
Richard Smithc660c8f2018-03-16 13:36:56 +00007398 else {
7399 auto *ND = cast<NamedDecl>(SpecializedContext);
Alexey Bataev0068cb22015-03-20 07:21:46 +00007400 int Diag = diag::err_template_spec_redecl_out_of_scope;
Richard Smithc660c8f2018-03-16 13:36:56 +00007401 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
Alexey Bataev0068cb22015-03-20 07:21:46 +00007402 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
7403 S.Diag(Loc, Diag) << EntityKind << Specialized
Richard Smithc660c8f2018-03-16 13:36:56 +00007404 << ND << isa<CXXRecordDecl>(ND);
7405 }
Richard Smitha98f8fc2013-12-07 05:09:50 +00007406
7407 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007408
Richard Smithc660c8f2018-03-16 13:36:56 +00007409 // Don't allow specializing in the wrong class during error recovery.
7410 // Otherwise, things can go horribly wrong.
7411 if (DC->isRecord())
7412 return true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007413 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007414
Douglas Gregorf47b9112009-02-25 22:02:03 +00007415 return false;
7416}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007417
Richard Smith57aae072016-12-28 02:37:25 +00007418static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
7419 if (!E->isTypeDependent())
Richard Smith6056d5e2014-02-09 00:54:43 +00007420 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00007421 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00007422 Checker.TraverseStmt(E);
Richard Smith57aae072016-12-28 02:37:25 +00007423 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00007424 return E->getSourceRange();
7425 return Checker.MatchLoc;
7426}
7427
7428static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
7429 if (!TL.getType()->isDependentType())
7430 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00007431 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00007432 Checker.TraverseTypeLoc(TL);
Richard Smith57aae072016-12-28 02:37:25 +00007433 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00007434 return TL.getSourceRange();
7435 return Checker.MatchLoc;
7436}
7437
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007438/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007439/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007440static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00007441 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
7442 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007443 for (unsigned I = 0; I != NumArgs; ++I) {
7444 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00007445 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00007446 S, TemplateNameLoc, Param, Args[I].pack_begin(),
7447 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007448 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007449
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007450 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007451 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007452
Eli Friedmanb826a002012-09-26 02:36:12 +00007453 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007454 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00007455
7456 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007457
Douglas Gregor98318c22011-01-03 21:37:45 +00007458 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007459 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
7460 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00007461
7462 // Strip off any implicit casts we added as part of type checking.
7463 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
7464 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007465
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007466 // C++ [temp.class.spec]p8:
7467 // A non-type argument is non-specialized if it is the name of a
7468 // non-type parameter. All other non-type arguments are
7469 // specialized.
7470 //
7471 // Below, we check the two conditions that only apply to
7472 // specialized non-type arguments, so skip any non-specialized
7473 // arguments.
7474 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00007475 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007476 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007477
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007478 // C++ [temp.class.spec]p9:
7479 // Within the argument list of a class template partial
7480 // specialization, the following restrictions apply:
7481 // -- A partially specialized non-type argument expression
7482 // shall not involve a template parameter of the partial
7483 // specialization except when the argument expression is a
7484 // simple identifier.
Richard Smith57aae072016-12-28 02:37:25 +00007485 // -- The type of a template parameter corresponding to a
7486 // specialized non-type argument shall not be dependent on a
7487 // parameter of the specialization.
7488 // DR1315 removes the first bullet, leaving an incoherent set of rules.
7489 // We implement a compromise between the original rules and DR1315:
7490 // -- A specialized non-type template argument shall not be
7491 // type-dependent and the corresponding template parameter
7492 // shall have a non-dependent type.
Richard Smith6056d5e2014-02-09 00:54:43 +00007493 SourceRange ParamUseRange =
Richard Smith57aae072016-12-28 02:37:25 +00007494 findTemplateParameterInType(Param->getDepth(), ArgExpr);
Richard Smith6056d5e2014-02-09 00:54:43 +00007495 if (ParamUseRange.isValid()) {
7496 if (IsDefaultArgument) {
7497 S.Diag(TemplateNameLoc,
7498 diag::err_dependent_non_type_arg_in_partial_spec);
7499 S.Diag(ParamUseRange.getBegin(),
7500 diag::note_dependent_non_type_default_arg_in_partial_spec)
7501 << ParamUseRange;
7502 } else {
7503 S.Diag(ParamUseRange.getBegin(),
7504 diag::err_dependent_non_type_arg_in_partial_spec)
7505 << ParamUseRange;
7506 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007507 return true;
7508 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007509
Richard Smith6056d5e2014-02-09 00:54:43 +00007510 ParamUseRange = findTemplateParameter(
Richard Smith57aae072016-12-28 02:37:25 +00007511 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
Richard Smith6056d5e2014-02-09 00:54:43 +00007512 if (ParamUseRange.isValid()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007513 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
Richard Smith6056d5e2014-02-09 00:54:43 +00007514 diag::err_dependent_typed_non_type_arg_in_partial_spec)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007515 << Param->getType();
Richard Smith6056d5e2014-02-09 00:54:43 +00007516 S.Diag(Param->getLocation(), diag::note_template_param_here)
Richard Smith57aae072016-12-28 02:37:25 +00007517 << (IsDefaultArgument ? ParamUseRange : SourceRange())
7518 << ParamUseRange;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007519 return true;
7520 }
7521 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007522
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007523 return false;
7524}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007525
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007526/// Check the non-type template arguments of a class template
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007527/// partial specialization according to C++ [temp.class.spec]p9.
7528///
Richard Smith6056d5e2014-02-09 00:54:43 +00007529/// \param TemplateNameLoc the location of the template name.
Simon Pilgrim6905d222016-12-30 22:55:33 +00007530/// \param PrimaryTemplate the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00007531/// template.
7532/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00007533/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00007534/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007535///
Richard Smith6056d5e2014-02-09 00:54:43 +00007536/// \returns \c true if there was an error, \c false otherwise.
Richard Smith57aae072016-12-28 02:37:25 +00007537bool Sema::CheckTemplatePartialSpecializationArgs(
7538 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
7539 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
7540 // We have to be conservative when checking a template in a dependent
7541 // context.
7542 if (PrimaryTemplate->getDeclContext()->isDependentContext())
7543 return false;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007544
Richard Smith57aae072016-12-28 02:37:25 +00007545 TemplateParameterList *TemplateParams =
7546 PrimaryTemplate->getTemplateParameters();
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007547 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7548 NonTypeTemplateParmDecl *Param
7549 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
7550 if (!Param)
7551 continue;
7552
Richard Smith57aae072016-12-28 02:37:25 +00007553 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
7554 Param, &TemplateArgs[I],
7555 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00007556 return true;
7557 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007558
7559 return false;
7560}
7561
Erich Keanec480f302018-07-12 21:09:05 +00007562DeclResult Sema::ActOnClassTemplateSpecialization(
7563 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7564 SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId,
7565 const ParsedAttributesView &Attr,
7566 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00007567 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00007568
Richard Smith4b55a9c2014-04-17 03:29:33 +00007569 CXXScopeSpec &SS = TemplateId.SS;
7570
Abramo Bagnara60804e12011-03-18 15:16:37 +00007571 // NOTE: KWLoc is the location of the tag keyword. This will instead
7572 // store the location of the outermost template keyword in the declaration.
7573 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00007574 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
7575 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
7576 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
7577 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00007578
Douglas Gregor67a65642009-02-17 23:15:12 +00007579 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00007580 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00007581 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00007582 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
7583
7584 if (!ClassTemplate) {
7585 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007586 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00007587 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
7588 return true;
7589 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007590
Richard Smithf445f192017-02-09 21:04:43 +00007591 bool isMemberSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00007592 bool isPartialSpecialization = false;
7593
Douglas Gregorf47b9112009-02-25 22:02:03 +00007594 // Check the validity of the template headers that introduce this
7595 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00007596 // FIXME: We probably shouldn't complain about these headers for
7597 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007598 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00007599 TemplateParameterList *TemplateParams =
7600 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00007601 KWLoc, TemplateNameLoc, SS, &TemplateId,
Richard Smithf445f192017-02-09 21:04:43 +00007602 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
Richard Smith4b55a9c2014-04-17 03:29:33 +00007603 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007604 if (Invalid)
7605 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007606
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007607 if (TemplateParams && TemplateParams->size() > 0) {
7608 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00007609
Douglas Gregorec9518b2010-12-21 08:14:57 +00007610 if (TUK == TUK_Friend) {
7611 Diag(KWLoc, diag::err_partial_specialization_friend)
7612 << SourceRange(LAngleLoc, RAngleLoc);
7613 return true;
7614 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007615
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007616 // C++ [temp.class.spec]p10:
7617 // The template parameter list of a specialization shall not
7618 // contain default template argument values.
7619 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7620 Decl *Param = TemplateParams->getParam(I);
7621 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
7622 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00007623 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007624 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00007625 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007626 }
7627 } else if (NonTypeTemplateParmDecl *NTTP
7628 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
7629 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00007630 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007631 diag::err_default_arg_in_partial_spec)
7632 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00007633 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007634 }
7635 } else {
7636 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00007637 if (TTP->hasDefaultArgument()) {
7638 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00007639 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00007640 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00007641 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00007642 }
7643 }
7644 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007645 } else if (TemplateParams) {
7646 if (TUK == TUK_Friend)
7647 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00007648 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007649 SourceRange(TemplateParams->getTemplateLoc(),
7650 TemplateParams->getRAngleLoc()))
7651 << SourceRange(LAngleLoc, RAngleLoc);
Richard Smith4b55a9c2014-04-17 03:29:33 +00007652 } else {
7653 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007654 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00007655
Douglas Gregor67a65642009-02-17 23:15:12 +00007656 // Check that the specialization uses the same tag kind as the
7657 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007658 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7659 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00007660 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007661 Kind, TUK == TUK_Definition, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00007662 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007663 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00007664 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007665 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00007666 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007667 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00007668 diag::note_previous_use);
7669 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7670 }
7671
Douglas Gregorc40290e2009-03-09 23:48:35 +00007672 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00007673 TemplateArgumentListInfo TemplateArgs =
7674 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00007675
Douglas Gregor14406932011-01-03 20:35:03 +00007676 // Check for unexpanded parameter packs in any of the template arguments.
7677 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007678 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00007679 UPPC_PartialSpecialization))
7680 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007681
Douglas Gregor67a65642009-02-17 23:15:12 +00007682 // Check that the template argument list is well-formed for this
7683 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007684 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007685 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7686 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00007687 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00007688
Douglas Gregor2373c592009-05-31 09:31:02 +00007689 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00007690 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00007691 if (isPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00007692 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
7693 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00007694 return true;
7695
Richard Smith57aae072016-12-28 02:37:25 +00007696 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
7697 // also do it during instantiation.
Douglas Gregor678d76c2011-07-01 01:22:09 +00007698 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007699 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00007700 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00007701 TemplateArgs.arguments(), InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00007702 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
7703 << ClassTemplate->getDeclName();
7704 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00007705 }
7706 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007707
Craig Topperc3ec1492014-05-26 06:22:03 +00007708 void *InsertPos = nullptr;
7709 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00007710
7711 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007712 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00007713 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00007714 else
Craig Topper7e0daca2014-06-26 04:58:53 +00007715 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00007716
Craig Topperc3ec1492014-05-26 06:22:03 +00007717 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00007718
Douglas Gregorf47b9112009-02-25 22:02:03 +00007719 // Check whether we can declare a class template specialization in
7720 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00007721 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007722 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
7723 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007724 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00007725 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007726
Douglas Gregor15301382009-07-30 17:40:51 +00007727 // The canonical type
7728 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00007729 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00007730 // Build the canonical type that describes the converted template
7731 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00007732 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7733 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00007734 Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007735
7736 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007737 ClassTemplate->getInjectedClassNameSpecialization())) {
7738 // C++ [temp.class.spec]p9b3:
7739 //
7740 // -- The argument list of the specialization shall not be identical
7741 // to the implicit argument list of the primary template.
Richard Smith0e617ec2016-12-27 07:56:27 +00007742 //
7743 // This rule has since been removed, because it's redundant given DR1495,
7744 // but we keep it because it produces better diagnostics and recovery.
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007745 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00007746 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00007747 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007748 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
7749 ClassTemplate->getIdentifier(),
7750 TemplateNameLoc,
7751 Attr,
7752 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00007753 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00007754 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00007755 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007756 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00007757 }
Douglas Gregor15301382009-07-30 17:40:51 +00007758
Douglas Gregor2373c592009-05-31 09:31:02 +00007759 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00007760 ClassTemplatePartialSpecializationDecl *PrevPartial
7761 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007762 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00007763 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00007764 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007765 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00007766 TemplateParams,
7767 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007768 Converted,
John McCall6b51f282009-11-23 01:53:49 +00007769 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00007770 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00007771 PrevPartial);
Bruno Ricci4224c872018-12-21 14:35:24 +00007772 SetNestedNameSpecifier(*this, Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007773 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Benjamin Kramer9cc210652015-08-05 09:40:49 +00007774 Partial->setTemplateParameterListsInfo(
7775 Context, TemplateParameterLists.drop_back(1));
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007776 }
Douglas Gregor2373c592009-05-31 09:31:02 +00007777
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007778 if (!PrevPartial)
7779 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00007780 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00007781
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007782 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00007783 // template specialization, make a note of that.
7784 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
7785 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007786
Richard Smith57aae072016-12-28 02:37:25 +00007787 CheckTemplatePartialSpecialization(Partial);
Douglas Gregor67a65642009-02-17 23:15:12 +00007788 } else {
7789 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00007790 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00007791 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007792 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00007793 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007794 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007795 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007796 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00007797 PrevDecl);
Bruno Ricci4224c872018-12-21 14:35:24 +00007798 SetNestedNameSpecifier(*this, Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007799 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00007800 Specialization->setTemplateParameterListsInfo(Context,
Benjamin Kramer9cc210652015-08-05 09:40:49 +00007801 TemplateParameterLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007802 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007803
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007804 if (!PrevDecl)
7805 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00007806
David Majnemer678f50b2015-11-18 19:49:19 +00007807 if (CurContext->isDependentContext()) {
David Majnemer678f50b2015-11-18 19:49:19 +00007808 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7809 CanonType = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00007810 CanonTemplate, Converted);
David Majnemer678f50b2015-11-18 19:49:19 +00007811 } else {
7812 CanonType = Context.getTypeDeclType(Specialization);
7813 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007814 }
7815
Douglas Gregor06db9f52009-10-12 20:18:28 +00007816 // C++ [temp.expl.spec]p6:
7817 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007818 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007819 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007820 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007821 // use occurs; no diagnostic is required.
7822 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007823 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007824 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00007825 // Is there any previous explicit specialization declaration?
7826 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7827 Okay = true;
7828 break;
7829 }
7830 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007831
Douglas Gregorc854c662010-02-26 06:03:23 +00007832 if (!Okay) {
7833 SourceRange Range(TemplateNameLoc, RAngleLoc);
7834 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
7835 << Context.getTypeDeclType(Specialization) << Range;
7836
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007837 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00007838 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007839 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00007840 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00007841 return true;
7842 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007843 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007844
Douglas Gregor2208a292009-09-26 20:57:03 +00007845 // If this is not a friend, note that this is an explicit specialization.
7846 if (TUK != TUK_Friend)
7847 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00007848
7849 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00007850 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00007851 RecordDecl *Def = Specialization->getDefinition();
7852 NamedDecl *Hidden = nullptr;
7853 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
7854 SkipBody->ShouldSkip = true;
Richard Smithc4577662018-09-12 02:13:47 +00007855 SkipBody->Previous = Def;
Richard Smith858e0e02017-05-11 23:11:16 +00007856 makeMergedDefinitionVisible(Hidden);
Richard Smithc7e6ff02015-05-18 20:36:47 +00007857 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00007858 SourceRange Range(TemplateNameLoc, RAngleLoc);
Richard Smith792c22d2016-12-24 04:09:05 +00007859 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00007860 Diag(Def->getLocation(), diag::note_previous_definition);
7861 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00007862 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00007863 }
7864 }
7865
Erich Keanec480f302018-07-12 21:09:05 +00007866 ProcessDeclAttributeList(S, Specialization, Attr);
John McCall659a3372010-12-18 03:30:47 +00007867
Richard Smith034b94a2012-08-17 03:20:55 +00007868 // Add alignment attributes if necessary; these attributes are checked when
7869 // the ASTContext lays out the structure.
Richard Smithc4577662018-09-12 02:13:47 +00007870 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
Richard Smith034b94a2012-08-17 03:20:55 +00007871 AddAlignmentAttributesForRecord(Specialization);
7872 AddMsStructLayoutForRecord(Specialization);
7873 }
7874
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00007875 if (ModulePrivateLoc.isValid())
7876 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
7877 << (isPartialSpecialization? 1 : 0)
7878 << FixItHint::CreateRemoval(ModulePrivateLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00007879
Douglas Gregord56a91e2009-02-26 22:19:44 +00007880 // Build the fully-sugared type for this class template
7881 // specialization as the user wrote in the specialization
7882 // itself. This means that we'll pretty-print the type retrieved
7883 // from the specialization's declaration the way that the user
7884 // actually wrote the specialization, rather than formatting the
7885 // name based on the "canonical" representation used to store the
7886 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007887 TypeSourceInfo *WrittenTy
7888 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7889 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007890 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00007891 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007892 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007893 }
Douglas Gregor67a65642009-02-17 23:15:12 +00007894
Douglas Gregor1e249f82009-02-25 22:18:32 +00007895 // C++ [temp.expl.spec]p9:
7896 // A template explicit specialization is in the scope of the
7897 // namespace in which the template was defined.
7898 //
7899 // We actually implement this paragraph where we set the semantic
7900 // context (in the creation of the ClassTemplateSpecializationDecl),
7901 // but we also maintain the lexical context where the actual
7902 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00007903 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00007904
Douglas Gregor67a65642009-02-17 23:15:12 +00007905 // We may be starting the definition of this specialization.
Richard Smithc4577662018-09-12 02:13:47 +00007906 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
Douglas Gregor67a65642009-02-17 23:15:12 +00007907 Specialization->startDefinition();
7908
Douglas Gregor2208a292009-09-26 20:57:03 +00007909 if (TUK == TUK_Friend) {
7910 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
7911 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00007912 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00007913 /*FIXME:*/KWLoc);
7914 Friend->setAccess(AS_public);
7915 CurContext->addDecl(Friend);
7916 } else {
7917 // Add the specialization into its lexical context, so that it can
7918 // be seen when iterating through the list of declarations in that
7919 // context. However, specializations are not found by name lookup.
7920 CurContext->addDecl(Specialization);
7921 }
Richard Smithc4577662018-09-12 02:13:47 +00007922
7923 if (SkipBody && SkipBody->ShouldSkip)
7924 return SkipBody->Previous;
7925
John McCall48871652010-08-21 09:40:31 +00007926 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00007927}
Douglas Gregor333489b2009-03-27 23:10:48 +00007928
John McCall48871652010-08-21 09:40:31 +00007929Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00007930 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00007931 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007932 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00007933 ActOnDocumentableDecl(NewDecl);
7934 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00007935}
7936
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007937/// Strips various properties off an implicit instantiation
John McCall4f7ced62010-02-11 01:33:53 +00007938/// that has just been explicitly specialized.
7939static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00007940 D->dropAttr<DLLImportAttr>();
7941 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00007942
Nico Webere4974382014-12-19 23:52:45 +00007943 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00007944 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00007945}
7946
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007947/// Compute the diagnostic location for an explicit instantiation
Nico Webera8f80b32012-01-09 19:52:25 +00007948// declaration or definition.
7949static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007950 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00007951 // Explicit instantiations following a specialization have no effect and
7952 // hence no PointOfInstantiation. In that case, walk decl backwards
7953 // until a valid name loc is found.
7954 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00007955 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
7956 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00007957 PrevDiagLoc = Prev->getLocation();
7958 }
7959 assert(PrevDiagLoc.isValid() &&
7960 "Explicit instantiation without point of instantiation?");
7961 return PrevDiagLoc;
7962}
7963
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007964/// Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007965/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007966/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007967/// new specialization/instantiation will have any effect.
7968///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007969/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007970/// instantiation.
7971///
7972/// \param NewTSK the kind of the new explicit specialization or instantiation.
7973///
7974/// \param PrevDecl the previous declaration of the entity.
7975///
7976/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
7977///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007978/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007979/// declaration was instantiated (either implicitly or explicitly).
7980///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007981/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007982/// specialization or instantiation has no effect and should be ignored.
7983///
7984/// \returns true if there was an error that should prevent the introduction of
7985/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00007986bool
7987Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7988 TemplateSpecializationKind NewTSK,
7989 NamedDecl *PrevDecl,
7990 TemplateSpecializationKind PrevTSK,
7991 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007992 bool &HasNoEffect) {
7993 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007994
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007995 switch (NewTSK) {
7996 case TSK_Undeclared:
7997 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00007998 assert(
7999 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
8000 "previous declaration must be implicit!");
8001 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008002
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008003 case TSK_ExplicitSpecialization:
8004 switch (PrevTSK) {
8005 case TSK_Undeclared:
8006 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008007 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008008 // explicitly specialized or has merely been mentioned without any
8009 // instantiation.
8010 return false;
8011
8012 case TSK_ImplicitInstantiation:
8013 if (PrevPointOfInstantiation.isInvalid()) {
8014 // The declaration itself has not actually been instantiated, so it is
8015 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00008016 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008017 return false;
8018 }
8019 // Fall through
Galina Kistanova3779cb32017-06-07 06:25:05 +00008020 LLVM_FALLTHROUGH;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008021
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008022 case TSK_ExplicitInstantiationDeclaration:
8023 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008024 assert((PrevTSK == TSK_ImplicitInstantiation ||
8025 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008026 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008027
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008028 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008029 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008030 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008031 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008032 // implicit instantiation to take place, in every translation unit in
8033 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00008034 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00008035 // Is there any previous explicit specialization declaration?
8036 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
8037 return false;
8038 }
8039
Douglas Gregor1d957a32009-10-27 18:42:08 +00008040 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008041 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008042 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008043 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008044
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008045 return true;
8046 }
Galina Kistanova1d36e832017-06-08 18:20:32 +00008047 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008048
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008049 case TSK_ExplicitInstantiationDeclaration:
8050 switch (PrevTSK) {
8051 case TSK_ExplicitInstantiationDeclaration:
8052 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00008053 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008054 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008055
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008056 case TSK_Undeclared:
8057 case TSK_ImplicitInstantiation:
8058 // We're explicitly instantiating something that may have already been
8059 // implicitly instantiated; that's fine.
8060 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008061
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008062 case TSK_ExplicitSpecialization:
8063 // C++0x [temp.explicit]p4:
8064 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008065 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008066 // specialization for that template, the explicit instantiation has no
8067 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00008068 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008069 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008070
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008071 case TSK_ExplicitInstantiationDefinition:
8072 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008073 // If an entity is the subject of both an explicit instantiation
8074 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008075 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008076 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00008077 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00008078
8079 // Explicit instantiations following a specialization have no effect and
8080 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
8081 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00008082 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
8083 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008084 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008085 return false;
8086 }
Bruno Riccid8c17672018-12-21 20:38:06 +00008087 llvm_unreachable("Unexpected TemplateSpecializationKind!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008088
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008089 case TSK_ExplicitInstantiationDefinition:
8090 switch (PrevTSK) {
8091 case TSK_Undeclared:
8092 case TSK_ImplicitInstantiation:
8093 // We're explicitly instantiating something that may have already been
8094 // implicitly instantiated; that's fine.
8095 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008096
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008097 case TSK_ExplicitSpecialization:
8098 // C++ DR 259, C++0x [temp.explicit]p4:
8099 // For a given set of template parameters, if an explicit
8100 // instantiation of a template appears after a declaration of
8101 // an explicit specialization for that template, the explicit
8102 // instantiation has no effect.
Richard Smithe4caa482016-08-31 23:23:25 +00008103 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
Richard Smith0bf8a4922011-10-18 20:49:44 +00008104 << PrevDecl;
8105 Diag(PrevDecl->getLocation(),
8106 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008107 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008108 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008109
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008110 case TSK_ExplicitInstantiationDeclaration:
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00008111 // We're explicitly instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008112 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00008113
8114 // C++0x [temp.explicit]p4:
8115 // For a given set of template parameters, if an explicit instantiation
8116 // of a template appears after a declaration of an explicit
8117 // specialization for that template, the explicit instantiation has no
8118 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00008119 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00008120 // Is there any previous explicit specialization declaration?
8121 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
8122 HasNoEffect = true;
8123 break;
8124 }
8125 }
8126
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008127 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008128
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008129 case TSK_ExplicitInstantiationDefinition:
8130 // C++0x [temp.spec]p5:
8131 // For a given template and a given set of template-arguments,
8132 // - an explicit instantiation definition shall appear at most once
8133 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00008134
8135 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
8136 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00008137 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00008138 : diag::err_explicit_instantiation_duplicate)
8139 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00008140 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00008141 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008142 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008143 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008144 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008145 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008146
David Blaikie83d382b2011-09-23 05:06:16 +00008147 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008148}
8149
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008150/// Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00008151/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00008152///
James Dennettf14a6e52012-06-15 22:23:43 +00008153/// The only possible way to get a dependent function template specialization
8154/// is with a friend declaration, like so:
8155///
8156/// \code
8157/// template \<class T> void foo(T);
8158/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00008159/// friend void foo<>(T);
8160/// };
James Dennettf14a6e52012-06-15 22:23:43 +00008161/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00008162///
8163/// There really isn't any useful analysis we can do here, so we
8164/// just store the information.
8165bool
8166Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
8167 const TemplateArgumentListInfo &ExplicitTemplateArgs,
8168 LookupResult &Previous) {
8169 // Remove anything from Previous that isn't a function template in
8170 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00008171 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00008172 LookupResult::Filter F = Previous.makeFilter();
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008173 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
8174 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
John McCallb9c78482010-04-08 09:05:18 +00008175 while (F.hasNext()) {
8176 NamedDecl *D = F.next()->getUnderlyingDecl();
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008177 if (!isa<FunctionTemplateDecl>(D)) {
John McCallb9c78482010-04-08 09:05:18 +00008178 F.erase();
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008179 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
8180 continue;
8181 }
8182
8183 if (!FDLookupContext->InEnclosingNamespaceSetOf(
8184 D->getDeclContext()->getRedeclContext())) {
8185 F.erase();
8186 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
8187 continue;
8188 }
John McCallb9c78482010-04-08 09:05:18 +00008189 }
8190 F.done();
8191
Erik Pilkington0b75dc52018-07-19 20:40:20 +00008192 if (Previous.empty()) {
8193 Diag(FD->getLocation(),
8194 diag::err_dependent_function_template_spec_no_match);
8195 for (auto &P : DiscardedCandidates)
8196 Diag(P.second->getLocation(),
8197 diag::note_dependent_function_template_spec_discard_reason)
8198 << P.first;
8199 return true;
8200 }
John McCallb9c78482010-04-08 09:05:18 +00008201
8202 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
8203 ExplicitTemplateArgs);
8204 return false;
8205}
8206
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008207/// Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008208/// specialization.
8209///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008210/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008211/// explicit function template specialization. On successful completion,
8212/// the function declaration \p FD will become a function template
8213/// specialization.
8214///
8215/// \param FD the function declaration, which will be updated to become a
8216/// function template specialization.
8217///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008218/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
8219/// if any. Note that this may be valid info even when 0 arguments are
8220/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
8221/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008222///
Francois Pichet3a44e432011-07-08 06:21:47 +00008223/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008224/// this function specialization.
Richard Smith8ce732b2019-01-07 06:00:46 +00008225///
8226/// \param QualifiedFriend whether this is a lookup for a qualified friend
8227/// declaration with no explicit template argument list that might be
8228/// befriending a function template specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008229bool Sema::CheckFunctionTemplateSpecialization(
8230 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smith8ce732b2019-01-07 06:00:46 +00008231 LookupResult &Previous, bool QualifiedFriend) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008232 // The set of function template specializations that could match this
8233 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00008234 UnresolvedSet<8> Candidates;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008235 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
8236 /*ForTakingAddress=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008237
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008238 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
8239 ConvertedTemplateArgs;
8240
Sebastian Redl50c68252010-08-31 00:36:30 +00008241 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00008242 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8243 I != E; ++I) {
8244 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
8245 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008246 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008247 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00008248 if (!FDLookupContext->InEnclosingNamespaceSetOf(
8249 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008250 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008251
Richard Smith574f4f62013-01-14 05:37:29 +00008252 // When matching a constexpr member function template specialization
8253 // against the primary template, we don't yet know whether the
8254 // specialization has an implicit 'const' (because we don't know whether
8255 // it will be a static member function until we know which template it
8256 // specializes), so adjust it now assuming it specializes this template.
8257 QualType FT = FD->getType();
8258 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00008259 CXXMethodDecl *OldMD =
8260 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00008261 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00008262 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00008263 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00008264 EPI.TypeQuals.addConst();
Alp Toker314cc812014-01-25 16:55:45 +00008265 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00008266 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00008267 }
8268 }
8269
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008270 TemplateArgumentListInfo Args;
8271 if (ExplicitTemplateArgs)
8272 Args = *ExplicitTemplateArgs;
8273
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008274 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008275 // A trailing template-argument can be left unspecified in the
8276 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008277 // provided it can be deduced from the function argument type.
8278 // Perform template argument deduction to determine whether we may be
8279 // specializing this template.
8280 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00008281 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00008282 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00008283 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
8284 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
Richard Smithc2bebe92016-05-11 20:37:46 +00008285 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
8286 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008287 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008288 // that we can provide nifty diagnostics.
Richard Smithc2bebe92016-05-11 20:37:46 +00008289 FailedCandidates.addCandidate().set(
8290 I.getPair(), FunTmpl->getTemplatedDecl(),
8291 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008292 (void)TDK;
8293 continue;
8294 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008295
Artem Belevich64135c32016-12-08 19:38:13 +00008296 // Target attributes are part of the cuda function signature, so
8297 // the deduced template's cuda target must match that of the
8298 // specialization. Given that C++ template deduction does not
8299 // take target attributes into account, we reject candidates
8300 // here that have a different target.
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008301 if (LangOpts.CUDA &&
Artem Belevich64135c32016-12-08 19:38:13 +00008302 IdentifyCUDATarget(Specialization,
8303 /* IgnoreImplicitHDAttributes = */ true) !=
8304 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttributes = */ true)) {
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008305 FailedCandidates.addCandidate().set(
8306 I.getPair(), FunTmpl->getTemplatedDecl(),
8307 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
8308 continue;
8309 }
8310
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008311 // Record this candidate.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008312 if (ExplicitTemplateArgs)
8313 ConvertedTemplateArgs[Specialization] = std::move(Args);
John McCall58cc69d2010-01-27 01:50:18 +00008314 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008315 }
8316 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008317
Richard Smith8ce732b2019-01-07 06:00:46 +00008318 // For a qualified friend declaration (with no explicit marker to indicate
8319 // that a template specialization was intended), note all (template and
8320 // non-template) candidates.
8321 if (QualifiedFriend && Candidates.empty()) {
8322 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
8323 << FD->getDeclName() << FDLookupContext;
8324 // FIXME: We should form a single candidate list and diagnose all
8325 // candidates at once, to get proper sorting and limiting.
8326 for (auto *OldND : Previous) {
8327 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
8328 NoteOverloadCandidate(OldND, OldFD, FD->getType(), false);
8329 }
8330 FailedCandidates.NoteCandidates(*this, FD->getLocation());
8331 return true;
8332 }
8333
Douglas Gregor5de279c2009-09-26 03:41:46 +00008334 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008335 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith8ce732b2019-01-07 06:00:46 +00008336 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
Larisse Voufo98b20f12013-07-19 23:00:19 +00008337 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
8338 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00008339 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00008340 PDiag(diag::note_function_template_spec_matched));
8341
John McCall58cc69d2010-01-27 01:50:18 +00008342 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008343 return true;
John McCall58cc69d2010-01-27 01:50:18 +00008344
8345 // Ignore access information; it doesn't figure into redeclaration checking.
8346 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00008347
8348 FunctionTemplateSpecializationInfo *SpecInfo
8349 = Specialization->getTemplateSpecializationInfo();
8350 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00008351
8352 // Note: do not overwrite location info if previous template
8353 // specialization kind was explicit.
8354 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00008355 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00008356 Specialization->setLocation(FD->getLocation());
Richard Smith54f04402017-05-18 02:29:20 +00008357 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
Richard Smith5b8b3db2012-02-20 23:28:05 +00008358 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
8359 // function can differ from the template declaration with respect to
8360 // the constexpr specifier.
Richard Smith77e9e842017-05-09 23:02:10 +00008361 // FIXME: We need an update record for this AST mutation.
8362 // FIXME: What if there are multiple such prior declarations (for instance,
8363 // from different modules)?
Richard Smith5b8b3db2012-02-20 23:28:05 +00008364 Specialization->setConstexpr(FD->isConstexpr());
8365 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008366
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008367 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00008368 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00008369
8370 // If this is a friend declaration, then we're not really declaring
8371 // an explicit specialization.
8372 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008373
Douglas Gregor54888652009-10-07 00:13:32 +00008374 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00008375 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008376 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00008377 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008378 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00008379 false))
Douglas Gregor54888652009-10-07 00:13:32 +00008380 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00008381
8382 // C++ [temp.expl.spec]p6:
8383 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008384 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00008385 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008386 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00008387 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00008388 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00008389 if (!isFriend &&
8390 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00008391 TSK_ExplicitSpecialization,
8392 Specialization,
8393 SpecInfo->getTemplateSpecializationKind(),
8394 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008395 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00008396 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008397
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008398 // Mark the prior declaration as an explicit specialization, so that later
8399 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00008400 if (!isFriend) {
Faisal Vali81a88be2016-06-14 03:23:15 +00008401 // Since explicit specializations do not inherit '=delete' from their
8402 // primary function template - check if the 'specialization' that was
8403 // implicitly generated (during template argument deduction for partial
8404 // ordering) from the most specialized of all the function templates that
8405 // 'FD' could have been specializing, has a 'deleted' definition. If so,
8406 // first check that it was implicitly generated during template argument
8407 // deduction by making sure it wasn't referenced, and then reset the deleted
8408 // flag to not-deleted, so that we can inherit that information from 'FD'.
8409 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
8410 !Specialization->getCanonicalDecl()->isReferenced()) {
Richard Smith77e9e842017-05-09 23:02:10 +00008411 // FIXME: This assert will not hold in the presence of modules.
Faisal Vali81a88be2016-06-14 03:23:15 +00008412 assert(
8413 Specialization->getCanonicalDecl() == Specialization &&
8414 "This must be the only existing declaration of this specialization");
Richard Smith77e9e842017-05-09 23:02:10 +00008415 // FIXME: We need an update record for this AST mutation.
Faisal Vali81a88be2016-06-14 03:23:15 +00008416 Specialization->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008417 }
Richard Smith54f04402017-05-18 02:29:20 +00008418 // FIXME: We need an update record for this AST mutation.
John McCall816d75b2010-03-24 07:46:06 +00008419 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00008420 MarkUnusedFileScopedDecl(Specialization);
8421 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008422
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008423 // Turn the given function declaration into a function template
8424 // specialization, with the template arguments from the previous
8425 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00008426 // Take copies of (semantic and syntactic) template argument lists.
8427 const TemplateArgumentList* TemplArgs = new (Context)
8428 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Richard Smith7d3c3ef2015-10-02 00:49:37 +00008429 FD->setFunctionTemplateSpecialization(
8430 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
8431 SpecInfo->getTemplateSpecializationKind(),
8432 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008433
Artem Belevich64135c32016-12-08 19:38:13 +00008434 // A function template specialization inherits the target attributes
8435 // of its template. (We require the attributes explicitly in the
8436 // code to match, but a template may have implicit attributes by
8437 // virtue e.g. of being constexpr, and it passes these implicit
8438 // attributes on to its specializations.)
8439 if (LangOpts.CUDA)
8440 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
8441
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008442 // The "previous declaration" for this function template specialization is
8443 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00008444 Previous.clear();
8445 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00008446 return false;
8447}
8448
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008449/// Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008450/// specialization.
8451///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008452/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008453/// explicit member function specialization. On successful completion,
8454/// the function declaration \p FD will become a member function
8455/// specialization.
8456///
Douglas Gregor86d142a2009-10-08 07:24:58 +00008457/// \param Member the member declaration, which will be updated to become a
8458/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008459///
John McCall1f82f242009-11-18 22:49:29 +00008460/// \param Previous the set of declarations, one of which may be specialized
8461/// by this function specialization; the set will be modified to contain the
8462/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008463bool
John McCall1f82f242009-11-18 22:49:29 +00008464Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008465 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00008466
Douglas Gregor86d142a2009-10-08 07:24:58 +00008467 // Try to find the member we are instantiating.
Richard Smith22e7cc62016-05-24 00:01:49 +00008468 NamedDecl *FoundInstantiation = nullptr;
Craig Topperc3ec1492014-05-26 06:22:03 +00008469 NamedDecl *Instantiation = nullptr;
8470 NamedDecl *InstantiatedFrom = nullptr;
8471 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00008472
John McCall1f82f242009-11-18 22:49:29 +00008473 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008474 // Nowhere to look anyway.
8475 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008476 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8477 I != E; ++I) {
8478 NamedDecl *D = (*I)->getUnderlyingDecl();
8479 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00008480 QualType Adjusted = Function->getType();
8481 if (!hasExplicitCallingConv(Adjusted))
8482 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
Richard Smith4576a772018-09-10 06:35:32 +00008483 // This doesn't handle deduced return types, but both function
8484 // declarations should be undeduced at this point.
Rafael Espindola66747222013-12-10 00:59:31 +00008485 if (Context.hasSameType(Adjusted, Method->getType())) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008486 FoundInstantiation = *I;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008487 Instantiation = Method;
8488 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008489 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008490 break;
8491 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008492 }
8493 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00008494 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008495 VarDecl *PrevVar;
8496 if (Previous.isSingleResult() &&
8497 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00008498 if (PrevVar->isStaticDataMember()) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008499 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00008500 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008501 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008502 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008503 }
8504 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00008505 CXXRecordDecl *PrevRecord;
8506 if (Previous.isSingleResult() &&
8507 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008508 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00008509 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00008510 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008511 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00008512 }
Richard Smith7d137e32012-03-23 03:33:32 +00008513 } else if (isa<EnumDecl>(Member)) {
8514 EnumDecl *PrevEnum;
8515 if (Previous.isSingleResult() &&
8516 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00008517 FoundInstantiation = Previous.getRepresentativeDecl();
Richard Smith7d137e32012-03-23 03:33:32 +00008518 Instantiation = PrevEnum;
8519 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
8520 MSInfo = PrevEnum->getMemberSpecializationInfo();
8521 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008522 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008523
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008524 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00008525 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008526 // specializations are always out-of-line, the caller will complain about
8527 // this mismatch later.
8528 return false;
8529 }
John McCalle820e5e2010-04-13 20:37:33 +00008530
Richard Smith77e9e842017-05-09 23:02:10 +00008531 // A member specialization in a friend declaration isn't really declaring
8532 // an explicit specialization, just identifying a specific (possibly implicit)
8533 // specialization. Don't change the template specialization kind.
8534 //
8535 // FIXME: Is this really valid? Other compilers reject.
John McCalle820e5e2010-04-13 20:37:33 +00008536 if (Member->getFriendObjectKind() != Decl::FOK_None) {
8537 // Preserve instantiation information.
8538 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
8539 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
8540 cast<CXXMethodDecl>(InstantiatedFrom),
8541 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
8542 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
8543 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
8544 cast<CXXRecordDecl>(InstantiatedFrom),
8545 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
8546 }
8547
8548 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00008549 Previous.addDecl(FoundInstantiation);
John McCalle820e5e2010-04-13 20:37:33 +00008550 return false;
8551 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008552
Douglas Gregor86d142a2009-10-08 07:24:58 +00008553 // Make sure that this is a specialization of a member.
8554 if (!InstantiatedFrom) {
8555 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
8556 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008557 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
8558 return true;
8559 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008560
Douglas Gregor06db9f52009-10-12 20:18:28 +00008561 // C++ [temp.expl.spec]p6:
8562 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00008563 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00008564 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008565 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00008566 // use occurs; no diagnostic is required.
8567 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00008568
Abramo Bagnara8075c852010-06-12 07:44:57 +00008569 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00008570 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
8571 TSK_ExplicitSpecialization,
8572 Instantiation,
8573 MSInfo->getTemplateSpecializationKind(),
8574 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008575 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00008576 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008577
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008578 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008579 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00008580 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008581 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00008582 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008583 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00008584
Richard Smith77e9e842017-05-09 23:02:10 +00008585 // Note that this member specialization is an "instantiation of" the
8586 // corresponding member of the original template.
8587 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008588 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
8589 if (InstantiationFunction->getTemplateSpecializationKind() ==
8590 TSK_ImplicitInstantiation) {
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008591 // Explicit specializations of member functions of class templates do not
8592 // inherit '=delete' from the member function they are specializing.
8593 if (InstantiationFunction->isDeleted()) {
Richard Smith77e9e842017-05-09 23:02:10 +00008594 // FIXME: This assert will not hold in the presence of modules.
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008595 assert(InstantiationFunction->getCanonicalDecl() ==
8596 InstantiationFunction);
Richard Smith77e9e842017-05-09 23:02:10 +00008597 // FIXME: We need an update record for this AST mutation.
Richard Smith5f274382016-09-28 23:55:27 +00008598 InstantiationFunction->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00008599 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008600 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008601
Richard Smith77e9e842017-05-09 23:02:10 +00008602 MemberFunction->setInstantiationOfMemberFunction(
8603 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8604 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
8605 MemberVar->setInstantiationOfStaticDataMember(
Larisse Voufo39a1e502013-08-06 01:03:05 +00008606 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Richard Smith77e9e842017-05-09 23:02:10 +00008607 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
8608 MemberClass->setInstantiationOfMemberClass(
8609 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8610 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
8611 MemberEnum->setInstantiationOfMemberEnum(
Richard Smith7d137e32012-03-23 03:33:32 +00008612 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Richard Smith77e9e842017-05-09 23:02:10 +00008613 } else {
8614 llvm_unreachable("unknown member specialization kind");
Douglas Gregor86d142a2009-10-08 07:24:58 +00008615 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008616
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008617 // Save the caller the trouble of having to figure out which declaration
8618 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00008619 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00008620 Previous.addDecl(FoundInstantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008621 return false;
8622}
8623
Richard Smith77e9e842017-05-09 23:02:10 +00008624/// Complete the explicit specialization of a member of a class template by
8625/// updating the instantiated member to be marked as an explicit specialization.
8626///
8627/// \param OrigD The member declaration instantiated from the template.
8628/// \param Loc The location of the explicit specialization of the member.
8629template<typename DeclT>
8630static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
8631 SourceLocation Loc) {
8632 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
8633 return;
8634
8635 // FIXME: Inform AST mutation listeners of this AST mutation.
8636 // FIXME: If there are multiple in-class declarations of the member (from
8637 // multiple modules, or a declaration and later definition of a member type),
8638 // should we update all of them?
8639 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
8640 OrigD->setLocation(Loc);
8641}
8642
8643void Sema::CompleteMemberSpecialization(NamedDecl *Member,
8644 LookupResult &Previous) {
8645 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
8646 if (Instantiation == Member)
8647 return;
8648
8649 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
8650 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
8651 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
8652 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
8653 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
8654 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
8655 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
8656 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
8657 else
8658 llvm_unreachable("unknown member specialization kind");
8659}
8660
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008661/// Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008662///
8663/// \returns true if a serious error occurs, false otherwise.
8664static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00008665 SourceLocation InstLoc,
8666 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00008667 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
8668 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008669
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008670 if (CurContext->isRecord()) {
8671 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
8672 << D;
8673 return true;
8674 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008675
Richard Smith050d2612011-10-18 02:28:33 +00008676 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008677 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00008678 // template. If the name declared in the explicit instantiation is an
8679 // unqualified name, the explicit instantiation shall appear in the
8680 // namespace where its template is declared or, if that namespace is inline
8681 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008682 //
8683 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00008684 if (WasQualifiedName) {
8685 if (CurContext->Encloses(OrigContext))
8686 return false;
8687 } else {
8688 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
8689 return false;
8690 }
8691
8692 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
8693 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008694 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008695 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008696 diag::err_explicit_instantiation_out_of_scope :
8697 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008698 << D << NS;
8699 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008700 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008701 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008702 diag::err_explicit_instantiation_unqualified_wrong_namespace :
8703 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
8704 << D << NS;
8705 } else
8706 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008707 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00008708 diag::err_explicit_instantiation_must_be_global :
8709 diag::warn_explicit_instantiation_must_be_global_0x)
8710 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00008711 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008712 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00008713}
8714
Richard Smith0d923af2019-04-26 01:51:07 +00008715/// Common checks for whether an explicit instantiation of \p D is valid.
8716static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D,
8717 SourceLocation InstLoc,
8718 bool WasQualifiedName,
8719 TemplateSpecializationKind TSK) {
8720 // C++ [temp.explicit]p13:
8721 // An explicit instantiation declaration shall not name a specialization of
8722 // a template with internal linkage.
8723 if (TSK == TSK_ExplicitInstantiationDeclaration &&
8724 D->getFormalLinkage() == InternalLinkage) {
8725 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
8726 return true;
8727 }
8728
8729 // C++11 [temp.explicit]p3: [DR 275]
8730 // An explicit instantiation shall appear in an enclosing namespace of its
8731 // template.
8732 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
8733 return true;
8734
8735 return false;
8736}
8737
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008738/// Determine whether the given scope specifier has a template-id in it.
Douglas Gregore47f5a72009-10-14 23:41:34 +00008739static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
8740 if (!SS.isSet())
8741 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008742
Richard Smith050d2612011-10-18 02:28:33 +00008743 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008744 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008745 // or a static data member of a class template specialization, the name of
8746 // the class template specialization in the qualified-id for the member
8747 // name shall be a simple-template-id.
8748 //
8749 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00008750 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
8751 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00008752 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00008753 if (isa<TemplateSpecializationType>(T))
8754 return true;
8755
8756 return false;
8757}
8758
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008759/// Make a dllexport or dllimport attr on a class template specialization take
8760/// effect.
8761static void dllExportImportClassTemplateSpecialization(
8762 Sema &S, ClassTemplateSpecializationDecl *Def) {
8763 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
8764 assert(A && "dllExportImportClassTemplateSpecialization called "
8765 "on Def without dllexport or dllimport");
8766
8767 // We reject explicit instantiations in class scope, so there should
8768 // never be any delayed exported classes to worry about.
8769 assert(S.DelayedDllExportClasses.empty() &&
8770 "delayed exports present at explicit instantiation");
8771 S.checkClassLevelDLLAttribute(Def);
8772
8773 // Propagate attribute to base class templates.
8774 for (auto &B : Def->bases()) {
8775 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
8776 B.getType()->getAsCXXRecordDecl()))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008777 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getBeginLoc());
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00008778 }
8779
8780 S.referenceDLLExportedClassMethods();
8781}
8782
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008783// Explicit instantiation of a class template specialization
Erich Keanec480f302018-07-12 21:09:05 +00008784DeclResult Sema::ActOnExplicitInstantiation(
8785 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
8786 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
8787 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
8788 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
8789 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
Douglas Gregora1f49972009-05-13 00:25:59 +00008790 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00008791 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00008792 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00008793 // Check that the specialization uses the same tag kind as the
8794 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00008795 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8796 assert(Kind != TTK_Enum &&
8797 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00008798
Richard Trieu265c3442016-04-05 21:13:54 +00008799 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
8800
8801 if (!ClassTemplate) {
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00008802 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
8803 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
Richard Trieu265c3442016-04-05 21:13:54 +00008804 Diag(TD->getLocation(), diag::note_previous_use);
Richard Smith392497b2013-06-22 22:03:31 +00008805 return true;
8806 }
8807
Douglas Gregord9034f02009-05-14 16:41:31 +00008808 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00008809 Kind, /*isDefinition*/false, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00008810 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00008811 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00008812 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00008813 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00008814 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00008815 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00008816 diag::note_previous_use);
8817 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8818 }
8819
Douglas Gregore47f5a72009-10-14 23:41:34 +00008820 // C++0x [temp.explicit]p2:
8821 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008822 // definition and an explicit instantiation declaration. An explicit
8823 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00008824 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
8825 ? TSK_ExplicitInstantiationDefinition
8826 : TSK_ExplicitInstantiationDeclaration;
8827
Martin Storsjo5be69bc2019-04-26 08:09:51 +00008828 if (TSK == TSK_ExplicitInstantiationDeclaration &&
8829 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
8830 // Check for dllexport class template instantiation declarations,
8831 // except for MinGW mode.
Erich Keanee891aa92018-07-13 15:07:47 +00008832 for (const ParsedAttr &AL : Attr) {
8833 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
Hans Wennborgfd76d912015-01-15 21:18:30 +00008834 Diag(ExternLoc,
8835 diag::warn_attribute_dllexport_explicit_instantiation_decl);
Erich Keanec480f302018-07-12 21:09:05 +00008836 Diag(AL.getLoc(), diag::note_attribute);
Hans Wennborgfd76d912015-01-15 21:18:30 +00008837 break;
8838 }
8839 }
8840
8841 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
8842 Diag(ExternLoc,
8843 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8844 Diag(A->getLocation(), diag::note_attribute);
8845 }
8846 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008847
Hans Wennborga86a83b2016-05-26 19:42:56 +00008848 // In MSVC mode, dllimported explicit instantiation definitions are treated as
8849 // instantiation declarations for most purposes.
8850 bool DLLImportExplicitInstantiationDef = false;
8851 if (TSK == TSK_ExplicitInstantiationDefinition &&
8852 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
8853 // Check for dllimport class template instantiation definitions.
8854 bool DLLImport =
8855 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
Erich Keanee891aa92018-07-13 15:07:47 +00008856 for (const ParsedAttr &AL : Attr) {
8857 if (AL.getKind() == ParsedAttr::AT_DLLImport)
Hans Wennborga86a83b2016-05-26 19:42:56 +00008858 DLLImport = true;
Erich Keanee891aa92018-07-13 15:07:47 +00008859 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
Hans Wennborga86a83b2016-05-26 19:42:56 +00008860 // dllexport trumps dllimport here.
8861 DLLImport = false;
8862 break;
8863 }
8864 }
8865 if (DLLImport) {
8866 TSK = TSK_ExplicitInstantiationDeclaration;
8867 DLLImportExplicitInstantiationDef = true;
8868 }
8869 }
8870
Douglas Gregora1f49972009-05-13 00:25:59 +00008871 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00008872 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00008873 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00008874
8875 // Check that the template argument list is well-formed for this
8876 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008877 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00008878 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
8879 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00008880 return true;
8881
Douglas Gregora1f49972009-05-13 00:25:59 +00008882 // Find the class template specialization declaration that
8883 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00008884 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00008885 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00008886 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00008887
Abramo Bagnara8075c852010-06-12 07:44:57 +00008888 TemplateSpecializationKind PrevDecl_TSK
8889 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
8890
Martin Storsjo5be69bc2019-04-26 08:09:51 +00008891 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
8892 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
8893 // Check for dllexport class template instantiation definitions in MinGW
8894 // mode, if a previous declaration of the instantiation was seen.
8895 for (const ParsedAttr &AL : Attr) {
8896 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
8897 Diag(AL.getLoc(),
8898 diag::warn_attribute_dllexport_explicit_instantiation_def);
8899 break;
8900 }
8901 }
8902 }
8903
Richard Smith0d923af2019-04-26 01:51:07 +00008904 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
8905 SS.isSet(), TSK))
Douglas Gregor6cc1df52010-07-13 00:10:04 +00008906 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008907
Craig Topperc3ec1492014-05-26 06:22:03 +00008908 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00008909
Abramo Bagnara8075c852010-06-12 07:44:57 +00008910 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00008911 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00008912 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00008913 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00008914 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008915 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00008916 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00008917
Abramo Bagnara8075c852010-06-12 07:44:57 +00008918 // Even though HasNoEffect == true means that this explicit instantiation
8919 // has no effect on semantics, we go on to put its syntax in the AST.
8920
8921 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
8922 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008923 // Since the only prior class template specialization with these
8924 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00008925 // declaration node as our own, updating the source location
8926 // for the template name to reflect our new declaration.
8927 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008928 Specialization = PrevDecl;
8929 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00008930 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008931 }
Hans Wennborga86a83b2016-05-26 19:42:56 +00008932
8933 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
8934 DLLImportExplicitInstantiationDef) {
8935 // The new specialization might add a dllimport attribute.
8936 HasNoEffect = false;
8937 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00008938 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00008939
Douglas Gregor4aa04b12009-09-11 21:19:12 +00008940 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00008941 // Create a new class template specialization declaration node for
8942 // this explicit specialization.
8943 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00008944 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00008945 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00008946 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00008947 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00008948 Converted,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008949 PrevDecl);
Bruno Ricci4224c872018-12-21 14:35:24 +00008950 SetNestedNameSpecifier(*this, Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00008951
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00008952 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00008953 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00008954 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00008955 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008956 }
8957
8958 // Build the fully-sugared type for this explicit instantiation as
8959 // the user wrote in the explicit instantiation itself. This means
8960 // that we'll pretty-print the type retrieved from the
8961 // specialization's declaration the way that the user actually wrote
8962 // the explicit instantiation, rather than formatting the name based
8963 // on the "canonical" representation used to store the template
8964 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00008965 TypeSourceInfo *WrittenTy
8966 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
8967 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00008968 Context.getTypeDeclType(Specialization));
8969 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00008970
Abramo Bagnara8075c852010-06-12 07:44:57 +00008971 // Set source locations for keywords.
8972 Specialization->setExternLoc(ExternLoc);
8973 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00008974 Specialization->setBraceRange(SourceRange());
Abramo Bagnara8075c852010-06-12 07:44:57 +00008975
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00008976 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
Erich Keanec480f302018-07-12 21:09:05 +00008977 ProcessDeclAttributeList(S, Specialization, Attr);
Rafael Espindola0b062072012-01-03 06:04:21 +00008978
Abramo Bagnara8075c852010-06-12 07:44:57 +00008979 // Add the explicit instantiation into its lexical context. However,
8980 // since explicit instantiations are never found by name lookup, we
8981 // just put it into the declaration context directly.
8982 Specialization->setLexicalDeclContext(CurContext);
8983 CurContext->addDecl(Specialization);
8984
8985 // Syntax is now OK, so return if it has no other effect on semantics.
8986 if (HasNoEffect) {
8987 // Set the template specialization kind.
8988 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00008989 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00008990 }
Douglas Gregora1f49972009-05-13 00:25:59 +00008991
8992 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00008993 // A definition of a class template or class member template
8994 // shall be in scope at the point of the explicit instantiation of
8995 // the class template or class member template.
8996 //
8997 // This check comes when we actually try to perform the
8998 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00008999 ClassTemplateSpecializationDecl *Def
9000 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009001 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00009002 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00009003 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00009004 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00009005 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00009006 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
9007 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00009008
Douglas Gregor1d957a32009-10-27 18:42:08 +00009009 // Instantiate the members of this class template specialization.
9010 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009011 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00009012 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00009013 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00009014 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
9015 // TSK_ExplicitInstantiationDefinition
9016 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborga86a83b2016-05-26 19:42:56 +00009017 (TSK == TSK_ExplicitInstantiationDefinition ||
9018 DLLImportExplicitInstantiationDef)) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00009019 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00009020 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00009021
Hans Wennborgc0875502015-06-09 00:39:05 +00009022 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
Shoaib Meenaiab3f96c2016-11-09 23:52:20 +00009023 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
9024 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
Hans Wennborgc0875502015-06-09 00:39:05 +00009025 // In the MS ABI, an explicit instantiation definition can add a dll
9026 // attribute to a template with a previous instantiation declaration.
9027 // MinGW doesn't allow this.
Hans Wennborg17f9b442015-05-27 00:06:45 +00009028 auto *A = cast<InheritableAttr>(
9029 getDLLAttr(Specialization)->clone(getASTContext()));
9030 A->setInherited(true);
9031 Def->addAttr(A);
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00009032 dllExportImportClassTemplateSpecialization(*this, Def);
Hans Wennborg17f9b442015-05-27 00:06:45 +00009033 }
9034 }
9035
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00009036 // Fix a TSK_ImplicitInstantiation followed by a
9037 // TSK_ExplicitInstantiationDefinition
Shoaib Meenai5adfb5a2017-01-13 01:28:34 +00009038 bool NewlyDLLExported =
9039 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
9040 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00009041 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
9042 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
9043 // In the MS ABI, an explicit instantiation definition can add a dll
9044 // attribute to a template with a previous implicit instantiation.
9045 // MinGW doesn't allow this. We limit clang to only adding dllexport, to
9046 // avoid potentially strange codegen behavior. For example, if we extend
9047 // this conditional to dllimport, and we have a source file calling a
9048 // method on an implicitly instantiated template class instance and then
9049 // declaring a dllimport explicit instantiation definition for the same
9050 // template class, the codegen for the method call will not respect the
9051 // dllimport, while it will with cl. The Def will already have the DLL
9052 // attribute, since the Def and Specialization will be the same in the
9053 // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
9054 // attribute to the Specialization; we just need to make it take effect.
9055 assert(Def == Specialization &&
9056 "Def and Specialization should match for implicit instantiation");
9057 dllExportImportClassTemplateSpecialization(*this, Def);
9058 }
9059
Martin Storsjo5be69bc2019-04-26 08:09:51 +00009060 // In MinGW mode, export the template instantiation if the declaration
9061 // was marked dllexport.
9062 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
9063 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
9064 PrevDecl->hasAttr<DLLExportAttr>()) {
9065 dllExportImportClassTemplateSpecialization(*this, Def);
9066 }
9067
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00009068 // Set the template specialization kind. Make sure it is set before
9069 // instantiating the members which will trigger ASTConsumer callbacks.
9070 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregor12e49d32009-10-15 22:53:21 +00009071 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00009072 } else {
9073
9074 // Set the template specialization kind.
9075 Specialization->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00009076 }
Douglas Gregora1f49972009-05-13 00:25:59 +00009077
John McCall48871652010-08-21 09:40:31 +00009078 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00009079}
9080
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009081// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00009082DeclResult
Erich Keanec480f302018-07-12 21:09:05 +00009083Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
9084 SourceLocation TemplateLoc, unsigned TagSpec,
9085 SourceLocation KWLoc, CXXScopeSpec &SS,
9086 IdentifierInfo *Name, SourceLocation NameLoc,
9087 const ParsedAttributesView &Attr) {
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009088
Douglas Gregord6ab8742009-05-28 23:31:59 +00009089 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00009090 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00009091 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00009092 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00009093 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00009094 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00009095 SourceLocation(), false, TypeResult(),
Akira Hatanaka12ddcee2017-06-26 18:46:12 +00009096 /*IsTypeSpecifier*/false,
9097 /*IsTemplateParamOrArg*/false);
John McCall7f41d982009-09-11 04:59:25 +00009098 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
9099
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009100 if (!TagD)
9101 return true;
9102
John McCall48871652010-08-21 09:40:31 +00009103 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00009104 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009105
Douglas Gregorb8006faf2009-05-27 17:30:49 +00009106 if (Tag->isInvalidDecl())
9107 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009108
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009109 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
9110 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
9111 if (!Pattern) {
9112 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
9113 << Context.getTypeDeclType(Record);
9114 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
9115 return true;
9116 }
9117
Douglas Gregore47f5a72009-10-14 23:41:34 +00009118 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009119 // If the explicit instantiation is for a class or member class, the
9120 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00009121 // simple-template-id.
9122 //
9123 // C++98 has the same restriction, just worded differently.
9124 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00009125 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00009126 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009127
Douglas Gregore47f5a72009-10-14 23:41:34 +00009128 // C++0x [temp.explicit]p2:
9129 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009130 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00009131 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00009132 TemplateSpecializationKind TSK
9133 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
9134 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009135
Richard Smith0d923af2019-04-26 01:51:07 +00009136 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009137
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009138 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009139 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00009140 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009141 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00009142 PrevDecl = Record;
9143 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009144 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00009145 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009146 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009147 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009148 PrevDecl,
9149 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009150 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00009151 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009152 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00009153 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009154 return TagD;
9155 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009156
Douglas Gregor12e49d32009-10-15 22:53:21 +00009157 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009158 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00009159 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00009160 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009161 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00009162 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009163 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009164 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00009165 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00009166 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
9167 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00009168 Diag(Pattern->getLocation(), diag::note_forward_declaration)
9169 << Pattern;
9170 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00009171 } else {
9172 if (InstantiateClass(NameLoc, Record, Def,
9173 getTemplateInstantiationArgs(Record),
9174 TSK))
9175 return true;
9176
Douglas Gregor0a5a2212010-02-11 01:04:33 +00009177 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00009178 if (!RecordDef)
9179 return true;
9180 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009181 }
9182
Douglas Gregor1d957a32009-10-27 18:42:08 +00009183 // Instantiate all of the members of the class.
9184 InstantiateClassMembers(NameLoc, RecordDef,
9185 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009186
Douglas Gregor88d292c2010-05-13 16:44:06 +00009187 if (TSK == TSK_ExplicitInstantiationDefinition)
9188 MarkVTableUsed(NameLoc, RecordDef, true);
9189
Mike Stump87c57ac2009-05-16 07:39:55 +00009190 // FIXME: We don't have any representation for explicit instantiations of
9191 // member classes. Such a representation is not needed for compilation, but it
9192 // should be available for clients that want to see all of the declarations in
9193 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00009194 return TagD;
9195}
9196
John McCallfaf5fb42010-08-26 23:41:50 +00009197DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
9198 SourceLocation ExternLoc,
9199 SourceLocation TemplateLoc,
9200 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00009201 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009202 // TODO: check if/when DNInfo should replace Name.
9203 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9204 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00009205 if (!Name) {
9206 if (!D.isInvalidType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009207 Diag(D.getDeclSpec().getBeginLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00009208 diag::err_explicit_instantiation_requires_name)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009209 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009210
Douglas Gregor450f00842009-09-25 18:43:00 +00009211 return true;
9212 }
9213
9214 // The scope passed in may not be a decl scope. Zip up the scope tree until
9215 // we find one that is.
9216 while ((S->getFlags() & Scope::DeclScope) == 0 ||
9217 (S->getFlags() & Scope::TemplateParamScope) != 0)
9218 S = S->getParent();
9219
9220 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00009221 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
9222 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00009223 if (R.isNull())
9224 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009225
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009226 // C++ [dcl.stc]p1:
Simon Pilgrim6905d222016-12-30 22:55:33 +00009227 // A storage-class-specifier shall not be specified in [...] an explicit
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009228 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00009229 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00009230 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
9231 << Name;
9232 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009233 } else if (D.getDeclSpec().getStorageClassSpec()
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009234 != DeclSpec::SCS_unspecified) {
9235 // Complain about then remove the storage class specifier.
9236 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
9237 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009238
Douglas Gregor781ba6e2011-05-21 18:53:30 +00009239 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00009240 }
9241
Douglas Gregor3c74d412009-10-14 20:14:33 +00009242 // C++0x [temp.explicit]p1:
9243 // [...] An explicit instantiation of a function template shall not use the
9244 // inline or constexpr specifiers.
9245 // Presumably, this also applies to member functions of class templates as
9246 // well.
Richard Smith83c19292011-10-18 03:44:03 +00009247 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009248 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009249 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00009250 diag::err_explicit_instantiation_inline :
9251 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00009252 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00009253 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00009254 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
9255 // not already specified.
9256 Diag(D.getDeclSpec().getConstexprSpecLoc(),
9257 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009258
Richard Smith19a311a2017-02-09 22:47:51 +00009259 // A deduction guide is not on the list of entities that can be explicitly
9260 // instantiated.
9261 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009262 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
9263 << /*explicit instantiation*/ 0;
Richard Smith19a311a2017-02-09 22:47:51 +00009264 return true;
9265 }
9266
Douglas Gregore47f5a72009-10-14 23:41:34 +00009267 // C++0x [temp.explicit]p2:
9268 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009269 // definition and an explicit instantiation declaration. An explicit
9270 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00009271 TemplateSpecializationKind TSK
9272 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
9273 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009274
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009275 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00009276 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00009277
9278 if (!R->isFunctionType()) {
9279 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009280 // A [...] static data member of a class template can be explicitly
9281 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00009282 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00009283 // C++1y [temp.explicit]p1:
9284 // A [...] variable [...] template specialization can be explicitly
9285 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00009286 if (Previous.isAmbiguous())
9287 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009288
John McCall67c00872009-12-02 08:25:40 +00009289 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00009290 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009291
Larisse Voufo39a1e502013-08-06 01:03:05 +00009292 if (!PrevTemplate) {
9293 if (!Prev || !Prev->isStaticDataMember()) {
Richard Smitha6b41d72019-05-03 23:51:38 +00009294 // We expect to see a static data member here.
Larisse Voufo39a1e502013-08-06 01:03:05 +00009295 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
9296 << Name;
9297 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9298 P != PEnd; ++P)
9299 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
9300 return true;
9301 }
9302
9303 if (!Prev->getInstantiatedFromStaticDataMember()) {
9304 // FIXME: Check for explicit specialization?
9305 Diag(D.getIdentifierLoc(),
9306 diag::err_explicit_instantiation_data_member_not_instantiated)
9307 << Prev;
9308 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
9309 // FIXME: Can we provide a note showing where this was declared?
9310 return true;
9311 }
9312 } else {
9313 // Explicitly instantiate a variable template.
9314
9315 // C++1y [dcl.spec.auto]p6:
9316 // ... A program that uses auto or decltype(auto) in a context not
9317 // explicitly allowed in this section is ill-formed.
9318 //
9319 // This includes auto-typed variable template instantiations.
9320 if (R->isUndeducedType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009321 Diag(T->getTypeLoc().getBeginLoc(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00009322 diag::err_auto_not_allowed_var_inst);
9323 return true;
9324 }
9325
Faisal Vali2ab8c152017-12-30 04:15:27 +00009326 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
Richard Smithef985ac2013-09-18 02:10:12 +00009327 // C++1y [temp.explicit]p3:
9328 // If the explicit instantiation is for a variable, the unqualified-id
9329 // in the declaration shall be a template-id.
9330 Diag(D.getIdentifierLoc(),
9331 diag::err_explicit_instantiation_without_template_id)
9332 << PrevTemplate;
9333 Diag(PrevTemplate->getLocation(),
9334 diag::note_explicit_instantiation_here);
9335 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00009336 }
9337
Richard Smithef985ac2013-09-18 02:10:12 +00009338 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00009339 TemplateArgumentListInfo TemplateArgs =
9340 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00009341
Larisse Voufo39a1e502013-08-06 01:03:05 +00009342 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
9343 D.getIdentifierLoc(), TemplateArgs);
9344 if (Res.isInvalid())
9345 return true;
9346
9347 // Ignore access control bits, we don't need them for redeclaration
9348 // checking.
9349 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00009350 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009351
Douglas Gregore47f5a72009-10-14 23:41:34 +00009352 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009353 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00009354 // or a static data member of a class template specialization, the name of
9355 // the class template specialization in the qualified-id for the member
9356 // name shall be a simple-template-id.
9357 //
9358 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00009359 //
Richard Smith5977d872013-09-18 21:55:14 +00009360 // This does not apply to variable template specializations, where the
9361 // template-id is in the unqualified-id instead.
9362 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009363 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00009364 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00009365 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009366
Richard Smith0d923af2019-04-26 01:51:07 +00009367 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009368
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009369 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00009370 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
9371 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00009372 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00009373 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00009374 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00009375 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009376
Larisse Voufo39a1e502013-08-06 01:03:05 +00009377 if (!HasNoEffect) {
9378 // Instantiate static data member or variable template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00009379 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Louis Dionnee6e81752018-10-10 15:32:29 +00009380 // Merge attributes.
9381 ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
Larisse Voufo39a1e502013-08-06 01:03:05 +00009382 if (TSK == TSK_ExplicitInstantiationDefinition)
9383 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
9384 }
9385
9386 // Check the new variable specialization against the parsed input.
9387 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009388 Diag(T->getTypeLoc().getBeginLoc(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00009389 diag::err_invalid_var_template_spec_type)
9390 << 0 << PrevTemplate << R << Prev->getType();
9391 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
9392 << 2 << PrevTemplate->getDeclName();
9393 return true;
9394 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009395
Douglas Gregor450f00842009-09-25 18:43:00 +00009396 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00009397 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009398 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009399
9400 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00009401 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00009402 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00009403 TemplateArgumentListInfo TemplateArgs;
Faisal Vali2ab8c152017-12-30 04:15:27 +00009404 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00009405 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00009406 HasExplicitTemplateArgs = true;
9407 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009408
Douglas Gregor450f00842009-09-25 18:43:00 +00009409 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009410 // A [...] function [...] can be explicitly instantiated from its template.
9411 // A member function [...] of a class template can be explicitly
9412 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00009413 // template.
John McCall27c11dd2017-06-07 23:00:05 +00009414 UnresolvedSet<8> TemplateMatches;
9415 FunctionDecl *NonTemplateMatch = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009416 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00009417 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9418 P != PEnd; ++P) {
9419 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00009420 if (!HasExplicitTemplateArgs) {
9421 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Richard Smithbaa47832016-12-01 02:11:49 +00009422 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
9423 /*AdjustExceptionSpec*/true);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00009424 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
John McCall27c11dd2017-06-07 23:00:05 +00009425 if (Method->getPrimaryTemplate()) {
9426 TemplateMatches.addDecl(Method, P.getAccess());
9427 } else {
9428 // FIXME: Can this assert ever happen? Needs a test.
9429 assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
9430 NonTemplateMatch = Method;
9431 }
Douglas Gregord90fd522009-09-25 21:45:23 +00009432 }
Douglas Gregor450f00842009-09-25 18:43:00 +00009433 }
9434 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009435
Douglas Gregor450f00842009-09-25 18:43:00 +00009436 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
9437 if (!FunTmpl)
9438 continue;
9439
Larisse Voufo98b20f12013-07-19 23:00:19 +00009440 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00009441 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009442 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009443 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00009444 (HasExplicitTemplateArgs ? &TemplateArgs
9445 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00009446 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009447 // Keep track of almost-matches.
9448 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +00009449 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +00009450 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00009451 (void)TDK;
9452 continue;
9453 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009454
Artem Belevich64135c32016-12-08 19:38:13 +00009455 // Target attributes are part of the cuda function signature, so
9456 // the cuda target of the instantiated function must match that of its
9457 // template. Given that C++ template deduction does not take
9458 // target attributes into account, we reject candidates here that
9459 // have a different target.
9460 if (LangOpts.CUDA &&
9461 IdentifyCUDATarget(Specialization,
9462 /* IgnoreImplicitHDAttributes = */ true) !=
Erich Keanec480f302018-07-12 21:09:05 +00009463 IdentifyCUDATarget(D.getDeclSpec().getAttributes())) {
Artem Belevich64135c32016-12-08 19:38:13 +00009464 FailedCandidates.addCandidate().set(
9465 P.getPair(), FunTmpl->getTemplatedDecl(),
9466 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
9467 continue;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00009468 }
9469
John McCall27c11dd2017-06-07 23:00:05 +00009470 TemplateMatches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00009471 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009472
John McCall27c11dd2017-06-07 23:00:05 +00009473 FunctionDecl *Specialization = NonTemplateMatch;
9474 if (!Specialization) {
9475 // Find the most specialized function template specialization.
9476 UnresolvedSetIterator Result = getMostSpecialized(
9477 TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
9478 D.getIdentifierLoc(),
9479 PDiag(diag::err_explicit_instantiation_not_known) << Name,
9480 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
9481 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00009482
John McCall27c11dd2017-06-07 23:00:05 +00009483 if (Result == TemplateMatches.end())
9484 return true;
John McCall58cc69d2010-01-27 01:50:18 +00009485
John McCall27c11dd2017-06-07 23:00:05 +00009486 // Ignore access control bits, we don't need them for redeclaration checking.
9487 Specialization = cast<FunctionDecl>(*Result);
9488 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009489
Alexey Bataev73983912014-11-06 10:10:50 +00009490 // C++11 [except.spec]p4
9491 // In an explicit instantiation an exception-specification may be specified,
9492 // but is not required.
9493 // If an exception-specification is specified in an explicit instantiation
9494 // directive, it shall be compatible with the exception-specifications of
9495 // other declarations of that function.
9496 if (auto *FPT = R->getAs<FunctionProtoType>())
9497 if (FPT->hasExceptionSpec()) {
9498 unsigned DiagID =
9499 diag::err_mismatched_exception_spec_explicit_instantiation;
9500 if (getLangOpts().MicrosoftExt)
9501 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
9502 bool Result = CheckEquivalentExceptionSpec(
9503 PDiag(DiagID) << Specialization->getType(),
9504 PDiag(diag::note_explicit_instantiation_here),
9505 Specialization->getType()->getAs<FunctionProtoType>(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009506 Specialization->getLocation(), FPT, D.getBeginLoc());
Alexey Bataev73983912014-11-06 10:10:50 +00009507 // In Microsoft mode, mismatching exception specifications just cause a
9508 // warning.
9509 if (!getLangOpts().MicrosoftExt && Result)
9510 return true;
9511 }
9512
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009513 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009514 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00009515 diag::err_explicit_instantiation_member_function_not_instantiated)
9516 << Specialization
9517 << (Specialization->getTemplateSpecializationKind() ==
9518 TSK_ExplicitSpecialization);
9519 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
9520 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009521 }
9522
Douglas Gregorec9fd132012-01-14 16:38:05 +00009523 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00009524 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
9525 PrevDecl = Specialization;
9526
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009527 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00009528 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00009529 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009530 PrevDecl,
9531 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009532 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00009533 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009534 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009535
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009536 // FIXME: We may still want to build some representation of this
9537 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00009538 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00009539 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009540 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00009541
Richard Smith0d923af2019-04-26 01:51:07 +00009542 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
9543 // functions
9544 // valarray<size_t>::valarray(size_t) and
9545 // valarray<size_t>::~valarray()
9546 // that it declared to have internal linkage with the internal_linkage
9547 // attribute. Ignore the explicit instantiation declaration in this case.
9548 if (Specialization->hasAttr<InternalLinkageAttr>() &&
9549 TSK == TSK_ExplicitInstantiationDeclaration) {
9550 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
9551 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
9552 RD->isInStdNamespace())
9553 return (Decl*) nullptr;
9554 }
9555
Erich Keanec480f302018-07-12 21:09:05 +00009556 ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009557
Hans Wennborgb8304a62017-11-29 23:44:11 +00009558 // In MSVC mode, dllimported explicit instantiation definitions are treated as
9559 // instantiation declarations.
9560 if (TSK == TSK_ExplicitInstantiationDefinition &&
9561 Specialization->hasAttr<DLLImportAttr>() &&
9562 Context.getTargetInfo().getCXXABI().isMicrosoft())
9563 TSK = TSK_ExplicitInstantiationDeclaration;
9564
9565 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9566
Richard Smitheb36ddf2014-04-24 22:45:46 +00009567 if (Specialization->isDefined()) {
9568 // Let the ASTConsumer know that this function has been explicitly
9569 // instantiated now, and its linkage might have changed.
9570 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
9571 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00009572 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009573
Douglas Gregore47f5a72009-10-14 23:41:34 +00009574 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009575 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00009576 // or a static data member of a class template specialization, the name of
9577 // the class template specialization in the qualified-id for the member
9578 // name shall be a simple-template-id.
9579 //
9580 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00009581 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Faisal Vali2ab8c152017-12-30 04:15:27 +00009582 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009583 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00009584 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009585 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00009586 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00009587 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009588
Richard Smith0d923af2019-04-26 01:51:07 +00009589 CheckExplicitInstantiation(
9590 *this,
9591 FunTmpl ? (NamedDecl *)FunTmpl
9592 : Specialization->getInstantiatedFromMemberFunction(),
9593 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009594
Douglas Gregor450f00842009-09-25 18:43:00 +00009595 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00009596 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00009597}
9598
John McCallfaf5fb42010-08-26 23:41:50 +00009599TypeResult
Faisal Vali090da2d2018-01-01 18:23:28 +00009600Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
John McCall7f41d982009-09-11 04:59:25 +00009601 const CXXScopeSpec &SS, IdentifierInfo *Name,
9602 SourceLocation TagLoc, SourceLocation NameLoc) {
9603 // This has to hold, because SS is expected to be defined.
9604 assert(Name && "Expected a name in a dependent tag");
9605
Aaron Ballman4a979672014-01-03 13:56:08 +00009606 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00009607 if (!NNS)
9608 return true;
9609
Abramo Bagnara6150c882010-05-11 21:36:43 +00009610 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00009611
Douglas Gregorba41d012010-04-24 16:38:41 +00009612 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
9613 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00009614 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00009615 return true;
9616 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00009617
Douglas Gregore7c20652011-03-02 00:47:37 +00009618 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00009619 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00009620 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009621
Douglas Gregore7c20652011-03-02 00:47:37 +00009622 // Create type-source location information for this type.
9623 TypeLocBuilder TLB;
9624 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009625 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00009626 TL.setQualifierLoc(SS.getWithLocInContext(Context));
9627 TL.setNameLoc(NameLoc);
9628 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00009629}
9630
John McCallfaf5fb42010-08-26 23:41:50 +00009631TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009632Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
9633 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00009634 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009635 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00009636 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009637
Richard Smith0bf8a4922011-10-18 20:49:44 +00009638 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9639 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009640 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00009641 diag::warn_cxx98_compat_typename_outside_of_template :
9642 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009643 << FixItHint::CreateRemoval(TypenameLoc);
9644
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009645 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00009646 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
9647 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00009648 if (T.isNull())
9649 return true;
John McCall99b2fe52010-04-29 23:50:39 +00009650
9651 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9652 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00009653 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009654 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009655 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00009656 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00009657 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00009658 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009659 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009660 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00009661 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00009662 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009663
John McCallba7bf592010-08-24 05:47:05 +00009664 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00009665}
9666
John McCallfaf5fb42010-08-26 23:41:50 +00009667TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009668Sema::ActOnTypenameType(Scope *S,
9669 SourceLocation TypenameLoc,
9670 const CXXScopeSpec &SS,
9671 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00009672 TemplateTy TemplateIn,
Richard Smith74f02342017-01-19 21:00:13 +00009673 IdentifierInfo *TemplateII,
9674 SourceLocation TemplateIILoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00009675 SourceLocation LAngleLoc,
9676 ASTTemplateArgsPtr TemplateArgsIn,
9677 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00009678 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9679 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009680 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00009681 diag::warn_cxx98_compat_typename_outside_of_template :
9682 diag::ext_typename_outside_of_template)
9683 << FixItHint::CreateRemoval(TypenameLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009684
Richard Smith74f02342017-01-19 21:00:13 +00009685 // Strangely, non-type results are not ignored by this lookup, so the
9686 // program is ill-formed if it finds an injected-class-name.
Richard Smith62559bd2017-02-01 21:36:38 +00009687 if (TypenameLoc.isValid()) {
9688 auto *LookupRD =
9689 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
9690 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
9691 Diag(TemplateIILoc,
9692 diag::ext_out_of_line_qualified_id_type_names_constructor)
9693 << TemplateII << 0 /*injected-class-name used as template name*/
9694 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
9695 }
Richard Smith74f02342017-01-19 21:00:13 +00009696 }
9697
Douglas Gregorb09518c2011-02-27 22:46:49 +00009698 // Translate the parser's template argument list in our AST format.
9699 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9700 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009701
Douglas Gregorb09518c2011-02-27 22:46:49 +00009702 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009703 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
9704 // Construct a dependent template specialization type.
9705 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00009706 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009707 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
9708 DTN->getQualifier(),
9709 DTN->getIdentifier(),
9710 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00009711
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009712 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00009713 TypeLocBuilder Builder;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009714 DependentTemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009715 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009716 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
9717 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00009718 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00009719 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009720 SpecTL.setLAngleLoc(LAngleLoc);
9721 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009722 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9723 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009724 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00009725 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009726
Richard Smith74f02342017-01-19 21:00:13 +00009727 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009728 if (T.isNull())
9729 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00009730
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009731 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00009732 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009733 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009734 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00009735 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Richard Smith74f02342017-01-19 21:00:13 +00009736 SpecTL.setTemplateNameLoc(TemplateIILoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009737 SpecTL.setLAngleLoc(LAngleLoc);
9738 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00009739 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9740 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009741
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009742 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
9743 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009744 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009745 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Simon Pilgrim6905d222016-12-30 22:55:33 +00009746
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00009747 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
9748 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00009749}
9750
Douglas Gregorb09518c2011-02-27 22:46:49 +00009751
Richard Smith6f8d2c62012-05-09 05:17:00 +00009752/// Determine whether this failed name lookup should be treated as being
9753/// disabled by a usage of std::enable_if.
9754static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009755 SourceRange &CondRange, Expr *&Cond) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00009756 // We must be looking for a ::type...
9757 if (!II.isStr("type"))
9758 return false;
9759
9760 // ... within an explicitly-written template specialization...
9761 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
9762 return false;
9763 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00009764 TemplateSpecializationTypeLoc EnableIfTSTLoc =
9765 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
9766 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00009767 return false;
George Burgess IV00f70bd2018-03-01 05:43:23 +00009768 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009769
9770 // ... which names a complete class template declaration...
9771 const TemplateDecl *EnableIfDecl =
9772 EnableIfTST->getTemplateName().getAsTemplateDecl();
9773 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
9774 return false;
9775
9776 // ... called "enable_if".
9777 const IdentifierInfo *EnableIfII =
9778 EnableIfDecl->getDeclName().getAsIdentifierInfo();
9779 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
9780 return false;
9781
9782 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00009783 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009784
9785 // Dig out the condition.
9786 Cond = nullptr;
9787 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
9788 != TemplateArgument::Expression)
9789 return true;
9790
9791 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
9792
9793 // Ignore Boolean literals; they add no value.
9794 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
9795 Cond = nullptr;
9796
Richard Smith6f8d2c62012-05-09 05:17:00 +00009797 return true;
9798}
9799
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009800/// Build the type that describes a C++ typename specifier,
Douglas Gregor333489b2009-03-27 23:10:48 +00009801/// e.g., "typename T::type".
9802QualType
Simon Pilgrim6905d222016-12-30 22:55:33 +00009803Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009804 SourceLocation KeywordLoc,
Simon Pilgrim6905d222016-12-30 22:55:33 +00009805 NestedNameSpecifierLoc QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009806 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00009807 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00009808 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009809 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00009810
John McCall0b66eb32010-05-01 00:40:08 +00009811 DeclContext *Ctx = computeDeclContext(SS);
9812 if (!Ctx) {
9813 // If the nested-name-specifier is dependent and couldn't be
9814 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009815 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
Simon Pilgrim6905d222016-12-30 22:55:33 +00009816 return Context.getDependentNameType(Keyword,
9817 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009818 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00009819 }
Douglas Gregor333489b2009-03-27 23:10:48 +00009820
John McCall0b66eb32010-05-01 00:40:08 +00009821 // If the nested-name-specifier refers to the current instantiation,
9822 // the "typename" keyword itself is superfluous. In C++03, the
9823 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
9824 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00009825 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00009826
John McCall0b66eb32010-05-01 00:40:08 +00009827 if (RequireCompleteDeclContext(SS, Ctx))
9828 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00009829
9830 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00009831 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00009832 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00009833 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00009834 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00009835 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00009836 case LookupResult::NotFound: {
9837 // If we're looking up 'type' within a template named 'enable_if', produce
9838 // a more specific diagnostic.
9839 SourceRange CondRange;
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009840 Expr *Cond = nullptr;
9841 if (isEnableIf(QualifierLoc, II, CondRange, Cond)) {
9842 // If we have a condition, narrow it down to the specific failed
9843 // condition.
9844 if (Cond) {
9845 Expr *FailedCond;
9846 std::string FailedDescription;
9847 std::tie(FailedCond, FailedDescription) =
Clement Courbetf44c6f42018-12-11 08:39:11 +00009848 findFailedBooleanCondition(Cond);
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009849
9850 Diag(FailedCond->getExprLoc(),
9851 diag::err_typename_nested_not_found_requirement)
9852 << FailedDescription
9853 << FailedCond->getSourceRange();
9854 return QualType();
9855 }
9856
Richard Smith6f8d2c62012-05-09 05:17:00 +00009857 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009858 << Ctx << CondRange;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009859 return QualType();
9860 }
9861
Douglas Gregore40876a2009-10-13 21:16:44 +00009862 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00009863 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009864 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009865
9866 case LookupResult::FoundUnresolvedValue: {
9867 // We found a using declaration that is a value. Most likely, the using
9868 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009869 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009870 IILoc);
9871 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
9872 << Name << Ctx << FullRange;
9873 if (UnresolvedUsingValueDecl *Using
9874 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009875 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00009876 Diag(Loc, diag::note_using_value_decl_missing_typename)
9877 << FixItHint::CreateInsertion(Loc, "typename ");
9878 }
9879 }
9880 // Fall through to create a dependent typename type, from which we can recover
9881 // better.
Galina Kistanova3779cb32017-06-07 06:25:05 +00009882 LLVM_FALLTHROUGH;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009883
Douglas Gregord0d2ee02010-01-15 01:44:47 +00009884 case LookupResult::NotFoundInCurrentInstantiation:
9885 // Okay, it's a member of an unknown instantiation.
Simon Pilgrim6905d222016-12-30 22:55:33 +00009886 return Context.getDependentNameType(Keyword,
9887 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009888 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00009889
9890 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009891 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Richard Smith74f02342017-01-19 21:00:13 +00009892 // C++ [class.qual]p2:
9893 // In a lookup in which function names are not ignored and the
9894 // nested-name-specifier nominates a class C, if the name specified
9895 // after the nested-name-specifier, when looked up in C, is the
9896 // injected-class-name of C [...] then the name is instead considered
9897 // to name the constructor of class C.
9898 //
9899 // Unlike in an elaborated-type-specifier, function names are not ignored
9900 // in typename-specifier lookup. However, they are ignored in all the
9901 // contexts where we form a typename type with no keyword (that is, in
9902 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
9903 //
9904 // FIXME: That's not strictly true: mem-initializer-id lookup does not
9905 // ignore functions, but that appears to be an oversight.
9906 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
9907 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
9908 if (Keyword == ETK_Typename && LookupRD && FoundRD &&
9909 FoundRD->isInjectedClassName() &&
9910 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
9911 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
9912 << &II << 1 << 0 /*'typename' keyword used*/;
9913
Abramo Bagnara6150c882010-05-11 21:36:43 +00009914 // We found a type. Build an ElaboratedType, since the
9915 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00009916 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Richard Smith74f02342017-01-19 21:00:13 +00009917 return Context.getElaboratedType(Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009918 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00009919 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00009920 }
9921
Richard Smithee579842017-01-30 20:39:26 +00009922 // C++ [dcl.type.simple]p2:
9923 // A type-specifier of the form
9924 // typename[opt] nested-name-specifier[opt] template-name
9925 // is a placeholder for a deduced class type [...].
Aaron Ballmanc351fba2017-12-04 20:27:34 +00009926 if (getLangOpts().CPlusPlus17) {
Richard Smithee579842017-01-30 20:39:26 +00009927 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
9928 return Context.getElaboratedType(
9929 Keyword, QualifierLoc.getNestedNameSpecifier(),
9930 Context.getDeducedTemplateSpecializationType(TemplateName(TD),
9931 QualType(), false));
9932 }
9933 }
Richard Smith600b5262017-01-26 20:40:47 +00009934
Douglas Gregor333489b2009-03-27 23:10:48 +00009935 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00009936 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00009937 break;
9938
9939 case LookupResult::FoundOverloaded:
9940 DiagID = diag::err_typename_nested_not_type;
9941 Referenced = *Result.begin();
9942 break;
9943
John McCall6538c932009-10-10 05:48:19 +00009944 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00009945 return QualType();
9946 }
9947
9948 // If we get here, it's because name lookup did not find a
9949 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009950 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00009951 IILoc);
9952 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00009953 if (Referenced)
9954 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
9955 << Name;
9956 return QualType();
9957}
Douglas Gregor15acfb92009-08-06 16:20:37 +00009958
9959namespace {
9960 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00009961 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00009962 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00009963 SourceLocation Loc;
9964 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00009965
Douglas Gregor15acfb92009-08-06 16:20:37 +00009966 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00009967 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009968
Mike Stump11289f42009-09-09 15:08:12 +00009969 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00009970 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00009971 DeclarationName Entity)
9972 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00009973 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00009974
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009975 /// Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00009976 /// transformed.
9977 ///
9978 /// For the purposes of type reconstruction, a type has already been
9979 /// transformed if it is NULL or if it is not dependent.
9980 bool AlreadyTransformed(QualType T) {
9981 return T.isNull() || !T->isDependentType();
9982 }
Mike Stump11289f42009-09-09 15:08:12 +00009983
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009984 /// Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00009985 /// rebuilt.
9986 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00009987
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009988 /// Returns the name of the entity whose type is being rebuilt.
Douglas Gregor15acfb92009-08-06 16:20:37 +00009989 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00009990
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009991 /// Sets the "base" location and entity when that
Douglas Gregoref6ab412009-10-27 06:26:26 +00009992 /// information is known based on another transformation.
9993 void setBase(SourceLocation Loc, DeclarationName Entity) {
9994 this->Loc = Loc;
9995 this->Entity = Entity;
9996 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00009997
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00009998 ExprResult TransformLambdaExpr(LambdaExpr *E) {
9999 // Lambdas never need to be transformed.
10000 return E;
10001 }
Douglas Gregor15acfb92009-08-06 16:20:37 +000010002 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010003} // end anonymous namespace
Douglas Gregor15acfb92009-08-06 16:20:37 +000010004
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010005/// Rebuilds a type within the context of the current instantiation.
Douglas Gregor15acfb92009-08-06 16:20:37 +000010006///
Mike Stump11289f42009-09-09 15:08:12 +000010007/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +000010008/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +000010009/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +000010010/// partial specialization thereof). This routine will rebuild that type now
10011/// that we have entered the declarator's scope, which may produce different
10012/// canonical types, e.g.,
10013///
10014/// \code
10015/// template<typename T>
10016/// struct X {
10017/// typedef T* pointer;
10018/// pointer data();
10019/// };
10020///
10021/// template<typename T>
10022/// typename X<T>::pointer X<T>::data() { ... }
10023/// \endcode
10024///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +000010025/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +000010026/// since we do not know that we can look into X<T> when we parsed the type.
10027/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +000010028/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +000010029/// as the canonical type of T*, allowing the return types of the out-of-line
10030/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +000010031TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
10032 SourceLocation Loc,
10033 DeclarationName Name) {
10034 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +000010035 return T;
Mike Stump11289f42009-09-09 15:08:12 +000010036
Douglas Gregor15acfb92009-08-06 16:20:37 +000010037 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
10038 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +000010039}
Douglas Gregorbe999392009-09-15 16:23:51 +000010040
John McCalldadc5752010-08-24 06:29:42 +000010041ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +000010042 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
10043 DeclarationName());
10044 return Rebuilder.TransformExpr(E);
10045}
10046
John McCall99b2fe52010-04-29 23:50:39 +000010047bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Simon Pilgrim6905d222016-12-30 22:55:33 +000010048 if (SS.isInvalid())
Douglas Gregor10176412011-02-25 16:07:42 +000010049 return true;
John McCall2408e322010-04-27 00:57:59 +000010050
Douglas Gregor10176412011-02-25 16:07:42 +000010051 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +000010052 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
10053 DeclarationName());
Simon Pilgrim6905d222016-12-30 22:55:33 +000010054 NestedNameSpecifierLoc Rebuilt
Douglas Gregor10176412011-02-25 16:07:42 +000010055 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +000010056 if (!Rebuilt)
Douglas Gregor10176412011-02-25 16:07:42 +000010057 return true;
John McCall99b2fe52010-04-29 23:50:39 +000010058
Douglas Gregor10176412011-02-25 16:07:42 +000010059 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +000010060 return false;
John McCall2408e322010-04-27 00:57:59 +000010061}
10062
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010063/// Rebuild the template parameters now that we know we're in a current
Douglas Gregor041b0842011-10-14 15:31:12 +000010064/// instantiation.
10065bool Sema::RebuildTemplateParamsInCurrentInstantiation(
10066 TemplateParameterList *Params) {
10067 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
10068 Decl *Param = Params->getParam(I);
Simon Pilgrim6905d222016-12-30 22:55:33 +000010069
Douglas Gregor041b0842011-10-14 15:31:12 +000010070 // There is nothing to rebuild in a type parameter.
10071 if (isa<TemplateTypeParmDecl>(Param))
10072 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +000010073
Douglas Gregor041b0842011-10-14 15:31:12 +000010074 // Rebuild the template parameter list of a template template parameter.
Simon Pilgrim6905d222016-12-30 22:55:33 +000010075 if (TemplateTemplateParmDecl *TTP
Douglas Gregor041b0842011-10-14 15:31:12 +000010076 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
10077 if (RebuildTemplateParamsInCurrentInstantiation(
10078 TTP->getTemplateParameters()))
10079 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +000010080
Douglas Gregor041b0842011-10-14 15:31:12 +000010081 continue;
10082 }
Simon Pilgrim6905d222016-12-30 22:55:33 +000010083
Douglas Gregor041b0842011-10-14 15:31:12 +000010084 // Rebuild the type of a non-type template parameter.
10085 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
Simon Pilgrim6905d222016-12-30 22:55:33 +000010086 TypeSourceInfo *NewTSI
10087 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
10088 NTTP->getLocation(),
Douglas Gregor041b0842011-10-14 15:31:12 +000010089 NTTP->getDeclName());
10090 if (!NewTSI)
10091 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +000010092
Erik Pilkington9f9462a2018-08-07 22:59:02 +000010093 if (NewTSI->getType()->isUndeducedType()) {
10094 // C++17 [temp.dep.expr]p3:
10095 // An id-expression is type-dependent if it contains
10096 // - an identifier associated by name lookup with a non-type
10097 // template-parameter declared with a type that contains a
10098 // placeholder type (7.1.7.4),
10099 NewTSI = SubstAutoTypeSourceInfo(NewTSI, Context.DependentTy);
10100 }
10101
Douglas Gregor041b0842011-10-14 15:31:12 +000010102 if (NewTSI != NTTP->getTypeSourceInfo()) {
10103 NTTP->setTypeSourceInfo(NewTSI);
10104 NTTP->setType(NewTSI->getType());
10105 }
10106 }
Simon Pilgrim6905d222016-12-30 22:55:33 +000010107
Douglas Gregor041b0842011-10-14 15:31:12 +000010108 return false;
10109}
10110
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010111/// Produces a formatted string that describes the binding of
Douglas Gregorbe999392009-09-15 16:23:51 +000010112/// template parameters to template arguments.
10113std::string
10114Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
10115 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +000010116 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +000010117}
10118
10119std::string
10120Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
10121 const TemplateArgument *Args,
10122 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000010123 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +000010124 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +000010125
Douglas Gregore62e6a02009-11-11 19:13:48 +000010126 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +000010127 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010128
Douglas Gregorbe999392009-09-15 16:23:51 +000010129 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +000010130 if (I >= NumArgs)
10131 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010132
Douglas Gregorbe999392009-09-15 16:23:51 +000010133 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +000010134 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +000010135 else
Douglas Gregor0192c232010-12-20 16:52:59 +000010136 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010137
Douglas Gregorbe999392009-09-15 16:23:51 +000010138 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +000010139 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +000010140 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +000010141 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +000010142 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010143
Douglas Gregor0192c232010-12-20 16:52:59 +000010144 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +000010145 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +000010146 }
Douglas Gregor0192c232010-12-20 16:52:59 +000010147
10148 Out << ']';
10149 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +000010150}
Francois Pichet1c229c02011-04-22 22:18:13 +000010151
Richard Smithe40f2ba2013-08-07 21:41:30 +000010152void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
10153 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +000010154 if (!FD)
10155 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +000010156
Justin Lebar28f09c52016-10-10 16:26:08 +000010157 auto LPT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +000010158
10159 // Take tokens to avoid allocations
10160 LPT->Toks.swap(Toks);
10161 LPT->D = FnD;
Justin Lebar28f09c52016-10-10 16:26:08 +000010162 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +000010163
10164 FD->setLateTemplateParsed(true);
10165}
10166
10167void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
10168 if (!FD)
10169 return;
10170 FD->setLateTemplateParsed(false);
10171}
Francois Pichet1c229c02011-04-22 22:18:13 +000010172
10173bool Sema::IsInsideALocalClassWithinATemplateFunction() {
10174 DeclContext *DC = CurContext;
10175
10176 while (DC) {
10177 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
10178 const FunctionDecl *FD = RD->isLocalClass();
10179 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
10180 } else if (DC->isTranslationUnit() || DC->isNamespace())
10181 return false;
10182
10183 DC = DC->getParent();
10184 }
10185 return false;
10186}
Richard Smith6739a102016-05-05 00:56:12 +000010187
Benjamin Kramera0a13c32016-08-06 11:21:04 +000010188namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010189/// Walk the path from which a declaration was instantiated, and check
Richard Smith6739a102016-05-05 00:56:12 +000010190/// that every explicit specialization along that path is visible. This enforces
10191/// C++ [temp.expl.spec]/6:
10192///
10193/// If a template, a member template or a member of a class template is
10194/// explicitly specialized then that specialization shall be declared before
10195/// the first use of that specialization that would cause an implicit
10196/// instantiation to take place, in every translation unit in which such a
10197/// use occurs; no diagnostic is required.
10198///
10199/// and also C++ [temp.class.spec]/1:
10200///
10201/// A partial specialization shall be declared before the first use of a
10202/// class template specialization that would make use of the partial
10203/// specialization as the result of an implicit or explicit instantiation
10204/// in every translation unit in which such a use occurs; no diagnostic is
10205/// required.
10206class ExplicitSpecializationVisibilityChecker {
10207 Sema &S;
10208 SourceLocation Loc;
10209 llvm::SmallVector<Module *, 8> Modules;
10210
10211public:
10212 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
10213 : S(S), Loc(Loc) {}
10214
10215 void check(NamedDecl *ND) {
10216 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10217 return checkImpl(FD);
10218 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
10219 return checkImpl(RD);
10220 if (auto *VD = dyn_cast<VarDecl>(ND))
10221 return checkImpl(VD);
10222 if (auto *ED = dyn_cast<EnumDecl>(ND))
10223 return checkImpl(ED);
10224 }
10225
10226private:
10227 void diagnose(NamedDecl *D, bool IsPartialSpec) {
10228 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
10229 : Sema::MissingImportKind::ExplicitSpecialization;
10230 const bool Recover = true;
10231
10232 // If we got a custom set of modules (because only a subset of the
10233 // declarations are interesting), use them, otherwise let
10234 // diagnoseMissingImport intelligently pick some.
10235 if (Modules.empty())
10236 S.diagnoseMissingImport(Loc, D, Kind, Recover);
10237 else
10238 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
10239 }
10240
10241 // Check a specific declaration. There are three problematic cases:
10242 //
10243 // 1) The declaration is an explicit specialization of a template
10244 // specialization.
10245 // 2) The declaration is an explicit specialization of a member of an
10246 // templated class.
10247 // 3) The declaration is an instantiation of a template, and that template
10248 // is an explicit specialization of a member of a templated class.
10249 //
10250 // We don't need to go any deeper than that, as the instantiation of the
10251 // surrounding class / etc is not triggered by whatever triggered this
10252 // instantiation, and thus should be checked elsewhere.
10253 template<typename SpecDecl>
10254 void checkImpl(SpecDecl *Spec) {
10255 bool IsHiddenExplicitSpecialization = false;
10256 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
10257 IsHiddenExplicitSpecialization =
10258 Spec->getMemberSpecializationInfo()
10259 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
Richard Smith54f04402017-05-18 02:29:20 +000010260 : !S.hasVisibleExplicitSpecialization(Spec, &Modules);
Richard Smith6739a102016-05-05 00:56:12 +000010261 } else {
10262 checkInstantiated(Spec);
10263 }
10264
10265 if (IsHiddenExplicitSpecialization)
10266 diagnose(Spec->getMostRecentDecl(), false);
10267 }
10268
10269 void checkInstantiated(FunctionDecl *FD) {
10270 if (auto *TD = FD->getPrimaryTemplate())
10271 checkTemplate(TD);
10272 }
10273
10274 void checkInstantiated(CXXRecordDecl *RD) {
10275 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
10276 if (!SD)
10277 return;
10278
10279 auto From = SD->getSpecializedTemplateOrPartial();
10280 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
10281 checkTemplate(TD);
10282 else if (auto *TD =
10283 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
10284 if (!S.hasVisibleDeclaration(TD))
10285 diagnose(TD, true);
10286 checkTemplate(TD);
10287 }
10288 }
10289
10290 void checkInstantiated(VarDecl *RD) {
10291 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
10292 if (!SD)
10293 return;
10294
10295 auto From = SD->getSpecializedTemplateOrPartial();
10296 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
10297 checkTemplate(TD);
10298 else if (auto *TD =
10299 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
10300 if (!S.hasVisibleDeclaration(TD))
10301 diagnose(TD, true);
10302 checkTemplate(TD);
10303 }
10304 }
10305
10306 void checkInstantiated(EnumDecl *FD) {}
10307
10308 template<typename TemplDecl>
10309 void checkTemplate(TemplDecl *TD) {
10310 if (TD->isMemberSpecialization()) {
10311 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
10312 diagnose(TD->getMostRecentDecl(), false);
10313 }
10314 }
10315};
Benjamin Kramera0a13c32016-08-06 11:21:04 +000010316} // end anonymous namespace
Richard Smith6739a102016-05-05 00:56:12 +000010317
10318void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
10319 if (!getLangOpts().Modules)
10320 return;
10321
10322 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
10323}
10324
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010325/// Check whether a template partial specialization that we've discovered
Richard Smith6739a102016-05-05 00:56:12 +000010326/// is hidden, and produce suitable diagnostics if so.
10327void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
10328 NamedDecl *Spec) {
10329 llvm::SmallVector<Module *, 8> Modules;
10330 if (!hasVisibleDeclaration(Spec, &Modules))
10331 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
10332 MissingImportKind::PartialSpecialization,
10333 /*Recover*/true);
10334}