blob: ec2f598814541a9c5d18de59d1448ab3dcf6ff74 [file] [log] [blame]
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
Douglas Gregor5101c242008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007//===----------------------------------------------------------------------===//
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010//===----------------------------------------------------------------------===//
Douglas Gregor5101c242008-12-05 18:15:24 +000011
Douglas Gregor15acfb92009-08-06 16:20:37 +000012#include "TreeTransform.h"
Larisse Voufo39a1e502013-08-06 01:03:05 +000013#include "clang/AST/ASTConsumer.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000014#include "clang/AST/ASTContext.h"
John McCallbbbbe4e2010-03-11 07:50:04 +000015#include "clang/AST/DeclFriend.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000016#include "clang/AST/DeclTemplate.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
John McCalla020a012010-10-20 05:44:58 +000019#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor7731d3f2010-10-13 00:27:52 +000020#include "clang/AST/TypeVisitor.h"
David Majnemerd9b1a4f2015-11-04 03:40:30 +000021#include "clang/Basic/Builtins.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000022#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000023#include "clang/Basic/PartialDiagnostic.h"
David Majnemer763584d2014-02-06 10:59:19 +000024#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Sema/DeclSpec.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/ParsedTemplate.h"
28#include "clang/Sema/Scope.h"
29#include "clang/Sema/SemaInternal.h"
30#include "clang/Sema/Template.h"
31#include "clang/Sema/TemplateDeduction.h"
Benjamin Kramere0513cb2012-01-30 16:17:39 +000032#include "llvm/ADT/SmallBitVector.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000033#include "llvm/ADT/SmallString.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000034#include "llvm/ADT/StringExtras.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000035
Eric Fiselier6ad68552016-07-01 01:24:09 +000036#include <iterator>
Douglas Gregor5101c242008-12-05 18:15:24 +000037using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000038using namespace sema;
Douglas Gregor5101c242008-12-05 18:15:24 +000039
John McCall9b72f892010-11-10 02:40:36 +000040// Exported for use by Parser.
41SourceRange
42clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
43 unsigned N) {
44 if (!N) return SourceRange();
45 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
46}
47
Douglas Gregorb7bfe792009-09-02 22:59:36 +000048/// \brief Determine whether the declaration found is acceptable as the name
49/// of a template and, if so, return that template declaration. Otherwise,
50/// returns NULL.
John McCalle9cccd82010-06-16 08:42:20 +000051static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000052 NamedDecl *Orig,
53 bool AllowFunctionTemplates) {
John McCalle9cccd82010-06-16 08:42:20 +000054 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +000055
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000056 if (isa<TemplateDecl>(D)) {
57 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +000058 return nullptr;
59
John McCalle9cccd82010-06-16 08:42:20 +000060 return Orig;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000061 }
Mike Stump11289f42009-09-09 15:08:12 +000062
Douglas Gregorb7bfe792009-09-02 22:59:36 +000063 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
64 // C++ [temp.local]p1:
65 // Like normal (non-template) classes, class templates have an
66 // injected-class-name (Clause 9). The injected-class-name
67 // can be used with or without a template-argument-list. When
68 // it is used without a template-argument-list, it is
69 // equivalent to the injected-class-name followed by the
70 // template-parameters of the class template enclosed in
71 // <>. When it is used with a template-argument-list, it
72 // refers to the specified class template specialization,
73 // which could be the current specialization or another
74 // specialization.
75 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000076 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000077 if (Record->getDescribedClassTemplate())
78 return Record->getDescribedClassTemplate();
79
80 if (ClassTemplateSpecializationDecl *Spec
81 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
82 return Spec->getSpecializedTemplate();
83 }
Mike Stump11289f42009-09-09 15:08:12 +000084
Craig Topperc3ec1492014-05-26 06:22:03 +000085 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +000086 }
Mike Stump11289f42009-09-09 15:08:12 +000087
Craig Topperc3ec1492014-05-26 06:22:03 +000088 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +000089}
90
Simon Pilgrim6905d222016-12-30 22:55:33 +000091void Sema::FilterAcceptableTemplateNames(LookupResult &R,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000092 bool AllowFunctionTemplates) {
Douglas Gregor41f90302010-04-12 20:54:26 +000093 // The set of class templates we've already seen.
94 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCalle66edc12009-11-24 19:00:30 +000095 LookupResult::Filter filter = R.makeFilter();
96 while (filter.hasNext()) {
97 NamedDecl *Orig = filter.next();
Simon Pilgrim6905d222016-12-30 22:55:33 +000098 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000099 AllowFunctionTemplates);
John McCalle66edc12009-11-24 19:00:30 +0000100 if (!Repl)
101 filter.erase();
Douglas Gregor41f90302010-04-12 20:54:26 +0000102 else if (Repl != Orig) {
103
104 // C++ [temp.local]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000105 // A lookup that finds an injected-class-name (10.2) can result in an
Douglas Gregor41f90302010-04-12 20:54:26 +0000106 // ambiguity in certain cases (for example, if it is found in more than
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000107 // one base class). If all of the injected-class-names that are found
108 // refer to specializations of the same class template, and if the name
Richard Smith3f1b5d02011-05-05 21:57:07 +0000109 // is used as a template-name, the reference refers to the class
110 // template itself and not a specialization thereof, and is not
Douglas Gregor41f90302010-04-12 20:54:26 +0000111 // ambiguous.
Douglas Gregor41f90302010-04-12 20:54:26 +0000112 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
David Blaikie82e95a32014-11-19 07:49:47 +0000113 if (!ClassTemplates.insert(ClassTmpl).second) {
Douglas Gregor41f90302010-04-12 20:54:26 +0000114 filter.erase();
115 continue;
116 }
John McCallbd8062d2010-08-13 07:02:08 +0000117
118 // FIXME: we promote access to public here as a workaround to
119 // the fact that LookupResult doesn't let us remember that we
120 // found this template through a particular injected class name,
121 // which means we end up doing nasty things to the invariants.
122 // Pretending that access is public is *much* safer.
123 filter.replace(Repl, AS_public);
Douglas Gregor41f90302010-04-12 20:54:26 +0000124 }
John McCalle66edc12009-11-24 19:00:30 +0000125 }
126 filter.done();
127}
128
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000129bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
130 bool AllowFunctionTemplates) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000131 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000132 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000133 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +0000134
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000135 return false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000136}
137
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000138TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000139 CXXScopeSpec &SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000140 bool hasTemplateKeyword,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000141 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +0000142 ParsedType ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000143 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000144 TemplateTy &TemplateResult,
145 bool &MemberOfUnknownSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000146 assert(getLangOpts().CPlusPlus && "No template names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000147
Douglas Gregor3cf81312009-11-03 23:16:33 +0000148 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000149 MemberOfUnknownSpecialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000150
Douglas Gregor3cf81312009-11-03 23:16:33 +0000151 switch (Name.getKind()) {
152 case UnqualifiedId::IK_Identifier:
153 TName = DeclarationName(Name.Identifier);
154 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000155
Douglas Gregor3cf81312009-11-03 23:16:33 +0000156 case UnqualifiedId::IK_OperatorFunctionId:
157 TName = Context.DeclarationNames.getCXXOperatorName(
158 Name.OperatorFunctionId.Operator);
159 break;
160
Alexis Hunted0530f2009-11-28 08:58:14 +0000161 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000162 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
163 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000164
Douglas Gregor3cf81312009-11-03 23:16:33 +0000165 default:
166 return TNK_Non_template;
167 }
Mike Stump11289f42009-09-09 15:08:12 +0000168
John McCallba7bf592010-08-24 05:47:05 +0000169 QualType ObjectType = ObjectTypePtr.get();
Mike Stump11289f42009-09-09 15:08:12 +0000170
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000171 LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +0000172 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
173 MemberOfUnknownSpecialization);
John McCallfb3f9ba2010-08-28 20:17:00 +0000174 if (R.empty()) return TNK_Non_template;
175 if (R.isAmbiguous()) {
176 // Suppress diagnostics; we'll redo this lookup later.
John McCalldcc71402010-08-13 02:23:42 +0000177 R.suppressDiagnostics();
John McCallfb3f9ba2010-08-28 20:17:00 +0000178
179 // FIXME: we might have ambiguous templates, in which case we
180 // should at least parse them properly!
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000181 return TNK_Non_template;
John McCalldcc71402010-08-13 02:23:42 +0000182 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000183
John McCalld28ae272009-12-02 08:04:21 +0000184 TemplateName Template;
185 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000186
John McCalld28ae272009-12-02 08:04:21 +0000187 unsigned ResultCount = R.end() - R.begin();
188 if (ResultCount > 1) {
189 // We assume that we'll preserve the qualifier from a function
190 // template name in other ways.
191 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
192 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000193
194 // We'll do this lookup again later.
195 R.suppressDiagnostics();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000196 } else {
John McCalld28ae272009-12-02 08:04:21 +0000197 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
198
199 if (SS.isSet() && !SS.isInvalid()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000200 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000201 Template = Context.getQualifiedTemplateName(Qualifier,
202 hasTemplateKeyword, TD);
John McCalld28ae272009-12-02 08:04:21 +0000203 } else {
204 Template = TemplateName(TD);
205 }
206
John McCalldcc71402010-08-13 02:23:42 +0000207 if (isa<FunctionTemplateDecl>(TD)) {
John McCalld28ae272009-12-02 08:04:21 +0000208 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000209
210 // We'll do this lookup again later.
211 R.suppressDiagnostics();
212 } else {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000213 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000214 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
215 isa<BuiltinTemplateDecl>(TD));
Larisse Voufo39a1e502013-08-06 01:03:05 +0000216 TemplateKind =
217 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
John McCalld28ae272009-12-02 08:04:21 +0000218 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000219 }
Mike Stump11289f42009-09-09 15:08:12 +0000220
John McCalld28ae272009-12-02 08:04:21 +0000221 TemplateResult = TemplateTy::make(Template);
222 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000223}
224
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000225bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
Douglas Gregor18473f32010-01-12 21:28:44 +0000226 SourceLocation IILoc,
227 Scope *S,
228 const CXXScopeSpec *SS,
229 TemplateTy &SuggestedTemplate,
230 TemplateNameKind &SuggestedKind) {
231 // We can't recover unless there's a dependent scope specifier preceding the
232 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000233 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000234 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
235 computeDeclContext(*SS))
236 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000237
Douglas Gregor18473f32010-01-12 21:28:44 +0000238 // The code is missing a 'template' keyword prior to the dependent template
239 // name.
240 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
241 Diag(IILoc, diag::err_template_kw_missing)
242 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000243 << FixItHint::CreateInsertion(IILoc, "template ");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000244 SuggestedTemplate
Douglas Gregor18473f32010-01-12 21:28:44 +0000245 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
246 SuggestedKind = TNK_Dependent_template_name;
247 return true;
248}
249
John McCalle66edc12009-11-24 19:00:30 +0000250void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000251 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000252 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000253 bool EnteringContext,
254 bool &MemberOfUnknownSpecialization) {
John McCalle66edc12009-11-24 19:00:30 +0000255 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000256 MemberOfUnknownSpecialization = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000257 DeclContext *LookupCtx = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000258 bool isDependent = false;
259 if (!ObjectType.isNull()) {
260 // This nested-name-specifier occurs in a member access expression, e.g.,
261 // x->B::f, and we are looking into the type of the object.
262 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
263 LookupCtx = computeDeclContext(ObjectType);
264 isDependent = ObjectType->isDependentType();
Richard Smith5ed79562013-06-07 20:03:01 +0000265 assert((isDependent || !ObjectType->isIncompleteType() ||
266 ObjectType->castAs<TagType>()->isBeingDefined()) &&
John McCalle66edc12009-11-24 19:00:30 +0000267 "Caller should have completed object type");
Simon Pilgrim6905d222016-12-30 22:55:33 +0000268
Douglas Gregorbf3a8262012-01-12 16:11:24 +0000269 // Template names cannot appear inside an Objective-C class or object type.
270 if (ObjectType->isObjCObjectOrInterfaceType()) {
271 Found.clear();
272 return;
273 }
John McCalle66edc12009-11-24 19:00:30 +0000274 } else if (SS.isSet()) {
275 // This nested-name-specifier occurs after another nested-name-specifier,
276 // so long into the context associated with the prior nested-name-specifier.
277 LookupCtx = computeDeclContext(SS, EnteringContext);
278 isDependent = isDependentScopeSpecifier(SS);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000279
John McCalle66edc12009-11-24 19:00:30 +0000280 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000281 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCalle66edc12009-11-24 19:00:30 +0000282 return;
283 }
284
285 bool ObjectTypeSearchedInScope = false;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000286 bool AllowFunctionTemplatesInLookup = true;
John McCalle66edc12009-11-24 19:00:30 +0000287 if (LookupCtx) {
288 // Perform "qualified" name lookup into the declaration context we
289 // computed, which is either the type of the base of a member access
290 // expression or the declaration context associated with a prior
291 // nested-name-specifier.
292 LookupQualifiedName(Found, LookupCtx);
John McCalle66edc12009-11-24 19:00:30 +0000293 if (!ObjectType.isNull() && Found.empty()) {
294 // C++ [basic.lookup.classref]p1:
295 // In a class member access expression (5.2.5), if the . or -> token is
296 // immediately followed by an identifier followed by a <, the
297 // identifier must be looked up to determine whether the < is the
298 // beginning of a template argument list (14.2) or a less-than operator.
299 // The identifier is first looked up in the class of the object
300 // expression. If the identifier is not found, it is then looked up in
301 // the context of the entire postfix-expression and shall name a class
302 // or function template.
John McCalle66edc12009-11-24 19:00:30 +0000303 if (S) LookupName(Found, S);
304 ObjectTypeSearchedInScope = true;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000305 AllowFunctionTemplatesInLookup = false;
John McCalle66edc12009-11-24 19:00:30 +0000306 }
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000307 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregorc119dd52010-01-12 17:06:20 +0000308 // We cannot look into a dependent object type or nested nme
309 // specifier.
Douglas Gregor786123d2010-05-21 23:18:07 +0000310 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000311 return;
312 } else {
313 // Perform unqualified name lookup in the current scope.
314 LookupName(Found, S);
Simon Pilgrim6905d222016-12-30 22:55:33 +0000315
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000316 if (!ObjectType.isNull())
317 AllowFunctionTemplatesInLookup = false;
John McCalle66edc12009-11-24 19:00:30 +0000318 }
319
Douglas Gregorc119dd52010-01-12 17:06:20 +0000320 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000321 // If we did not find any names, attempt to correct any typos.
322 DeclarationName Name = Found.getLookupName();
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000323 Found.clear();
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000324 // Simple filter callback that, for keywords, only accepts the C++ *_cast
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000325 auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
326 FilterCCC->WantTypeSpecifiers = false;
327 FilterCCC->WantExpressionKeywords = false;
328 FilterCCC->WantRemainingKeywords = false;
329 FilterCCC->WantCXXNamedCasts = true;
330 if (TypoCorrection Corrected = CorrectTypo(
331 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
332 std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000333 Found.setLookupName(Corrected.getCorrection());
Richard Smithde6d6c42015-12-29 19:43:10 +0000334 if (auto *ND = Corrected.getFoundDecl())
335 Found.addDecl(ND);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000336 FilterAcceptableTemplateNames(Found);
John McCalle9cccd82010-06-16 08:42:20 +0000337 if (!Found.empty()) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000338 if (LookupCtx) {
Richard Smithf9b15102013-08-17 00:46:16 +0000339 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
340 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000341 Name.getAsString() == CorrectedStr;
Richard Smithf9b15102013-08-17 00:46:16 +0000342 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
343 << Name << LookupCtx << DroppedSpecifier
344 << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000345 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000346 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000347 }
John McCalle9cccd82010-06-16 08:42:20 +0000348 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000349 } else {
Douglas Gregorc048c522010-06-29 19:27:42 +0000350 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000351 }
352 }
353
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000354 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000355 if (Found.empty()) {
356 if (isDependent)
357 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000358 return;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000359 }
John McCalle66edc12009-11-24 19:00:30 +0000360
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000361 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
Richard Smithe7d67f22013-09-03 21:22:41 +0000362 !getLangOpts().CPlusPlus11) {
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000363 // C++03 [basic.lookup.classref]p1:
John McCalle66edc12009-11-24 19:00:30 +0000364 // [...] If the lookup in the class of the object expression finds a
365 // template, the name is also looked up in the context of the entire
366 // postfix-expression and [...]
367 //
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000368 // Note: C++11 does not perform this second lookup.
John McCalle66edc12009-11-24 19:00:30 +0000369 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
370 LookupOrdinaryName);
371 LookupName(FoundOuter, S);
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000372 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000373
John McCalle66edc12009-11-24 19:00:30 +0000374 if (FoundOuter.empty()) {
375 // - if the name is not found, the name found in the class of the
376 // object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000377 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
378 FoundOuter.isAmbiguous()) {
John McCalle66edc12009-11-24 19:00:30 +0000379 // - if the name is found in the context of the entire
380 // postfix-expression and does not name a class template, the name
381 // found in the class of the object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000382 FoundOuter.clear();
John McCalle9cccd82010-06-16 08:42:20 +0000383 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000384 // - if the name found is a class template, it must refer to the same
385 // entity as the one found in the class of the object expression,
386 // otherwise the program is ill-formed.
387 if (!Found.isSingleResult() ||
388 Found.getFoundDecl()->getCanonicalDecl()
389 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000390 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000391 diag::ext_nested_name_member_ref_lookup_ambiguous)
392 << Found.getLookupName()
393 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000394 Diag(Found.getRepresentativeDecl()->getLocation(),
395 diag::note_ambig_member_ref_object_type)
396 << ObjectType;
397 Diag(FoundOuter.getFoundDecl()->getLocation(),
398 diag::note_ambig_member_ref_scope);
399
400 // Recover by taking the template that we found in the object
401 // expression's type.
402 }
403 }
404 }
405}
406
John McCallcd4b4772009-12-02 03:53:29 +0000407/// ActOnDependentIdExpression - Handle a dependent id-expression that
408/// was just parsed. This is only possible with an explicit scope
409/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000410ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000411Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000412 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000413 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000414 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000415 const TemplateArgumentListInfo *TemplateArgs) {
John McCall87fe5d52010-05-20 01:18:31 +0000416 DeclContext *DC = getFunctionLevelDeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000417
Reid Kleckner1af391df2016-03-11 18:59:12 +0000418 // C++11 [expr.prim.general]p12:
419 // An id-expression that denotes a non-static data member or non-static
420 // member function of a class can only be used:
421 // (...)
422 // - if that id-expression denotes a non-static data member and it
423 // appears in an unevaluated operand.
424 //
425 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
426 // CXXDependentScopeMemberExpr. The former can instantiate to either
427 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
428 // always a MemberExpr.
429 bool MightBeCxx11UnevalField =
430 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
431
Akira Hatanakad644e022016-12-16 03:19:41 +0000432 // Check if the nested name specifier is an enum type.
433 bool IsEnum = false;
434 if (NestedNameSpecifier *NNS = SS.getScopeRep())
435 IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
436
437 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
Reid Kleckner1af391df2016-03-11 18:59:12 +0000438 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
John McCall87fe5d52010-05-20 01:18:31 +0000439 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000440
John McCalle66edc12009-11-24 19:00:30 +0000441 // Since the 'this' expression is synthesized, we don't need to
442 // perform the double-lookup check.
Craig Topperc3ec1492014-05-26 06:22:03 +0000443 NamedDecl *FirstQualifierInScope = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000444
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000445 return CXXDependentScopeMemberExpr::Create(
446 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
447 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
448 FirstQualifierInScope, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000449 }
450
Abramo Bagnara7945c982012-01-27 09:46:47 +0000451 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000452}
453
John McCalldadc5752010-08-24 06:29:42 +0000454ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000455Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000456 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000457 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000458 const TemplateArgumentListInfo *TemplateArgs) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000459 return DependentScopeDeclRefExpr::Create(
460 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
461 TemplateArgs);
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000462}
463
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000464
465/// Determine whether we would be unable to instantiate this template (because
466/// it either has no definition, or is in the process of being instantiated).
467bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
468 NamedDecl *Instantiation,
469 bool InstantiatedFromMember,
470 const NamedDecl *Pattern,
471 const NamedDecl *PatternDef,
472 TemplateSpecializationKind TSK,
473 bool Complain /*= true*/) {
Richard Smithedbc6e92016-10-14 21:41:24 +0000474 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
475 isa<VarDecl>(Instantiation));
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000476
Richard Smithedbc6e92016-10-14 21:41:24 +0000477 bool IsEntityBeingDefined = false;
478 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
479 IsEntityBeingDefined = TD->isBeingDefined();
480
481 if (PatternDef && !IsEntityBeingDefined) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000482 NamedDecl *SuggestedDef = nullptr;
483 if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
484 /*OnlyNeedComplete*/false)) {
485 // If we're allowed to diagnose this and recover, do so.
486 bool Recover = Complain && !isSFINAEContext();
487 if (Complain)
488 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
489 Sema::MissingImportKind::Definition, Recover);
490 return !Recover;
491 }
492 return false;
493 }
494
Richard Smith6f4e2e02016-08-23 19:41:39 +0000495 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
496 return true;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000497
Richard Smithedbc6e92016-10-14 21:41:24 +0000498 llvm::Optional<unsigned> Note;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000499 QualType InstantiationTy;
500 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
501 InstantiationTy = Context.getTypeDeclType(TD);
Richard Smith6f4e2e02016-08-23 19:41:39 +0000502 if (PatternDef) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000503 Diag(PointOfInstantiation,
504 diag::err_template_instantiate_within_definition)
Richard Smithedbc6e92016-10-14 21:41:24 +0000505 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000506 << InstantiationTy;
507 // Not much point in noting the template declaration here, since
508 // we're lexically inside it.
509 Instantiation->setInvalidDecl();
510 } else if (InstantiatedFromMember) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000511 if (isa<FunctionDecl>(Instantiation)) {
512 Diag(PointOfInstantiation,
513 diag::err_explicit_instantiation_undefined_member)
Richard Smithedbc6e92016-10-14 21:41:24 +0000514 << /*member function*/ 1 << Instantiation->getDeclName()
515 << Instantiation->getDeclContext();
516 Note = diag::note_explicit_instantiation_here;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000517 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000518 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
Richard Smith6f4e2e02016-08-23 19:41:39 +0000519 Diag(PointOfInstantiation,
520 diag::err_implicit_instantiate_member_undefined)
521 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000522 Note = diag::note_member_declared_at;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000523 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000524 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000525 if (isa<FunctionDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000526 Diag(PointOfInstantiation,
527 diag::err_explicit_instantiation_undefined_func_template)
528 << Pattern;
Richard Smithedbc6e92016-10-14 21:41:24 +0000529 Note = diag::note_explicit_instantiation_here;
530 } else if (isa<TagDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000531 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
532 << (TSK != TSK_ImplicitInstantiation)
533 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000534 Note = diag::note_template_decl_here;
535 } else {
536 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
537 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
538 Diag(PointOfInstantiation,
539 diag::err_explicit_instantiation_undefined_var_template)
540 << Instantiation;
541 Instantiation->setInvalidDecl();
542 } else
543 Diag(PointOfInstantiation,
544 diag::err_explicit_instantiation_undefined_member)
545 << /*static data member*/ 2 << Instantiation->getDeclName()
546 << Instantiation->getDeclContext();
547 Note = diag::note_explicit_instantiation_here;
548 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000549 }
Richard Smithedbc6e92016-10-14 21:41:24 +0000550 if (Note) // Diagnostics were emitted.
551 Diag(Pattern->getLocation(), Note.getValue());
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000552
553 // In general, Instantiation isn't marked invalid to get more than one
554 // error for multiple undefined instantiations. But the code that does
555 // explicit declaration -> explicit definition conversion can't handle
556 // invalid declarations, so mark as invalid in that case.
557 if (TSK == TSK_ExplicitInstantiationDeclaration)
558 Instantiation->setInvalidDecl();
559 return true;
560}
561
Douglas Gregor5101c242008-12-05 18:15:24 +0000562/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
563/// that the template parameter 'PrevDecl' is being shadowed by a new
564/// declaration at location Loc. Returns true to indicate that this is
565/// an error, and false otherwise.
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000566void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000567 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000568
569 // Microsoft Visual C++ permits template parameters to be shadowed.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000570 if (getLangOpts().MicrosoftExt)
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000571 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000572
573 // C++ [temp.local]p4:
574 // A template-parameter shall not be redeclared within its
575 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000576 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000577 << cast<NamedDecl>(PrevDecl)->getDeclName();
578 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregor5101c242008-12-05 18:15:24 +0000579}
580
Douglas Gregor463421d2009-03-03 04:44:36 +0000581/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000582/// the parameter D to reference the templated declaration and return a pointer
583/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000584TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
585 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
586 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000587 return Temp;
588 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000589 return nullptr;
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000590}
591
Douglas Gregoreb29d182011-01-05 17:40:24 +0000592ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
593 SourceLocation EllipsisLoc) const {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000594 assert(Kind == Template &&
Douglas Gregoreb29d182011-01-05 17:40:24 +0000595 "Only template template arguments can be pack expansions here");
596 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
597 "Template template argument pack expansion without packs");
598 ParsedTemplateArgument Result(*this);
599 Result.EllipsisLoc = EllipsisLoc;
600 return Result;
601}
602
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000603static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
604 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000605
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000606 switch (Arg.getKind()) {
607 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000608 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000609 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000610 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000611 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000612 return TemplateArgumentLoc(TemplateArgument(T), DI);
613 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000614
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000615 case ParsedTemplateArgument::NonType: {
616 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
617 return TemplateArgumentLoc(TemplateArgument(E), E);
618 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000619
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000620 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000621 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregore1d60df2011-01-14 23:41:42 +0000622 TemplateArgument TArg;
623 if (Arg.getEllipsisLoc().isValid())
David Blaikie05785d12013-02-20 22:23:23 +0000624 TArg = TemplateArgument(Template, Optional<unsigned int>());
Douglas Gregore1d60df2011-01-14 23:41:42 +0000625 else
626 TArg = Template;
627 return TemplateArgumentLoc(TArg,
Douglas Gregor9d802122011-03-02 17:09:35 +0000628 Arg.getScopeSpec().getWithLocInContext(
629 SemaRef.Context),
Douglas Gregoreb29d182011-01-05 17:40:24 +0000630 Arg.getLocation(),
631 Arg.getEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000632 }
633 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000634
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000635 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000636}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000637
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000638/// \brief Translates template arguments as provided by the parser
639/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000640void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
641 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000642 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000643 TemplateArgs.addArgument(translateTemplateArgument(*this,
644 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000645}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000646
Richard Smithb80d5402013-06-25 22:21:36 +0000647static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
648 SourceLocation Loc,
649 IdentifierInfo *Name) {
650 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
651 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
652 if (PrevDecl && PrevDecl->isTemplateParameter())
653 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
654}
655
Douglas Gregor5101c242008-12-05 18:15:24 +0000656/// ActOnTypeParameter - Called when a C++ template type parameter
657/// (e.g., "typename T") has been parsed. Typename specifies whether
658/// the keyword "typename" was used to declare the type parameter
659/// (otherwise, "class" was used), and KeyLoc is the location of the
660/// "class" or "typename" keyword. ParamName is the name of the
661/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth08836322011-05-01 00:51:33 +0000662/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000663/// If the type parameter has a default argument, it will be added
664/// later via ActOnTypeParameterDefault.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000665Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
John McCall48871652010-08-21 09:40:31 +0000666 SourceLocation EllipsisLoc,
667 SourceLocation KeyLoc,
668 IdentifierInfo *ParamName,
669 SourceLocation ParamNameLoc,
670 unsigned Depth, unsigned Position,
671 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000672 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000673 assert(S->isTemplateParamScope() &&
674 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000675
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000676 SourceLocation Loc = ParamNameLoc;
677 if (!ParamName)
678 Loc = KeyLoc;
679
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000680 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregor5101c242008-12-05 18:15:24 +0000681 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000682 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000683 KeyLoc, Loc, Depth, Position, ParamName,
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000684 Typename, IsParameterPack);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000685 Param->setAccess(AS_public);
Douglas Gregor5101c242008-12-05 18:15:24 +0000686
687 if (ParamName) {
Richard Smithb80d5402013-06-25 22:21:36 +0000688 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
689
Douglas Gregor5101c242008-12-05 18:15:24 +0000690 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000691 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000692 IdResolver.AddDecl(Param);
693 }
694
Douglas Gregorf5500772011-01-05 15:48:55 +0000695 // C++0x [temp.param]p9:
696 // A default template-argument may be specified for any kind of
697 // template-parameter that is not a template parameter pack.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000698 if (DefaultArg && IsParameterPack) {
Douglas Gregorf5500772011-01-05 15:48:55 +0000699 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
David Blaikieefdccaa2016-01-15 23:43:34 +0000700 DefaultArg = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000701 }
702
Douglas Gregordc13ded2010-07-01 00:00:45 +0000703 // Handle the default argument, if provided.
704 if (DefaultArg) {
705 TypeSourceInfo *DefaultTInfo;
706 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000707
Douglas Gregordc13ded2010-07-01 00:00:45 +0000708 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000709
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000710 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000711 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000712 UPPC_DefaultArgument))
713 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000714
Douglas Gregordc13ded2010-07-01 00:00:45 +0000715 // Check the template argument itself.
716 if (CheckTemplateArgument(Param, DefaultTInfo)) {
717 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000718 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000719 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000720
Richard Smith1469b912015-06-10 00:29:03 +0000721 Param->setDefaultArgument(DefaultTInfo);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000722 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000723
John McCall48871652010-08-21 09:40:31 +0000724 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000725}
726
Douglas Gregor463421d2009-03-03 04:44:36 +0000727/// \brief Check that the type of a non-type template parameter is
728/// well-formed.
729///
730/// \returns the (possibly-promoted) parameter type if valid;
731/// otherwise, produces a diagnostic and returns a NULL type.
Richard Smith15361a22016-12-28 06:27:18 +0000732QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
733 SourceLocation Loc) {
734 if (TSI->getType()->isUndeducedType()) {
735 // C++1z [temp.dep.expr]p3:
736 // An id-expression is type-dependent if it contains
737 // - an identifier associated by name lookup with a non-type
738 // template-parameter declared with a type that contains a
739 // placeholder type (7.1.7.4),
740 TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
741 }
742
743 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
744}
745
746QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
747 SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000748 // We don't allow variably-modified types as the type of non-type template
749 // parameters.
750 if (T->isVariablyModifiedType()) {
751 Diag(Loc, diag::err_variably_modified_nontype_template_param)
752 << T;
753 return QualType();
754 }
755
Douglas Gregor463421d2009-03-03 04:44:36 +0000756 // C++ [temp.param]p4:
757 //
758 // A non-type template-parameter shall have one of the following
759 // (optionally cv-qualified) types:
760 //
761 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000762 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000763 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000764 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000765 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000766 T->isReferenceType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000767 // -- pointer to member,
Douglas Gregor463421d2009-03-03 04:44:36 +0000768 T->isMemberPointerType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000769 // -- std::nullptr_t.
770 T->isNullPtrType() ||
Douglas Gregor463421d2009-03-03 04:44:36 +0000771 // If T is a dependent type, we can't do the check now, so we
772 // assume that it is well-formed.
Richard Smith5f274382016-09-28 23:55:27 +0000773 T->isDependentType() ||
774 // Allow use of auto in template parameter declarations.
775 T->isUndeducedType()) {
Richard Smithd0e1c952012-03-13 07:21:50 +0000776 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
777 // are ignored when determining its type.
778 return T.getUnqualifiedType();
779 }
780
Douglas Gregor463421d2009-03-03 04:44:36 +0000781 // C++ [temp.param]p8:
782 //
783 // A non-type template-parameter of type "array of T" or
784 // "function returning T" is adjusted to be of type "pointer to
785 // T" or "pointer to function returning T", respectively.
Richard Smithd663fdd2014-12-17 20:42:37 +0000786 else if (T->isArrayType() || T->isFunctionType())
787 return Context.getDecayedType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000788
Douglas Gregor463421d2009-03-03 04:44:36 +0000789 Diag(Loc, diag::err_template_nontype_parm_bad_type)
790 << T;
791
792 return QualType();
793}
794
John McCall48871652010-08-21 09:40:31 +0000795Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
796 unsigned Depth,
797 unsigned Position,
798 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000799 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000800 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Richard Smith15361a22016-12-28 06:27:18 +0000801
802 if (TInfo->getType()->isUndeducedType()) {
803 Diag(D.getIdentifierLoc(),
804 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
805 << QualType(TInfo->getType()->getContainedAutoType(), 0);
806 }
Douglas Gregor5101c242008-12-05 18:15:24 +0000807
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000808 assert(S->isTemplateParamScope() &&
809 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000810 bool Invalid = false;
811
Richard Smith15361a22016-12-28 06:27:18 +0000812 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
Douglas Gregor38ee75e2010-12-16 15:36:43 +0000813 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000814 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000815 Invalid = true;
816 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000817
Richard Smithb80d5402013-06-25 22:21:36 +0000818 IdentifierInfo *ParamName = D.getIdentifier();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000819 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor5101c242008-12-05 18:15:24 +0000820 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000821 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000822 D.getLocStart(),
John McCallf7b2fb52010-01-22 00:28:27 +0000823 D.getIdentifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000824 Depth, Position, ParamName, T,
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000825 IsParameterPack, TInfo);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000826 Param->setAccess(AS_public);
Richard Smithb80d5402013-06-25 22:21:36 +0000827
Douglas Gregor5101c242008-12-05 18:15:24 +0000828 if (Invalid)
829 Param->setInvalidDecl();
830
Richard Smithb80d5402013-06-25 22:21:36 +0000831 if (ParamName) {
832 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
833 ParamName);
834
Douglas Gregor5101c242008-12-05 18:15:24 +0000835 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000836 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000837 IdResolver.AddDecl(Param);
838 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000839
Douglas Gregorf5500772011-01-05 15:48:55 +0000840 // C++0x [temp.param]p9:
841 // A default template-argument may be specified for any kind of
842 // template-parameter that is not a template parameter pack.
843 if (Default && IsParameterPack) {
844 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
Craig Topperc3ec1492014-05-26 06:22:03 +0000845 Default = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000846 }
847
Douglas Gregordc13ded2010-07-01 00:00:45 +0000848 // Check the well-formedness of the default template argument, if provided.
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000849 if (Default) {
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000850 // Check for unexpanded parameter packs.
851 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
852 return Param;
853
Douglas Gregordc13ded2010-07-01 00:00:45 +0000854 TemplateArgument Converted;
Richard Smithd663fdd2014-12-17 20:42:37 +0000855 ExprResult DefaultRes =
856 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
John Wiegley01296292011-04-08 18:41:53 +0000857 if (DefaultRes.isInvalid()) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000858 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000859 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000860 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000861 Default = DefaultRes.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000862
Richard Smith1469b912015-06-10 00:29:03 +0000863 Param->setDefaultArgument(Default);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000864 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000865
John McCall48871652010-08-21 09:40:31 +0000866 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000867}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000868
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000869/// ActOnTemplateTemplateParameter - Called when a C++ template template
James Dennett2a4d13c2012-06-15 07:13:21 +0000870/// parameter (e.g. T in template <template \<typename> class T> class array)
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000871/// has been parsed. S is the current scope.
John McCall48871652010-08-21 09:40:31 +0000872Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
873 SourceLocation TmpLoc,
Richard Trieu9becef62011-09-09 03:18:59 +0000874 TemplateParameterList *Params,
Douglas Gregorf5500772011-01-05 15:48:55 +0000875 SourceLocation EllipsisLoc,
John McCall48871652010-08-21 09:40:31 +0000876 IdentifierInfo *Name,
877 SourceLocation NameLoc,
878 unsigned Depth,
879 unsigned Position,
880 SourceLocation EqualLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +0000881 ParsedTemplateArgument Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000882 assert(S->isTemplateParamScope() &&
883 "Template template parameter not in template parameter scope!");
884
885 // Construct the parameter object.
Douglas Gregorf5500772011-01-05 15:48:55 +0000886 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000887 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000888 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000889 NameLoc.isInvalid()? TmpLoc : NameLoc,
890 Depth, Position, IsParameterPack,
Douglas Gregorf5500772011-01-05 15:48:55 +0000891 Name, Params);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000892 Param->setAccess(AS_public);
Simon Pilgrim6905d222016-12-30 22:55:33 +0000893
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000894 // If the template template parameter has a name, then link the identifier
Douglas Gregordc13ded2010-07-01 00:00:45 +0000895 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000896 if (Name) {
Richard Smithb80d5402013-06-25 22:21:36 +0000897 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
898
John McCall48871652010-08-21 09:40:31 +0000899 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000900 IdResolver.AddDecl(Param);
901 }
902
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000903 if (Params->size() == 0) {
904 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
905 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
906 Param->setInvalidDecl();
907 }
908
Douglas Gregorf5500772011-01-05 15:48:55 +0000909 // C++0x [temp.param]p9:
910 // A default template-argument may be specified for any kind of
911 // template-parameter that is not a template parameter pack.
912 if (IsParameterPack && !Default.isInvalid()) {
913 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
914 Default = ParsedTemplateArgument();
915 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000916
Douglas Gregordc13ded2010-07-01 00:00:45 +0000917 if (!Default.isInvalid()) {
918 // Check only that we have a template template argument. We don't want to
919 // try to check well-formedness now, because our template template parameter
920 // might have dependent types in its template parameters, which we wouldn't
921 // be able to match now.
922 //
923 // If none of the template template parameter's template arguments mention
924 // other template parameters, we could actually perform more checking here.
925 // However, it isn't worth doing.
926 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
927 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
Faisal Valib8b04f82016-03-26 20:46:45 +0000928 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
Douglas Gregordc13ded2010-07-01 00:00:45 +0000929 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +0000930 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000931 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000932
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000933 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000934 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000935 DefaultArg.getArgument().getAsTemplate(),
936 UPPC_DefaultArgument))
937 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000938
Richard Smith1469b912015-06-10 00:29:03 +0000939 Param->setDefaultArgument(Context, DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000940 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000941
John McCall48871652010-08-21 09:40:31 +0000942 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +0000943}
944
Hubert Tongf608c052016-04-29 18:05:37 +0000945/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
946/// constrained by RequiresClause, that contains the template parameters in
947/// Params.
Richard Trieu9becef62011-09-09 03:18:59 +0000948TemplateParameterList *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000949Sema::ActOnTemplateParameterList(unsigned Depth,
950 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000951 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000952 SourceLocation LAngleLoc,
Craig Topper96225a52015-12-24 23:58:25 +0000953 ArrayRef<Decl *> Params,
Hubert Tongf608c052016-04-29 18:05:37 +0000954 SourceLocation RAngleLoc,
955 Expr *RequiresClause) {
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000956 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000957 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000958
David Majnemer902f8c62015-12-27 07:16:27 +0000959 return TemplateParameterList::Create(
960 Context, TemplateLoc, LAngleLoc,
961 llvm::makeArrayRef((NamedDecl *const *)Params.data(), Params.size()),
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000962 RAngleLoc, RequiresClause);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000963}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000964
John McCall3e11ebe2010-03-15 10:12:16 +0000965static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
966 if (SS.isSet())
Douglas Gregor14454802011-02-25 02:25:35 +0000967 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +0000968}
969
John McCallfaf5fb42010-08-26 23:41:50 +0000970DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000971Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000972 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000973 IdentifierInfo *Name, SourceLocation NameLoc,
974 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000975 TemplateParameterList *TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +0000976 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
Nikola Smiljanic4fc91532014-07-17 01:59:34 +0000977 SourceLocation FriendLoc,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +0000978 unsigned NumOuterTemplateParamLists,
Richard Smithbe3980b2015-03-27 00:41:57 +0000979 TemplateParameterList** OuterTemplateParamLists,
Richard Smithd9ba2242015-05-07 03:54:19 +0000980 SkipBodyInfo *SkipBody) {
Mike Stump11289f42009-09-09 15:08:12 +0000981 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000982 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000983 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000984 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000985
986 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000987 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000988 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000989
Abramo Bagnara6150c882010-05-11 21:36:43 +0000990 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
991 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000992
993 // There is no such thing as an unnamed class template.
994 if (!Name) {
995 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000996 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000997 }
998
Richard Smith6483d222012-04-21 01:27:54 +0000999 // Find any previous declaration with this name. For a friend with no
1000 // scope explicitly specified, we only look for tag declarations (per
1001 // C++11 [basic.lookup.elab]p2).
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001002 DeclContext *SemanticContext;
Richard Smith6483d222012-04-21 01:27:54 +00001003 LookupResult Previous(*this, Name, NameLoc,
1004 (SS.isEmpty() && TUK == TUK_Friend)
1005 ? LookupTagName : LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +00001006 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001007 if (SS.isNotEmpty() && !SS.isInvalid()) {
1008 SemanticContext = computeDeclContext(SS, true);
1009 if (!SemanticContext) {
Douglas Gregor67daacb2012-03-30 16:20:47 +00001010 // FIXME: Horrible, horrible hack! We can't currently represent this
1011 // in the AST, and historically we have just ignored such friend
1012 // class templates, so don't complain here.
Richard Smithcd556eb2013-11-08 18:59:56 +00001013 Diag(NameLoc, TUK == TUK_Friend
1014 ? diag::warn_template_qualified_friend_ignored
1015 : diag::err_template_qualified_declarator_no_match)
Douglas Gregor67daacb2012-03-30 16:20:47 +00001016 << SS.getScopeRep() << SS.getRange();
Richard Smithcd556eb2013-11-08 18:59:56 +00001017 return TUK != TUK_Friend;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001018 }
Mike Stump11289f42009-09-09 15:08:12 +00001019
John McCall0b66eb32010-05-01 00:40:08 +00001020 if (RequireCompleteDeclContext(SS, SemanticContext))
1021 return true;
1022
Simon Pilgrim6905d222016-12-30 22:55:33 +00001023 // If we're adding a template to a dependent context, we may need to
1024 // rebuilding some of the types used within the template parameter list,
Douglas Gregor041b0842011-10-14 15:31:12 +00001025 // now that we know what the current instantiation is.
1026 if (SemanticContext->isDependentContext()) {
1027 ContextRAII SavedContext(*this, SemanticContext);
1028 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1029 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00001030 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1031 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
Richard Smith6483d222012-04-21 01:27:54 +00001032
John McCall27b18f82009-11-17 02:14:36 +00001033 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001034 } else {
1035 SemanticContext = CurContext;
Richard Smith88fe69c2015-07-06 01:45:27 +00001036
1037 // C++14 [class.mem]p14:
1038 // If T is the name of a class, then each of the following shall have a
1039 // name different from T:
1040 // -- every member template of class T
1041 if (TUK != TUK_Friend &&
1042 DiagnoseClassNameShadow(SemanticContext,
1043 DeclarationNameInfo(Name, NameLoc)))
1044 return true;
1045
John McCall27b18f82009-11-17 02:14:36 +00001046 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001047 }
Mike Stump11289f42009-09-09 15:08:12 +00001048
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001049 if (Previous.isAmbiguous())
1050 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001051
Craig Topperc3ec1492014-05-26 06:22:03 +00001052 NamedDecl *PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001053 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001054 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001055
Serge Pavlove50bf752016-06-10 04:39:07 +00001056 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1057 // Maybe we will complain about the shadowed template parameter.
1058 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1059 // Just pretend that we didn't see the previous declaration.
1060 PrevDecl = nullptr;
1061 }
1062
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001063 // If there is a previous declaration with the same name, check
1064 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +00001065 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001066 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001067
1068 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001069 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001070 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001071 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001072 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1073 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001074 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001075 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1076 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1077 PrevClassTemplate
1078 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1079 ->getSpecializedTemplate();
1080 }
1081 }
1082
John McCalld43784f2009-12-18 11:25:59 +00001083 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +00001084 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001085 // [...] When looking for a prior declaration of a class or a function
1086 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +00001087 // function is neither a qualified name nor a template-id, scopes outside
1088 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +00001089 if (!SS.isSet()) {
1090 DeclContext *OutermostContext = CurContext;
1091 while (!OutermostContext->isFileContext())
1092 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +00001093
Richard Smith61e582f2012-04-20 07:12:26 +00001094 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +00001095 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1096 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1097 SemanticContext = PrevDecl->getDeclContext();
1098 } else {
1099 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001100 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +00001101 // declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00001102 PrevDecl = PrevClassTemplate = nullptr;
Douglas Gregorb74b1032010-04-18 17:37:40 +00001103 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +00001104
1105 // Check that the chosen semantic context doesn't already contain a
1106 // declaration of this name as a non-tag type.
Richard Smithfc805ca2015-07-06 04:43:58 +00001107 Previous.clear(LookupOrdinaryName);
Richard Smith6483d222012-04-21 01:27:54 +00001108 DeclContext *LookupContext = SemanticContext;
1109 while (LookupContext->isTransparentContext())
1110 LookupContext = LookupContext->getLookupParent();
1111 LookupQualifiedName(Previous, LookupContext);
1112
1113 if (Previous.isAmbiguous())
1114 return true;
1115
1116 if (Previous.begin() != Previous.end())
1117 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +00001118 }
John McCall90d3bb92009-12-17 23:21:11 +00001119 }
Richard Smith72bcaec2013-12-05 04:30:04 +00001120 } else if (PrevDecl &&
Richard Smithfc805ca2015-07-06 04:43:58 +00001121 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1122 S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +00001123 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001124
Richard Smithfc805ca2015-07-06 04:43:58 +00001125 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1126 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1127 if (SS.isEmpty() &&
1128 !(PrevClassTemplate &&
1129 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1130 SemanticContext->getRedeclContext()))) {
1131 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1132 Diag(Shadow->getTargetDecl()->getLocation(),
1133 diag::note_using_decl_target);
1134 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1135 // Recover by ignoring the old declaration.
1136 PrevDecl = PrevClassTemplate = nullptr;
1137 }
1138 }
1139
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001140 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +00001141 // Ensure that the template parameter lists are compatible. Skip this check
1142 // for a friend in a dependent context: the template parameter list itself
1143 // could be dependent.
1144 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1145 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001146 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001147 /*Complain=*/true,
1148 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001149 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001150
1151 // C++ [temp.class]p4:
1152 // In a redeclaration, partial specialization, explicit
1153 // specialization or explicit instantiation of a class template,
1154 // the class-key shall agree in kind with the original class
1155 // template declaration (7.1.5.3).
1156 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +00001157 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001158 TUK == TUK_Definition, KWLoc, Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00001159 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00001160 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00001161 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001162 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00001163 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001164 }
1165
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001166 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +00001167 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001168 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001169 // If we have a prior definition that is not visible, treat this as
1170 // simply making that previous definition visible.
1171 NamedDecl *Hidden = nullptr;
1172 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
Richard Smithd9ba2242015-05-07 03:54:19 +00001173 SkipBody->ShouldSkip = true;
Richard Smithbe3980b2015-03-27 00:41:57 +00001174 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1175 assert(Tmpl && "original definition of a class template is not a "
1176 "class template?");
Richard Smithd9ba2242015-05-07 03:54:19 +00001177 makeMergedDefinitionVisible(Hidden, KWLoc);
1178 makeMergedDefinitionVisible(Tmpl, KWLoc);
Richard Smithbe3980b2015-03-27 00:41:57 +00001179 return Def;
1180 }
1181
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001182 Diag(NameLoc, diag::err_redefinition) << Name;
1183 Diag(Def->getLocation(), diag::note_previous_definition);
1184 // FIXME: Would it make sense to try to "forget" the previous
1185 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +00001186 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001187 }
Serge Pavlove50bf752016-06-10 04:39:07 +00001188 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001189 } else if (PrevDecl) {
1190 // C++ [temp]p5:
1191 // A class template shall not have the same name as any other
1192 // template, class, function, object, enumeration, enumerator,
1193 // namespace, or type in the same scope (3.3), except as specified
1194 // in (14.5.4).
1195 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1196 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001197 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001198 }
1199
Douglas Gregordba32632009-02-10 19:49:53 +00001200 // Check the template parameter list of this declaration, possibly
1201 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001202 // template declaration. Skip this check for a friend in a dependent
1203 // context, because the template parameter list might be dependent.
1204 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001205 CheckTemplateParameterList(
1206 TemplateParams,
Craig Topperc3ec1492014-05-26 06:22:03 +00001207 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1208 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001209 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1210 SemanticContext->isDependentContext())
1211 ? TPC_ClassTemplateMember
1212 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1213 : TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +00001214 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001215
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001216 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001217 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001218 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001219 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1220 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001221 : diag::err_member_decl_does_not_match)
1222 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001223 Invalid = true;
1224 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001225 }
1226
Mike Stump11289f42009-09-09 15:08:12 +00001227 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001228 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Mike Stump11289f42009-09-09 15:08:12 +00001229 PrevClassTemplate?
Craig Topperc3ec1492014-05-26 06:22:03 +00001230 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001231 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +00001232 SetNestedNameSpecifier(NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001233 if (NumOuterTemplateParamLists > 0)
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001234 NewClass->setTemplateParameterListsInfo(
1235 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1236 NumOuterTemplateParamLists));
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001237
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001238 // Add alignment attributes if necessary; these attributes are checked when
1239 // the ASTContext lays out the structure.
Eli Friedman0415f3e12012-08-08 21:08:34 +00001240 if (TUK == TUK_Definition) {
1241 AddAlignmentAttributesForRecord(NewClass);
1242 AddMsStructLayoutForRecord(NewClass);
1243 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001244
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001245 ClassTemplateDecl *NewTemplate
1246 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1247 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +00001248 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001249 NewClass->setDescribedClassTemplate(NewTemplate);
Simon Pilgrim6905d222016-12-30 22:55:33 +00001250
Douglas Gregor21823bf2011-12-20 18:11:52 +00001251 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001252 NewTemplate->setModulePrivate();
Simon Pilgrim6905d222016-12-30 22:55:33 +00001253
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001254 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001255 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001256 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001257 assert(T->isDependentType() && "Class template type is not dependent?");
1258 (void)T;
1259
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001260 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001261 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001262 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001263 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1264 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001265
Anders Carlsson137108d2009-03-26 01:24:28 +00001266 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001267 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001268 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001269
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001270 // Set the lexical context of these templates
1271 NewClass->setLexicalDeclContext(CurContext);
1272 NewTemplate->setLexicalDeclContext(CurContext);
1273
John McCall9bb74a52009-07-31 02:45:11 +00001274 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001275 NewClass->startDefinition();
1276
1277 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00001278 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001279
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001280 if (PrevClassTemplate)
1281 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1282
Rafael Espindola385c0422012-07-13 18:04:45 +00001283 AddPushedVisibilityAttribute(NewClass);
1284
Richard Smith234ff472014-08-23 00:49:01 +00001285 if (TUK != TUK_Friend) {
1286 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1287 Scope *Outer = S;
1288 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1289 Outer = Outer->getParent();
1290 PushOnScopeChains(NewTemplate, Outer);
1291 } else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001292 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001293 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001294 NewClass->setAccess(PrevClassTemplate->getAccess());
1295 }
John McCall27b5c252009-09-14 21:59:20 +00001296
Richard Smith64017682013-07-17 23:53:16 +00001297 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001298
John McCall27b5c252009-09-14 21:59:20 +00001299 // Friend templates are visible in fairly strange ways.
1300 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001301 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001302 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001303 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1304 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001305 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001306 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001307
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001308 FriendDecl *Friend = FriendDecl::Create(
1309 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
Douglas Gregor3dad8422009-09-26 06:47:28 +00001310 Friend->setAccess(AS_public);
1311 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001312 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001313
Douglas Gregordba32632009-02-10 19:49:53 +00001314 if (Invalid) {
1315 NewTemplate->setInvalidDecl();
1316 NewClass->setInvalidDecl();
1317 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001318
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001319 ActOnDocumentableDecl(NewTemplate);
1320
John McCall48871652010-08-21 09:40:31 +00001321 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001322}
1323
Douglas Gregored5731f2009-11-25 17:50:39 +00001324/// \brief Diagnose the presence of a default template argument on a
1325/// template parameter, which is ill-formed in certain contexts.
1326///
1327/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001328static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00001329 Sema::TemplateParamListContext TPC,
1330 SourceLocation ParamLoc,
1331 SourceRange DefArgRange) {
1332 switch (TPC) {
1333 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00001334 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00001335 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001336 return false;
1337
1338 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001339 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001340 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00001341 // A default template-argument shall not be specified in a
1342 // function template declaration or a function template
1343 // definition [...]
Simon Pilgrim6905d222016-12-30 22:55:33 +00001344 // If a friend function template declaration specifies a default
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001345 // template-argument, that declaration shall be a definition and shall be
1346 // the only declaration of the function template in the translation unit.
1347 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001348 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00001349 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1350 : diag::ext_template_parameter_default_in_function_template)
1351 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00001352 return false;
1353
1354 case Sema::TPC_ClassTemplateMember:
1355 // C++0x [temp.param]p9:
1356 // A default template-argument shall not be specified in the
1357 // template-parameter-lists of the definition of a member of a
1358 // class template that appears outside of the member's class.
1359 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1360 << DefArgRange;
1361 return true;
1362
David Majnemerba8f17a2013-06-25 22:08:55 +00001363 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001364 case Sema::TPC_FriendFunctionTemplate:
1365 // C++ [temp.param]p9:
1366 // A default template-argument shall not be specified in a
1367 // friend template declaration.
1368 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1369 << DefArgRange;
1370 return true;
1371
1372 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1373 // for friend function templates if there is only a single
1374 // declaration (and it is a definition). Strange!
1375 }
1376
David Blaikie8a40f702012-01-17 06:56:22 +00001377 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00001378}
1379
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001380/// \brief Check for unexpanded parameter packs within the template parameters
1381/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00001382static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1383 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001384 // A template template parameter which is a parameter pack is also a pack
1385 // expansion.
1386 if (TTP->isParameterPack())
1387 return false;
1388
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001389 TemplateParameterList *Params = TTP->getTemplateParameters();
1390 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1391 NamedDecl *P = Params->getParam(I);
1392 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001393 if (!NTTP->isParameterPack() &&
1394 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001395 NTTP->getTypeSourceInfo(),
1396 Sema::UPPC_NonTypeTemplateParameterType))
1397 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001398
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001399 continue;
1400 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001401
1402 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001403 = dyn_cast<TemplateTemplateParmDecl>(P))
1404 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1405 return true;
1406 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001407
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001408 return false;
1409}
1410
Douglas Gregordba32632009-02-10 19:49:53 +00001411/// \brief Checks the validity of a template parameter list, possibly
1412/// considering the template parameter list from a previous
1413/// declaration.
1414///
1415/// If an "old" template parameter list is provided, it must be
1416/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1417/// template parameter list.
1418///
1419/// \param NewParams Template parameter list for a new template
1420/// declaration. This template parameter list will be updated with any
1421/// default arguments that are carried through from the previous
1422/// template parameter list.
1423///
1424/// \param OldParams If provided, template parameter list from a
1425/// previous declaration of the same template. Default template
1426/// arguments will be merged from the old template parameter list to
1427/// the new template parameter list.
1428///
Douglas Gregored5731f2009-11-25 17:50:39 +00001429/// \param TPC Describes the context in which we are checking the given
1430/// template parameter list.
1431///
Douglas Gregordba32632009-02-10 19:49:53 +00001432/// \returns true if an error occurred, false otherwise.
1433bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001434 TemplateParameterList *OldParams,
1435 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001436 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001437
Douglas Gregordba32632009-02-10 19:49:53 +00001438 // C++ [temp.param]p10:
1439 // The set of default template-arguments available for use with a
1440 // template declaration or definition is obtained by merging the
1441 // default arguments from the definition (if in scope) and all
1442 // declarations in scope in the same way default function
1443 // arguments are (8.3.6).
1444 bool SawDefaultArgument = false;
1445 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001446
Mike Stumpc89c8e32009-02-11 23:03:27 +00001447 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001448 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001449 if (OldParams)
1450 OldParam = OldParams->begin();
1451
Douglas Gregor0693def2011-01-27 01:40:17 +00001452 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00001453 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1454 NewParamEnd = NewParams->end();
1455 NewParam != NewParamEnd; ++NewParam) {
1456 // Variables used to diagnose redundant default arguments
1457 bool RedundantDefaultArg = false;
1458 SourceLocation OldDefaultLoc;
1459 SourceLocation NewDefaultLoc;
1460
David Blaikie651c73c2011-10-19 05:19:50 +00001461 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00001462 bool MissingDefaultArg = false;
1463
David Blaikie651c73c2011-10-19 05:19:50 +00001464 // Variable used to diagnose non-final parameter packs
1465 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00001466
Douglas Gregordba32632009-02-10 19:49:53 +00001467 if (TemplateTypeParmDecl *NewTypeParm
1468 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001469 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001470 if (NewTypeParm->hasDefaultArgument() &&
1471 DiagnoseDefaultTemplateArgument(*this, TPC,
1472 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001473 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001474 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001475 NewTypeParm->removeDefaultArgument();
1476
1477 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001478 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001479 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Anders Carlsson327865d2009-06-12 23:20:15 +00001480 if (NewTypeParm->isParameterPack()) {
1481 assert(!NewTypeParm->hasDefaultArgument() &&
1482 "Parameter packs can't have a default argument!");
1483 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001484 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
John McCall0ad16662009-10-29 08:12:44 +00001485 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001486 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1487 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1488 SawDefaultArgument = true;
1489 RedundantDefaultArg = true;
1490 PreviousDefaultArgLoc = NewDefaultLoc;
1491 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1492 // Merge the default argument from the old declaration to the
1493 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001494 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001495 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1496 } else if (NewTypeParm->hasDefaultArgument()) {
1497 SawDefaultArgument = true;
1498 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1499 } else if (SawDefaultArgument)
1500 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001501 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001502 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001503 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001504 if (!NewNonTypeParm->isParameterPack() &&
1505 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001506 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001507 UPPC_NonTypeTemplateParameterType)) {
1508 Invalid = true;
1509 continue;
1510 }
1511
Douglas Gregored5731f2009-11-25 17:50:39 +00001512 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001513 if (NewNonTypeParm->hasDefaultArgument() &&
1514 DiagnoseDefaultTemplateArgument(*this, TPC,
1515 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001516 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001517 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001518 }
1519
Mike Stump12b8ce12009-08-04 21:02:39 +00001520 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001521 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001522 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001523 if (NewNonTypeParm->isParameterPack()) {
1524 assert(!NewNonTypeParm->hasDefaultArgument() &&
1525 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001526 if (!NewNonTypeParm->isPackExpansion())
1527 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001528 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
Richard Smith35828f12013-07-22 03:31:14 +00001529 NewNonTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001530 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1531 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1532 SawDefaultArgument = true;
1533 RedundantDefaultArg = true;
1534 PreviousDefaultArgLoc = NewDefaultLoc;
1535 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1536 // Merge the default argument from the old declaration to the
1537 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001538 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001539 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1540 } else if (NewNonTypeParm->hasDefaultArgument()) {
1541 SawDefaultArgument = true;
1542 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1543 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001544 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001545 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00001546 TemplateTemplateParmDecl *NewTemplateParm
1547 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001548
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001549 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00001550 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001551 Invalid = true;
1552 continue;
1553 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001554
David Blaikie651c73c2011-10-19 05:19:50 +00001555 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001556 if (NewTemplateParm->hasDefaultArgument() &&
1557 DiagnoseDefaultTemplateArgument(*this, TPC,
1558 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001559 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001560 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001561
1562 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001563 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001564 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001565 if (NewTemplateParm->isParameterPack()) {
1566 assert(!NewTemplateParm->hasDefaultArgument() &&
1567 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001568 if (!NewTemplateParm->isPackExpansion())
1569 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001570 } else if (OldTemplateParm &&
1571 hasVisibleDefaultArgument(OldTemplateParm) &&
1572 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001573 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1574 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001575 SawDefaultArgument = true;
1576 RedundantDefaultArg = true;
1577 PreviousDefaultArgLoc = NewDefaultLoc;
1578 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1579 // Merge the default argument from the old declaration to the
1580 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001581 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001582 PreviousDefaultArgLoc
1583 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001584 } else if (NewTemplateParm->hasDefaultArgument()) {
1585 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001586 PreviousDefaultArgLoc
1587 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001588 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001589 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001590 }
1591
Richard Smith1fde8ec2012-09-07 02:06:42 +00001592 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00001593 // If a template parameter of a primary class template or alias template
1594 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001595 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00001596 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
1597 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00001598 Diag((*NewParam)->getLocation(),
1599 diag::err_template_param_pack_must_be_last_template_parameter);
1600 Invalid = true;
1601 }
1602
Douglas Gregordba32632009-02-10 19:49:53 +00001603 if (RedundantDefaultArg) {
1604 // C++ [temp.param]p12:
1605 // A template-parameter shall not be given default arguments
1606 // by two different declarations in the same scope.
1607 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1608 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1609 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00001610 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00001611 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001612 // If a template-parameter of a class template has a default
1613 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00001614 // have a default template-argument supplied or be a template parameter
1615 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00001616 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001617 diag::err_template_param_default_arg_missing);
1618 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1619 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00001620 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001621 }
1622
1623 // If we have an old template parameter list that we're merging
1624 // in, move on to the next parameter.
1625 if (OldParams)
1626 ++OldParam;
1627 }
1628
Douglas Gregor0693def2011-01-27 01:40:17 +00001629 // We were missing some default arguments at the end of the list, so remove
1630 // all of the default arguments.
1631 if (RemoveDefaultArguments) {
1632 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1633 NewParamEnd = NewParams->end();
1634 NewParam != NewParamEnd; ++NewParam) {
1635 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1636 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001637 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00001638 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1639 NTTP->removeDefaultArgument();
1640 else
1641 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1642 }
1643 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001644
Douglas Gregordba32632009-02-10 19:49:53 +00001645 return Invalid;
1646}
Douglas Gregord32e0282009-02-09 23:23:08 +00001647
John McCalla020a012010-10-20 05:44:58 +00001648namespace {
1649
1650/// A class which looks for a use of a certain level of template
1651/// parameter.
1652struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1653 typedef RecursiveASTVisitor<DependencyChecker> super;
1654
1655 unsigned Depth;
Richard Smith57aae072016-12-28 02:37:25 +00001656
1657 // Whether we're looking for a use of a template parameter that makes the
1658 // overall construct type-dependent / a dependent type. This is strictly
1659 // best-effort for now; we may fail to match at all for a dependent type
1660 // in some cases if this is set.
1661 bool IgnoreNonTypeDependent;
1662
John McCalla020a012010-10-20 05:44:58 +00001663 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00001664 SourceLocation MatchLoc;
1665
Richard Smith57aae072016-12-28 02:37:25 +00001666 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
1667 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
1668 Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00001669
Richard Smith57aae072016-12-28 02:37:25 +00001670 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
1671 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
John McCalla020a012010-10-20 05:44:58 +00001672 NamedDecl *ND = Params->getParam(0);
1673 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1674 Depth = PD->getDepth();
1675 } else if (NonTypeTemplateParmDecl *PD =
1676 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1677 Depth = PD->getDepth();
1678 } else {
1679 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1680 }
1681 }
1682
Richard Smith6056d5e2014-02-09 00:54:43 +00001683 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
John McCalla020a012010-10-20 05:44:58 +00001684 if (ParmDepth >= Depth) {
1685 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00001686 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00001687 return true;
1688 }
1689 return false;
1690 }
1691
Richard Smith57aae072016-12-28 02:37:25 +00001692 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
1693 // Prune out non-type-dependent expressions if requested. This can
1694 // sometimes result in us failing to find a template parameter reference
1695 // (if a value-dependent expression creates a dependent type), but this
1696 // mode is best-effort only.
1697 if (auto *E = dyn_cast_or_null<Expr>(S))
1698 if (IgnoreNonTypeDependent && !E->isTypeDependent())
1699 return true;
1700 return super::TraverseStmt(S, Q);
1701 }
1702
1703 bool TraverseTypeLoc(TypeLoc TL) {
1704 if (IgnoreNonTypeDependent && !TL.isNull() &&
1705 !TL.getType()->isDependentType())
1706 return true;
1707 return super::TraverseTypeLoc(TL);
1708 }
1709
Richard Smith6056d5e2014-02-09 00:54:43 +00001710 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1711 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
1712 }
1713
John McCalla020a012010-10-20 05:44:58 +00001714 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
Richard Smith57aae072016-12-28 02:37:25 +00001715 // For a best-effort search, keep looking until we find a location.
1716 return IgnoreNonTypeDependent || !Matches(T->getDepth());
John McCalla020a012010-10-20 05:44:58 +00001717 }
1718
1719 bool TraverseTemplateName(TemplateName N) {
1720 if (TemplateTemplateParmDecl *PD =
1721 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00001722 if (Matches(PD->getDepth()))
1723 return false;
John McCalla020a012010-10-20 05:44:58 +00001724 return super::TraverseTemplateName(N);
1725 }
1726
1727 bool VisitDeclRefExpr(DeclRefExpr *E) {
1728 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00001729 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
1730 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00001731 return false;
John McCalla020a012010-10-20 05:44:58 +00001732 return super::VisitDeclRefExpr(E);
1733 }
Richard Smith6056d5e2014-02-09 00:54:43 +00001734
1735 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1736 return TraverseType(T->getReplacementType());
1737 }
1738
1739 bool
1740 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
1741 return TraverseTemplateArgument(T->getArgumentPack());
1742 }
1743
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00001744 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1745 return TraverseType(T->getInjectedSpecializationType());
1746 }
John McCalla020a012010-10-20 05:44:58 +00001747};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001748} // end anonymous namespace
John McCalla020a012010-10-20 05:44:58 +00001749
Douglas Gregor972fe532011-05-10 18:27:06 +00001750/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00001751/// list.
1752static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00001753DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
Richard Smith57aae072016-12-28 02:37:25 +00001754 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
Douglas Gregor972fe532011-05-10 18:27:06 +00001755 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00001756 return Checker.Match;
1757}
1758
Douglas Gregor972fe532011-05-10 18:27:06 +00001759// Find the source range corresponding to the named type in the given
1760// nested-name-specifier, if any.
1761static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1762 QualType T,
1763 const CXXScopeSpec &SS) {
1764 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1765 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1766 if (const Type *CurType = NNS->getAsType()) {
1767 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1768 return NNSLoc.getTypeLoc().getSourceRange();
1769 } else
1770 break;
Simon Pilgrim6905d222016-12-30 22:55:33 +00001771
Douglas Gregor972fe532011-05-10 18:27:06 +00001772 NNSLoc = NNSLoc.getPrefix();
1773 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00001774
Douglas Gregor972fe532011-05-10 18:27:06 +00001775 return SourceRange();
1776}
1777
Mike Stump11289f42009-09-09 15:08:12 +00001778/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001779/// specifier, returning the template parameter list that applies to the
1780/// name.
1781///
1782/// \param DeclStartLoc the start of the declaration that has a scope
1783/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001784///
Douglas Gregor972fe532011-05-10 18:27:06 +00001785/// \param DeclLoc The location of the declaration itself.
1786///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001787/// \param SS the scope specifier that will be matched to the given template
1788/// parameter lists. This scope specifier precedes a qualified name that is
1789/// being declared.
1790///
Richard Smith4b55a9c2014-04-17 03:29:33 +00001791/// \param TemplateId The template-id following the scope specifier, if there
1792/// is one. Used to check for a missing 'template<>'.
1793///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001794/// \param ParamLists the template parameter lists, from the outermost to the
1795/// innermost template parameter lists.
1796///
John McCalle820e5e2010-04-13 20:37:33 +00001797/// \param IsFriend Whether to apply the slightly different rules for
1798/// matching template parameters to scope specifiers in friend
1799/// declarations.
1800///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001801/// \param IsExplicitSpecialization will be set true if the entity being
1802/// declared is an explicit specialization, false otherwise.
1803///
Mike Stump11289f42009-09-09 15:08:12 +00001804/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001805/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00001806/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001807/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00001808/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00001809/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001810TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
1811 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001812 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001813 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
1814 bool &IsExplicitSpecialization, bool &Invalid) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001815 IsExplicitSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00001816 Invalid = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00001817
Douglas Gregor972fe532011-05-10 18:27:06 +00001818 // The sequence of nested types to which we will match up the template
1819 // parameter lists. We first build this list by starting with the type named
1820 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001821 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00001822 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00001823 if (SS.getScopeRep()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00001824 if (CXXRecordDecl *Record
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00001825 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1826 T = Context.getTypeDeclType(Record);
1827 else
1828 T = QualType(SS.getScopeRep()->getAsType(), 0);
1829 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00001830
Douglas Gregor972fe532011-05-10 18:27:06 +00001831 // If we found an explicit specialization that prevents us from needing
1832 // 'template<>' headers, this will be set to the location of that
1833 // explicit specialization.
1834 SourceLocation ExplicitSpecLoc;
Simon Pilgrim6905d222016-12-30 22:55:33 +00001835
Douglas Gregor972fe532011-05-10 18:27:06 +00001836 while (!T.isNull()) {
1837 NestedTypes.push_back(T);
Simon Pilgrim6905d222016-12-30 22:55:33 +00001838
Douglas Gregor972fe532011-05-10 18:27:06 +00001839 // Retrieve the parent of a record type.
1840 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1841 // If this type is an explicit specialization, we're done.
1842 if (ClassTemplateSpecializationDecl *Spec
1843 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00001844 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
Douglas Gregor972fe532011-05-10 18:27:06 +00001845 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1846 ExplicitSpecLoc = Spec->getLocation();
1847 break;
Douglas Gregor65911492009-11-23 12:11:45 +00001848 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001849 } else if (Record->getTemplateSpecializationKind()
1850 == TSK_ExplicitSpecialization) {
1851 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00001852 break;
1853 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00001854
Douglas Gregor972fe532011-05-10 18:27:06 +00001855 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1856 T = Context.getTypeDeclType(Parent);
1857 else
1858 T = QualType();
1859 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00001860 }
1861
Douglas Gregor972fe532011-05-10 18:27:06 +00001862 if (const TemplateSpecializationType *TST
1863 = T->getAs<TemplateSpecializationType>()) {
1864 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1865 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1866 T = Context.getTypeDeclType(Parent);
1867 else
1868 T = QualType();
Simon Pilgrim6905d222016-12-30 22:55:33 +00001869 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001870 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001871 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00001872
Douglas Gregor972fe532011-05-10 18:27:06 +00001873 // Look one step prior in a dependent template specialization type.
1874 if (const DependentTemplateSpecializationType *DependentTST
1875 = T->getAs<DependentTemplateSpecializationType>()) {
1876 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1877 T = QualType(NNS->getAsType(), 0);
1878 else
1879 T = QualType();
1880 continue;
1881 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00001882
Douglas Gregor972fe532011-05-10 18:27:06 +00001883 // Look one step prior in a dependent name type.
1884 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1885 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1886 T = QualType(NNS->getAsType(), 0);
1887 else
1888 T = QualType();
1889 continue;
1890 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00001891
Douglas Gregor972fe532011-05-10 18:27:06 +00001892 // Retrieve the parent of an enumeration type.
1893 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1894 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1895 // check here.
1896 EnumDecl *Enum = EnumT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00001897
Douglas Gregor972fe532011-05-10 18:27:06 +00001898 // Get to the parent type.
1899 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1900 T = Context.getTypeDeclType(Parent);
1901 else
Simon Pilgrim6905d222016-12-30 22:55:33 +00001902 T = QualType();
Douglas Gregor972fe532011-05-10 18:27:06 +00001903 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001904 }
Mike Stump11289f42009-09-09 15:08:12 +00001905
Douglas Gregor972fe532011-05-10 18:27:06 +00001906 T = QualType();
1907 }
1908 // Reverse the nested types list, since we want to traverse from the outermost
1909 // to the innermost while checking template-parameter-lists.
1910 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00001911
Douglas Gregor972fe532011-05-10 18:27:06 +00001912 // C++0x [temp.expl.spec]p17:
1913 // A member or a member template may be nested within many
1914 // enclosing class templates. In an explicit specialization for
1915 // such a member, the member declaration shall be preceded by a
1916 // template<> for each enclosing class template that is
1917 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001918 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00001919
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001920 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00001921 if (SawNonEmptyTemplateParameterList) {
1922 Diag(DeclLoc, diag::err_specialize_member_of_template)
1923 << !Recovery << Range;
1924 Invalid = true;
1925 IsExplicitSpecialization = false;
1926 return true;
1927 }
1928
1929 return false;
1930 };
1931
1932 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
1933 // Check that we can have an explicit specialization here.
1934 if (CheckExplicitSpecialization(Range, true))
1935 return true;
1936
1937 // We don't have a template header, but we should.
1938 SourceLocation ExpectedTemplateLoc;
1939 if (!ParamLists.empty())
1940 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1941 else
1942 ExpectedTemplateLoc = DeclStartLoc;
1943
1944 Diag(DeclLoc, diag::err_template_spec_needs_header)
1945 << Range
1946 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1947 return false;
1948 };
1949
Douglas Gregor972fe532011-05-10 18:27:06 +00001950 unsigned ParamIdx = 0;
1951 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1952 ++TypeIdx) {
1953 T = NestedTypes[TypeIdx];
Simon Pilgrim6905d222016-12-30 22:55:33 +00001954
Douglas Gregor972fe532011-05-10 18:27:06 +00001955 // Whether we expect a 'template<>' header.
1956 bool NeedEmptyTemplateHeader = false;
1957
1958 // Whether we expect a template header with parameters.
1959 bool NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00001960
Douglas Gregor972fe532011-05-10 18:27:06 +00001961 // For a dependent type, the set of template parameters that we
1962 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00001963 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001964
Douglas Gregor373af9b2011-05-11 23:26:17 +00001965 // C++0x [temp.expl.spec]p15:
Simon Pilgrim6905d222016-12-30 22:55:33 +00001966 // A member or a member template may be nested within many enclosing
1967 // class templates. In an explicit specialization for such a member, the
1968 // member declaration shall be preceded by a template<> for each
Douglas Gregor373af9b2011-05-11 23:26:17 +00001969 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00001970 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1971 if (ClassTemplatePartialSpecializationDecl *Partial
1972 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1973 ExpectedTemplateParams = Partial->getTemplateParameters();
1974 NeedNonemptyTemplateHeader = true;
1975 } else if (Record->isDependentType()) {
1976 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00001977 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00001978 ->getTemplateParameters();
1979 NeedNonemptyTemplateHeader = true;
1980 }
1981 } else if (ClassTemplateSpecializationDecl *Spec
1982 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1983 // C++0x [temp.expl.spec]p4:
1984 // Members of an explicitly specialized class template are defined
Simon Pilgrim6905d222016-12-30 22:55:33 +00001985 // in the same manner as members of normal classes, and not using
1986 // the template<> syntax.
Douglas Gregor972fe532011-05-10 18:27:06 +00001987 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1988 NeedEmptyTemplateHeader = true;
1989 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00001990 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001991 } else if (Record->getTemplateSpecializationKind()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00001992 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00001993 != TSK_ExplicitSpecialization &&
1994 TypeIdx == NumTypes - 1)
1995 IsExplicitSpecialization = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00001996
Douglas Gregor373af9b2011-05-11 23:26:17 +00001997 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001998 }
1999 } else if (const TemplateSpecializationType *TST
2000 = T->getAs<TemplateSpecializationType>()) {
Nico Weber28900612015-01-30 02:35:21 +00002001 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002002 ExpectedTemplateParams = Template->getTemplateParameters();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002003 NeedNonemptyTemplateHeader = true;
Douglas Gregor972fe532011-05-10 18:27:06 +00002004 }
2005 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2006 // FIXME: We actually could/should check the template arguments here
2007 // against the corresponding template parameter list.
2008 NeedNonemptyTemplateHeader = false;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002009 }
2010
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002011 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002012 // In an explicit specialization declaration for a member of a class
2013 // template or a member template that ap- pears in namespace scope, the
2014 // member template and some of its enclosing class templates may remain
2015 // unspecialized, except that the declaration shall not explicitly
2016 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002017 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002018 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002019 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002020 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2021 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002022 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002023 } else
2024 SawNonEmptyTemplateParameterList = true;
2025 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002026
Douglas Gregor972fe532011-05-10 18:27:06 +00002027 if (NeedEmptyTemplateHeader) {
2028 // If we're on the last of the types, and we need a 'template<>' header
2029 // here, then it's an explicit specialization.
2030 if (TypeIdx == NumTypes - 1)
2031 IsExplicitSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002032
2033 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002034 if (ParamLists[ParamIdx]->size() > 0) {
2035 // The header has template parameters when it shouldn't. Complain.
Simon Pilgrim6905d222016-12-30 22:55:33 +00002036 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregor972fe532011-05-10 18:27:06 +00002037 diag::err_template_param_list_matches_nontemplate)
2038 << T
2039 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2040 ParamLists[ParamIdx]->getRAngleLoc())
2041 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2042 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002043 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002044 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002045
Douglas Gregor972fe532011-05-10 18:27:06 +00002046 // Consume this template header.
2047 ++ParamIdx;
2048 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002049 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002050
2051 if (!IsFriend)
2052 if (DiagnoseMissingExplicitSpecialization(
2053 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00002054 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002055
Douglas Gregor972fe532011-05-10 18:27:06 +00002056 continue;
2057 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002058
Douglas Gregor972fe532011-05-10 18:27:06 +00002059 if (NeedNonemptyTemplateHeader) {
2060 // In friend declarations we can have template-ids which don't
2061 // depend on the corresponding template parameter lists. But
2062 // assume that empty parameter lists are supposed to match this
2063 // template-id.
2064 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002065 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002066 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00002067 ExpectedTemplateParams = nullptr;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002068 else
Douglas Gregor972fe532011-05-10 18:27:06 +00002069 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002070 }
Douglas Gregored5731f2009-11-25 17:50:39 +00002071
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002072 if (ParamIdx < ParamLists.size()) {
2073 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00002074 if (ExpectedTemplateParams &&
2075 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2076 ExpectedTemplateParams,
2077 true, TPL_TemplateMatch))
2078 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002079
Douglas Gregor972fe532011-05-10 18:27:06 +00002080 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00002081 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00002082 TPC_ClassTemplateMember))
2083 Invalid = true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00002084
Douglas Gregor972fe532011-05-10 18:27:06 +00002085 ++ParamIdx;
2086 continue;
2087 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002088
Douglas Gregor972fe532011-05-10 18:27:06 +00002089 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2090 << T
2091 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2092 Invalid = true;
2093 continue;
2094 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00002095 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00002096
Douglas Gregord8d297c2009-07-21 23:53:31 +00002097 // If there were at least as many template-ids as there were template
2098 // parameter lists, then there are no template parameter lists remaining for
2099 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00002100 if (ParamIdx >= ParamLists.size()) {
2101 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00002102 // We don't have a template header for the declaration itself, but we
2103 // should.
Richard Smith4b55a9c2014-04-17 03:29:33 +00002104 IsExplicitSpecialization = true;
Richard Smith11a80dc2014-04-17 03:52:20 +00002105 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2106 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00002107
2108 // Fabricate an empty template parameter list for the invented header.
2109 return TemplateParameterList::Create(Context, SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +00002110 SourceLocation(), None,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00002111 SourceLocation(), nullptr);
Richard Smith4b55a9c2014-04-17 03:29:33 +00002112 }
2113
Craig Topperc3ec1492014-05-26 06:22:03 +00002114 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002115 }
Mike Stump11289f42009-09-09 15:08:12 +00002116
Douglas Gregord8d297c2009-07-21 23:53:31 +00002117 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002118 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002119 bool HasAnyExplicitSpecHeader = false;
2120 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002121 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002122 if (ParamLists[I]->size() == 0)
2123 HasAnyExplicitSpecHeader = true;
2124 else
2125 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002126 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002127
Douglas Gregor972fe532011-05-10 18:27:06 +00002128 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002129 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2130 : diag::err_template_spec_extra_headers)
2131 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2132 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00002133
2134 // If there was a specialization somewhere, such that 'template<>' is
2135 // not required, and there were any 'template<>' headers, note where the
2136 // specialization occurred.
2137 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
Simon Pilgrim6905d222016-12-30 22:55:33 +00002138 Diag(ExplicitSpecLoc,
Douglas Gregor972fe532011-05-10 18:27:06 +00002139 diag::note_explicit_template_spec_does_not_need_header)
2140 << NestedTypes.back();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002141
Douglas Gregor972fe532011-05-10 18:27:06 +00002142 // We have a template parameter list with no corresponding scope, which
2143 // means that the resulting template declaration can't be instantiated
2144 // properly (we'll end up with dependent nodes when we shouldn't).
2145 if (!AllExplicitSpecHeaders)
2146 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002147 }
Mike Stump11289f42009-09-09 15:08:12 +00002148
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002149 // C++ [temp.expl.spec]p16:
Simon Pilgrim6905d222016-12-30 22:55:33 +00002150 // In an explicit specialization declaration for a member of a class
2151 // template or a member template that ap- pears in namespace scope, the
2152 // member template and some of its enclosing class templates may remain
2153 // unspecialized, except that the declaration shall not explicitly
2154 // specialize a class member template if its en- closing class templates
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002155 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00002156 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002157 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2158 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002159 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002160
Douglas Gregord8d297c2009-07-21 23:53:31 +00002161 // Return the last template parameter list, which corresponds to the
2162 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002163 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00002164}
2165
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002166void Sema::NoteAllFoundTemplates(TemplateName Name) {
2167 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2168 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002169 << (isa<FunctionTemplateDecl>(Template)
2170 ? 0
2171 : isa<ClassTemplateDecl>(Template)
2172 ? 1
2173 : isa<VarTemplateDecl>(Template)
2174 ? 2
2175 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2176 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002177 return;
2178 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002179
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002180 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00002181 for (OverloadedTemplateStorage::iterator I = OST->begin(),
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002182 IEnd = OST->end();
2183 I != IEnd; ++I)
2184 Diag((*I)->getLocation(), diag::note_template_declared_here)
2185 << 0 << (*I)->getDeclName();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002186
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002187 return;
2188 }
2189}
2190
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002191static QualType
2192checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2193 const SmallVectorImpl<TemplateArgument> &Converted,
2194 SourceLocation TemplateLoc,
2195 TemplateArgumentListInfo &TemplateArgs) {
2196 ASTContext &Context = SemaRef.getASTContext();
2197 switch (BTD->getBuiltinTemplateKind()) {
Eric Fiselier6ad68552016-07-01 01:24:09 +00002198 case BTK__make_integer_seq: {
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002199 // Specializations of __make_integer_seq<S, T, N> are treated like
2200 // S<T, 0, ..., N-1>.
2201
2202 // C++14 [inteseq.intseq]p1:
2203 // T shall be an integer type.
2204 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2205 SemaRef.Diag(TemplateArgs[1].getLocation(),
2206 diag::err_integer_sequence_integral_element_type);
2207 return QualType();
2208 }
2209
2210 // C++14 [inteseq.make]p1:
2211 // If N is negative the program is ill-formed.
2212 TemplateArgument NumArgsArg = Converted[2];
2213 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2214 if (NumArgs < 0) {
2215 SemaRef.Diag(TemplateArgs[2].getLocation(),
2216 diag::err_integer_sequence_negative_length);
2217 return QualType();
2218 }
2219
2220 QualType ArgTy = NumArgsArg.getIntegralType();
2221 TemplateArgumentListInfo SyntheticTemplateArgs;
2222 // The type argument gets reused as the first template argument in the
2223 // synthetic template argument list.
2224 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2225 // Expand N into 0 ... N-1.
2226 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2227 I < NumArgs; ++I) {
2228 TemplateArgument TA(Context, I, ArgTy);
Richard Smith7873de02016-08-11 22:25:46 +00002229 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
2230 TA, ArgTy, TemplateArgs[2].getLocation()));
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002231 }
2232 // The first template argument will be reused as the template decl that
2233 // our synthetic template arguments will be applied to.
2234 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2235 TemplateLoc, SyntheticTemplateArgs);
2236 }
Eric Fiselier6ad68552016-07-01 01:24:09 +00002237
2238 case BTK__type_pack_element:
2239 // Specializations of
2240 // __type_pack_element<Index, T_1, ..., T_N>
2241 // are treated like T_Index.
2242 assert(Converted.size() == 2 &&
2243 "__type_pack_element should be given an index and a parameter pack");
2244
2245 // If the Index is out of bounds, the program is ill-formed.
2246 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
2247 llvm::APSInt Index = IndexArg.getAsIntegral();
2248 assert(Index >= 0 && "the index used with __type_pack_element should be of "
2249 "type std::size_t, and hence be non-negative");
2250 if (Index >= Ts.pack_size()) {
2251 SemaRef.Diag(TemplateArgs[0].getLocation(),
2252 diag::err_type_pack_element_out_of_bounds);
2253 return QualType();
2254 }
2255
2256 // We simply return the type at index `Index`.
2257 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
2258 return Nth->getAsType();
2259 }
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002260 llvm_unreachable("unexpected BuiltinTemplateDecl!");
2261}
2262
Douglas Gregordc572a32009-03-30 22:58:21 +00002263QualType Sema::CheckTemplateIdType(TemplateName Name,
2264 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002265 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00002266 DependentTemplateName *DTN
2267 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00002268 if (DTN && DTN->isIdentifier())
2269 // When building a template-id where the template-name is dependent,
2270 // assume the template is a type template. Either our assumption is
2271 // correct, or the code is ill-formed and will be diagnosed when the
2272 // dependent name is substituted.
2273 return Context.getDependentTemplateSpecializationType(ETK_None,
2274 DTN->getQualifier(),
2275 DTN->getIdentifier(),
2276 TemplateArgs);
2277
Douglas Gregordc572a32009-03-30 22:58:21 +00002278 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00002279 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2280 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002281 // We might have a substituted template template parameter pack. If so,
2282 // build a template specialization type for it.
2283 if (Name.getAsSubstTemplateTemplateParmPack())
2284 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002285
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002286 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2287 << Name;
2288 NoteAllFoundTemplates(Name);
2289 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00002290 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002291
Douglas Gregorc40290e2009-03-09 23:48:35 +00002292 // Check that the template argument list is well-formed for this
2293 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002294 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00002295 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00002296 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00002297 return QualType();
2298
Douglas Gregorc40290e2009-03-09 23:48:35 +00002299 QualType CanonType;
2300
Douglas Gregor678d76c2011-07-01 01:22:09 +00002301 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00002302 if (TypeAliasTemplateDecl *AliasTemplate =
2303 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00002304 // Find the canonical type for this type alias template specialization.
2305 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2306 if (Pattern->isInvalidDecl())
2307 return QualType();
2308
2309 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00002310 Converted);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002311
2312 // Only substitute for the innermost template argument list.
2313 MultiLevelTemplateArgumentList TemplateArgLists;
Richard Smith0c4a34b2011-05-14 15:04:18 +00002314 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00002315 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2316 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00002317 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002318
Richard Smith802c4b72012-08-23 06:16:52 +00002319 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002320 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002321 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00002322 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00002323
Richard Smith3f1b5d02011-05-05 21:57:07 +00002324 CanonType = SubstType(Pattern->getUnderlyingType(),
2325 TemplateArgLists, AliasTemplate->getLocation(),
2326 AliasTemplate->getDeclName());
2327 if (CanonType.isNull())
2328 return QualType();
2329 } else if (Name.isDependent() ||
2330 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00002331 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002332 // This class template specialization is a dependent
2333 // type. Therefore, its canonical type is another class template
2334 // specialization type that contains all of the converted
2335 // arguments in canonical form. This ensures that, e.g., A<T> and
2336 // A<T, T> have identical types when A is declared as:
2337 //
2338 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00002339 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002340 CanonType = Context.getTemplateSpecializationType(CanonName,
David Majnemer6fbeee32016-07-07 04:43:07 +00002341 Converted);
Mike Stump11289f42009-09-09 15:08:12 +00002342
Douglas Gregora8e02e72009-07-28 23:00:59 +00002343 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00002344 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00002345 // In the future, we need to teach getTemplateSpecializationType to only
2346 // build the canonical type and return that to us.
2347 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00002348
2349 // This might work out to be a current instantiation, in which
2350 // case the canonical type needs to be the InjectedClassNameType.
2351 //
2352 // TODO: in theory this could be a simple hashtable lookup; most
2353 // changes to CurContext don't change the set of current
2354 // instantiations.
2355 if (isa<ClassTemplateDecl>(Template)) {
2356 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2357 // If we get out to a namespace, we're done.
2358 if (Ctx->isFileContext()) break;
2359
2360 // If this isn't a record, keep looking.
2361 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2362 if (!Record) continue;
2363
2364 // Look for one of the two cases with InjectedClassNameTypes
2365 // and check whether it's the same template.
2366 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2367 !Record->getDescribedClassTemplate())
2368 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002369
John McCall2408e322010-04-27 00:57:59 +00002370 // Fetch the injected class name type and check whether its
2371 // injected type is equal to the type we just built.
2372 QualType ICNT = Context.getTypeDeclType(Record);
2373 QualType Injected = cast<InjectedClassNameType>(ICNT)
2374 ->getInjectedSpecializationType();
2375
2376 if (CanonType != Injected->getCanonicalTypeInternal())
2377 continue;
2378
2379 // If so, the canonical type of this TST is the injected
2380 // class name type of the record we just found.
2381 assert(ICNT.isCanonical());
2382 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00002383 break;
2384 }
2385 }
Mike Stump11289f42009-09-09 15:08:12 +00002386 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002387 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002388 // Find the class template specialization declaration that
2389 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002390 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002391 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00002392 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002393 if (!Decl) {
2394 // This is the first time we have referenced this class template
2395 // specialization. Create the canonical declaration and add it to
2396 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002397 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002398 ClassTemplate->getTemplatedDecl()->getTagKind(),
2399 ClassTemplate->getDeclContext(),
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002400 ClassTemplate->getTemplatedDecl()->getLocStart(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002401 ClassTemplate->getLocation(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002402 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00002403 Converted, nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00002404 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00002405 if (ClassTemplate->isOutOfLine())
2406 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00002407 }
2408
Chandler Carruth2acfb222013-09-27 22:14:40 +00002409 // Diagnose uses of this specialization.
2410 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2411
Douglas Gregorc40290e2009-03-09 23:48:35 +00002412 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00002413 assert(isa<RecordType>(CanonType) &&
2414 "type of non-dependent specialization is not a RecordType");
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002415 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
2416 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
2417 TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002418 }
Mike Stump11289f42009-09-09 15:08:12 +00002419
Douglas Gregorc40290e2009-03-09 23:48:35 +00002420 // Build the fully-sugared type for this class template
2421 // specialization, which refers back to the class template
2422 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00002423 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002424}
2425
John McCallfaf5fb42010-08-26 23:41:50 +00002426TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002427Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00002428 TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002429 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00002430 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002431 SourceLocation RAngleLoc,
2432 bool IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002433 if (SS.isInvalid())
2434 return true;
2435
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002436 TemplateName Template = TemplateD.get();
Douglas Gregor8bf42052009-02-09 18:46:07 +00002437
Douglas Gregorc40290e2009-03-09 23:48:35 +00002438 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00002439 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002440 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00002441
Douglas Gregor5a064722011-02-28 17:23:35 +00002442 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00002443 QualType T
2444 = Context.getDependentTemplateSpecializationType(ETK_None,
2445 DTN->getQualifier(),
2446 DTN->getIdentifier(),
2447 TemplateArgs);
2448 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00002449 TypeLocBuilder TLB;
2450 DependentTemplateSpecializationTypeLoc SpecTL
2451 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002452 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2453 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002454 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002455 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002456 SpecTL.setLAngleLoc(LAngleLoc);
2457 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002458 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2459 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2460 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2461 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002462
John McCall6b51f282009-11-23 01:53:49 +00002463 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002464
2465 if (Result.isNull())
2466 return true;
2467
Douglas Gregore7c20652011-03-02 00:47:37 +00002468 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002469 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00002470 TemplateSpecializationTypeLoc SpecTL
2471 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002472 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002473 SpecTL.setTemplateNameLoc(TemplateLoc);
2474 SpecTL.setLAngleLoc(LAngleLoc);
2475 SpecTL.setRAngleLoc(RAngleLoc);
2476 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2477 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00002478
Abramo Bagnara4244b432012-01-27 08:46:19 +00002479 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2480 // constructor or destructor name (in such a case, the scope specifier
2481 // will be attached to the enclosing Decl or Expr node).
2482 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002483 // Create an elaborated-type-specifier containing the nested-name-specifier.
2484 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2485 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002486 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00002487 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2488 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002489
Douglas Gregore7c20652011-03-02 00:47:37 +00002490 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00002491}
John McCall06f6fe8d2009-09-04 01:14:41 +00002492
Douglas Gregore7c20652011-03-02 00:47:37 +00002493TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00002494 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00002495 SourceLocation TagLoc,
2496 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002497 SourceLocation TemplateKWLoc,
2498 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00002499 SourceLocation TemplateLoc,
2500 SourceLocation LAngleLoc,
2501 ASTTemplateArgsPtr TemplateArgsIn,
2502 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002503 TemplateName Template = TemplateD.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002504
Douglas Gregore7c20652011-03-02 00:47:37 +00002505 // Translate the parser's template argument list in our AST format.
2506 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2507 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00002508
Douglas Gregore7c20652011-03-02 00:47:37 +00002509 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00002510 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00002511 ElaboratedTypeKeyword Keyword
2512 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00002513
Douglas Gregore7c20652011-03-02 00:47:37 +00002514 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2515 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
Simon Pilgrim6905d222016-12-30 22:55:33 +00002516 DTN->getQualifier(),
2517 DTN->getIdentifier(),
Douglas Gregore7c20652011-03-02 00:47:37 +00002518 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00002519
2520 // Build type-source information.
Douglas Gregore7c20652011-03-02 00:47:37 +00002521 TypeLocBuilder TLB;
2522 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002523 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2524 SpecTL.setElaboratedKeywordLoc(TagLoc);
2525 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002526 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002527 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002528 SpecTL.setLAngleLoc(LAngleLoc);
2529 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002530 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2531 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2532 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2533 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00002534
2535 if (TypeAliasTemplateDecl *TAT =
2536 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2537 // C++0x [dcl.type.elab]p2:
2538 // If the identifier resolves to a typedef-name or the simple-template-id
2539 // resolves to an alias template specialization, the
2540 // elaborated-type-specifier is ill-formed.
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00002541 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
2542 << TAT << NTK_TypeAliasTemplate << TagKind;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002543 Diag(TAT->getLocation(), diag::note_declared_at);
2544 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00002545
Douglas Gregore7c20652011-03-02 00:47:37 +00002546 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2547 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00002548 return TypeResult(true);
Simon Pilgrim6905d222016-12-30 22:55:33 +00002549
Douglas Gregore7c20652011-03-02 00:47:37 +00002550 // Check the tag kind
2551 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00002552 RecordDecl *D = RT->getDecl();
Simon Pilgrim6905d222016-12-30 22:55:33 +00002553
John McCalld8fe9af2009-09-08 17:47:29 +00002554 IdentifierInfo *Id = D->getIdentifier();
2555 assert(Id && "templated class must have an identifier");
Simon Pilgrim6905d222016-12-30 22:55:33 +00002556
Richard Trieucaa33d32011-06-10 03:11:26 +00002557 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00002558 TagLoc, Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00002559 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00002560 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00002561 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00002562 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00002563 }
2564 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002565
Douglas Gregore7c20652011-03-02 00:47:37 +00002566 // Provide source-location information for the template specialization.
2567 TypeLocBuilder TLB;
2568 TemplateSpecializationTypeLoc SpecTL
2569 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002570 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002571 SpecTL.setTemplateNameLoc(TemplateLoc);
2572 SpecTL.setLAngleLoc(LAngleLoc);
2573 SpecTL.setRAngleLoc(RAngleLoc);
2574 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2575 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00002576
Douglas Gregore7c20652011-03-02 00:47:37 +00002577 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002578 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00002579 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2580 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002581 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002582 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2583 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00002584}
2585
Larisse Voufo39a1e502013-08-06 01:03:05 +00002586static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
2587 NamedDecl *PrevDecl,
2588 SourceLocation Loc,
2589 bool IsPartialSpecialization);
2590
2591static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002592
Richard Smith300e0c32013-09-24 04:49:23 +00002593static bool isTemplateArgumentTemplateParameter(
2594 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
2595 switch (Arg.getKind()) {
2596 case TemplateArgument::Null:
2597 case TemplateArgument::NullPtr:
2598 case TemplateArgument::Integral:
2599 case TemplateArgument::Declaration:
2600 case TemplateArgument::Pack:
2601 case TemplateArgument::TemplateExpansion:
2602 return false;
2603
2604 case TemplateArgument::Type: {
2605 QualType Type = Arg.getAsType();
2606 const TemplateTypeParmType *TPT =
2607 Arg.getAsType()->getAs<TemplateTypeParmType>();
2608 return TPT && !Type.hasQualifiers() &&
2609 TPT->getDepth() == Depth && TPT->getIndex() == Index;
2610 }
2611
2612 case TemplateArgument::Expression: {
2613 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
2614 if (!DRE || !DRE->getDecl())
2615 return false;
2616 const NonTypeTemplateParmDecl *NTTP =
2617 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2618 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
2619 }
2620
2621 case TemplateArgument::Template:
2622 const TemplateTemplateParmDecl *TTP =
2623 dyn_cast_or_null<TemplateTemplateParmDecl>(
2624 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
2625 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
2626 }
2627 llvm_unreachable("unexpected kind of template argument");
2628}
2629
2630static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
2631 ArrayRef<TemplateArgument> Args) {
2632 if (Params->size() != Args.size())
2633 return false;
2634
2635 unsigned Depth = Params->getDepth();
2636
2637 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2638 TemplateArgument Arg = Args[I];
2639
2640 // If the parameter is a pack expansion, the argument must be a pack
2641 // whose only element is a pack expansion.
2642 if (Params->getParam(I)->isParameterPack()) {
2643 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
2644 !Arg.pack_begin()->isPackExpansion())
2645 return false;
2646 Arg = Arg.pack_begin()->getPackExpansionPattern();
2647 }
2648
2649 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
2650 return false;
2651 }
2652
2653 return true;
2654}
2655
Richard Smith4b55a9c2014-04-17 03:29:33 +00002656/// Convert the parser's template argument list representation into our form.
2657static TemplateArgumentListInfo
2658makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
2659 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
2660 TemplateId.RAngleLoc);
2661 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
2662 TemplateId.NumArgs);
2663 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
2664 return TemplateArgs;
2665}
2666
Richard Smith0e617ec2016-12-27 07:56:27 +00002667template<typename PartialSpecDecl>
2668static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
2669 if (Partial->getDeclContext()->isDependentContext())
2670 return;
2671
2672 // FIXME: Get the TDK from deduction in order to provide better diagnostics
2673 // for non-substitution-failure issues?
2674 TemplateDeductionInfo Info(Partial->getLocation());
2675 if (S.isMoreSpecializedThanPrimary(Partial, Info))
2676 return;
2677
2678 auto *Template = Partial->getSpecializedTemplate();
2679 S.Diag(Partial->getLocation(),
Richard Smithfa4a09d2016-12-27 20:03:09 +00002680 diag::ext_partial_spec_not_more_specialized_than_primary)
2681 << isa<VarTemplateDecl>(Template);
Richard Smith0e617ec2016-12-27 07:56:27 +00002682
2683 if (Info.hasSFINAEDiagnostic()) {
2684 PartialDiagnosticAt Diag = {SourceLocation(),
2685 PartialDiagnostic::NullDiagnostic()};
2686 Info.takeSFINAEDiagnostic(Diag);
2687 SmallString<128> SFINAEArgString;
2688 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
2689 S.Diag(Diag.first,
2690 diag::note_partial_spec_not_more_specialized_than_primary)
2691 << SFINAEArgString;
2692 }
2693
2694 S.Diag(Template->getLocation(), diag::note_template_decl_here);
2695}
2696
Richard Smith57aae072016-12-28 02:37:25 +00002697template<typename PartialSpecDecl>
2698static void checkTemplatePartialSpecialization(Sema &S,
2699 PartialSpecDecl *Partial) {
2700 // C++1z [temp.class.spec]p8: (DR1495)
2701 // - The specialization shall be more specialized than the primary
2702 // template (14.5.5.2).
2703 checkMoreSpecializedThanPrimary(S, Partial);
2704
2705 // C++ [temp.class.spec]p8: (DR1315)
2706 // - Each template-parameter shall appear at least once in the
2707 // template-id outside a non-deduced context.
2708 // C++1z [temp.class.spec.match]p3 (P0127R2)
2709 // If the template arguments of a partial specialization cannot be
2710 // deduced because of the structure of its template-parameter-list
2711 // and the template-id, the program is ill-formed.
2712 auto *TemplateParams = Partial->getTemplateParameters();
2713 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
2714 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2715 TemplateParams->getDepth(), DeducibleParams);
2716
2717 if (!DeducibleParams.all()) {
2718 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
2719 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
2720 << isa<VarTemplatePartialSpecializationDecl>(Partial)
2721 << (NumNonDeducible > 1)
2722 << SourceRange(Partial->getLocation(),
2723 Partial->getTemplateArgsAsWritten()->RAngleLoc);
2724 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2725 if (!DeducibleParams[I]) {
2726 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2727 if (Param->getDeclName())
2728 S.Diag(Param->getLocation(),
2729 diag::note_partial_spec_unused_parameter)
2730 << Param->getDeclName();
2731 else
2732 S.Diag(Param->getLocation(),
2733 diag::note_partial_spec_unused_parameter)
2734 << "(anonymous)";
2735 }
2736 }
2737 }
2738}
2739
2740void Sema::CheckTemplatePartialSpecialization(
2741 ClassTemplatePartialSpecializationDecl *Partial) {
2742 checkTemplatePartialSpecialization(*this, Partial);
2743}
2744
2745void Sema::CheckTemplatePartialSpecialization(
2746 VarTemplatePartialSpecializationDecl *Partial) {
2747 checkTemplatePartialSpecialization(*this, Partial);
2748}
2749
Larisse Voufo39a1e502013-08-06 01:03:05 +00002750DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00002751 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00002752 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00002753 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002754 // D must be variable template id.
2755 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2756 "Variable template specialization is declared with a template it.");
2757
2758 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002759 TemplateArgumentListInfo TemplateArgs =
2760 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002761 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2762 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2763 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002764
Richard Smithbeef3452014-01-16 23:39:20 +00002765 TemplateName Name = TemplateId->Template.get();
2766
2767 // The template-id must name a variable template.
2768 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00002769 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
2770 if (!VarTemplate) {
2771 NamedDecl *FnTemplate;
2772 if (auto *OTS = Name.getAsOverloadedTemplate())
2773 FnTemplate = *OTS->begin();
2774 else
2775 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
2776 if (FnTemplate)
2777 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
2778 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00002779 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
2780 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00002781 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002782
2783 // Check for unexpanded parameter packs in any of the template arguments.
2784 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2785 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2786 UPPC_PartialSpecialization))
2787 return true;
2788
2789 // Check that the template argument list is well-formed for this
2790 // template.
2791 SmallVector<TemplateArgument, 4> Converted;
2792 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2793 false, Converted))
2794 return true;
2795
Larisse Voufo39a1e502013-08-06 01:03:05 +00002796 // Find the variable template (partial) specialization declaration that
2797 // corresponds to these arguments.
2798 if (IsPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00002799 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
2800 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002801 return true;
2802
Richard Smith57aae072016-12-28 02:37:25 +00002803 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
2804 // also do them during instantiation.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002805 bool InstantiationDependent;
2806 if (!Name.isDependent() &&
2807 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00002808 TemplateArgs.arguments(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00002809 InstantiationDependent)) {
2810 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2811 << VarTemplate->getDeclName();
2812 IsPartialSpecialization = false;
2813 }
Richard Smith300e0c32013-09-24 04:49:23 +00002814
2815 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
2816 Converted)) {
2817 // C++ [temp.class.spec]p9b3:
2818 //
2819 // -- The argument list of the specialization shall not be identical
2820 // to the implicit argument list of the primary template.
2821 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2822 << /*variable template*/ 1
2823 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2824 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2825 // FIXME: Recover from this by treating the declaration as a redeclaration
2826 // of the primary template.
2827 return true;
2828 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002829 }
2830
Craig Topperc3ec1492014-05-26 06:22:03 +00002831 void *InsertPos = nullptr;
2832 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002833
2834 if (IsPartialSpecialization)
2835 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00002836 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002837 else
Craig Topper7e0daca2014-06-26 04:58:53 +00002838 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002839
Craig Topperc3ec1492014-05-26 06:22:03 +00002840 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002841
2842 // Check whether we can declare a variable template specialization in
2843 // the current scope.
2844 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
2845 TemplateNameLoc,
2846 IsPartialSpecialization))
2847 return true;
2848
2849 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2850 // Since the only prior variable template specialization with these
2851 // arguments was referenced but not declared, reuse that
2852 // declaration node as our own, updating its source location and
2853 // the list of outer template parameters to reflect our new declaration.
2854 Specialization = PrevDecl;
2855 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002856 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002857 } else if (IsPartialSpecialization) {
2858 // Create a new class template partial specialization declaration node.
2859 VarTemplatePartialSpecializationDecl *PrevPartial =
2860 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002861 VarTemplatePartialSpecializationDecl *Partial =
2862 VarTemplatePartialSpecializationDecl::Create(
2863 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
2864 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
David Majnemer8b622692016-07-03 21:17:51 +00002865 Converted, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002866
2867 if (!PrevPartial)
2868 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
2869 Specialization = Partial;
2870
2871 // If we are providing an explicit specialization of a member variable
2872 // template specialization, make a note of that.
2873 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00002874 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002875
Richard Smith57aae072016-12-28 02:37:25 +00002876 CheckTemplatePartialSpecialization(Partial);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002877 } else {
2878 // Create a new class template specialization declaration node for
2879 // this explicit specialization or friend declaration.
2880 Specialization = VarTemplateSpecializationDecl::Create(
2881 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
David Majnemer8b622692016-07-03 21:17:51 +00002882 VarTemplate, DI->getType(), DI, SC, Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002883 Specialization->setTemplateArgsInfo(TemplateArgs);
2884
2885 if (!PrevDecl)
2886 VarTemplate->AddSpecialization(Specialization, InsertPos);
2887 }
2888
2889 // C++ [temp.expl.spec]p6:
2890 // If a template, a member template or the member of a class template is
2891 // explicitly specialized then that specialization shall be declared
2892 // before the first use of that specialization that would cause an implicit
2893 // instantiation to take place, in every translation unit in which such a
2894 // use occurs; no diagnostic is required.
2895 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2896 bool Okay = false;
2897 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
2898 // Is there any previous explicit specialization declaration?
2899 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
2900 Okay = true;
2901 break;
2902 }
2903 }
2904
2905 if (!Okay) {
2906 SourceRange Range(TemplateNameLoc, RAngleLoc);
2907 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2908 << Name << Range;
2909
2910 Diag(PrevDecl->getPointOfInstantiation(),
2911 diag::note_instantiation_required_here)
2912 << (PrevDecl->getTemplateSpecializationKind() !=
2913 TSK_ImplicitInstantiation);
2914 return true;
2915 }
2916 }
2917
2918 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
2919 Specialization->setLexicalDeclContext(CurContext);
2920
2921 // Add the specialization into its lexical context, so that it can
2922 // be seen when iterating through the list of declarations in that
2923 // context. However, specializations are not found by name lookup.
2924 CurContext->addDecl(Specialization);
2925
2926 // Note that this is an explicit specialization.
2927 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2928
2929 if (PrevDecl) {
2930 // Check that this isn't a redefinition of this specialization,
2931 // merging with previous declarations.
2932 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
2933 ForRedeclaration);
2934 PrevSpec.addDecl(PrevDecl);
2935 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00002936 } else if (Specialization->isStaticDataMember() &&
2937 Specialization->isOutOfLine()) {
2938 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00002939 }
2940
2941 // Link instantiations of static data members back to the template from
2942 // which they were instantiated.
2943 if (Specialization->isStaticDataMember())
2944 Specialization->setInstantiationOfStaticDataMember(
2945 VarTemplate->getTemplatedDecl(),
2946 Specialization->getSpecializationKind());
2947
2948 return Specialization;
2949}
2950
2951namespace {
2952/// \brief A partial specialization whose template arguments have matched
2953/// a given template-id.
2954struct PartialSpecMatchResult {
2955 VarTemplatePartialSpecializationDecl *Partial;
2956 TemplateArgumentList *Args;
2957};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002958} // end anonymous namespace
Larisse Voufo39a1e502013-08-06 01:03:05 +00002959
2960DeclResult
2961Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
2962 SourceLocation TemplateNameLoc,
2963 const TemplateArgumentListInfo &TemplateArgs) {
2964 assert(Template && "A variable template id without template?");
2965
2966 // Check that the template argument list is well-formed for this template.
2967 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002968 if (CheckTemplateArgumentList(
2969 Template, TemplateNameLoc,
2970 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00002971 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002972 return true;
2973
2974 // Find the variable template specialization declaration that
2975 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002976 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002977 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Richard Smith6739a102016-05-05 00:56:12 +00002978 Converted, InsertPos)) {
2979 checkSpecializationVisibility(TemplateNameLoc, Spec);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002980 // If we already have a variable template specialization, return it.
2981 return Spec;
Richard Smith6739a102016-05-05 00:56:12 +00002982 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002983
2984 // This is the first time we have referenced this variable template
2985 // specialization. Create the canonical declaration and add it to
2986 // the set of specializations, based on the closest partial specialization
2987 // that it represents. That is,
2988 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
2989 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00002990 Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002991 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
2992 bool AmbiguousPartialSpec = false;
2993 typedef PartialSpecMatchResult MatchResult;
2994 SmallVector<MatchResult, 4> Matched;
2995 SourceLocation PointOfInstantiation = TemplateNameLoc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002996 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
2997 /*ForTakingAddress=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002998
2999 // 1. Attempt to find the closest partial specialization that this
3000 // specializes, if any.
3001 // If any of the template arguments is dependent, then this is probably
3002 // a placeholder for an incomplete declarative context; which must be
3003 // complete by instantiation time. Thus, do not search through the partial
3004 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00003005 // TODO: Unify with InstantiateClassTemplateSpecialization()?
3006 // Perhaps better after unification of DeduceTemplateArguments() and
3007 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00003008 bool InstantiationDependent = false;
3009 if (!TemplateSpecializationType::anyDependentTemplateArguments(
3010 TemplateArgs, InstantiationDependent)) {
3011
3012 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3013 Template->getPartialSpecializations(PartialSpecs);
3014
3015 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3016 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3017 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3018
3019 if (TemplateDeductionResult Result =
3020 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
3021 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00003022 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00003023 FailedCandidates.addCandidate().set(
3024 DeclAccessPair::make(Template, AS_public), Partial,
3025 MakeDeductionFailureInfo(Context, Result, Info));
Larisse Voufo39a1e502013-08-06 01:03:05 +00003026 (void)Result;
3027 } else {
3028 Matched.push_back(PartialSpecMatchResult());
3029 Matched.back().Partial = Partial;
3030 Matched.back().Args = Info.take();
3031 }
3032 }
3033
Larisse Voufo39a1e502013-08-06 01:03:05 +00003034 if (Matched.size() >= 1) {
3035 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
3036 if (Matched.size() == 1) {
3037 // -- If exactly one matching specialization is found, the
3038 // instantiation is generated from that specialization.
3039 // We don't need to do anything for this.
3040 } else {
3041 // -- If more than one matching specialization is found, the
3042 // partial order rules (14.5.4.2) are used to determine
3043 // whether one of the specializations is more specialized
3044 // than the others. If none of the specializations is more
3045 // specialized than all of the other matching
3046 // specializations, then the use of the variable template is
3047 // ambiguous and the program is ill-formed.
3048 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
3049 PEnd = Matched.end();
3050 P != PEnd; ++P) {
3051 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
3052 PointOfInstantiation) ==
3053 P->Partial)
3054 Best = P;
3055 }
3056
3057 // Determine if the best partial specialization is more specialized than
3058 // the others.
3059 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
3060 PEnd = Matched.end();
3061 P != PEnd; ++P) {
3062 if (P != Best && getMoreSpecializedPartialSpecialization(
3063 P->Partial, Best->Partial,
3064 PointOfInstantiation) != Best->Partial) {
3065 AmbiguousPartialSpec = true;
3066 break;
3067 }
3068 }
3069 }
3070
3071 // Instantiate using the best variable template partial specialization.
3072 InstantiationPattern = Best->Partial;
3073 InstantiationArgs = Best->Args;
3074 } else {
3075 // -- If no match is found, the instantiation is generated
3076 // from the primary template.
3077 // InstantiationPattern = Template->getTemplatedDecl();
3078 }
3079 }
3080
Larisse Voufo39a1e502013-08-06 01:03:05 +00003081 // 2. Create the canonical declaration.
Richard Smith6739a102016-05-05 00:56:12 +00003082 // Note that we do not instantiate a definition until we see an odr-use
3083 // in DoMarkVarDeclReferenced().
Larisse Voufo39a1e502013-08-06 01:03:05 +00003084 // FIXME: LateAttrs et al.?
3085 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
3086 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
3087 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
3088 if (!Decl)
3089 return true;
3090
3091 if (AmbiguousPartialSpec) {
3092 // Partial ordering did not produce a clear winner. Complain.
3093 Decl->setInvalidDecl();
3094 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
3095 << Decl;
3096
3097 // Print the matching partial specializations.
Yaron Keren1cb81462016-11-16 13:45:34 +00003098 for (MatchResult P : Matched)
3099 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
3100 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
3101 *P.Args);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003102 return true;
3103 }
3104
3105 if (VarTemplatePartialSpecializationDecl *D =
3106 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
3107 Decl->setInstantiationOf(D, InstantiationArgs);
3108
Richard Smith6739a102016-05-05 00:56:12 +00003109 checkSpecializationVisibility(TemplateNameLoc, Decl);
3110
Larisse Voufo39a1e502013-08-06 01:03:05 +00003111 assert(Decl && "No variable template specialization?");
3112 return Decl;
3113}
3114
3115ExprResult
3116Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
3117 const DeclarationNameInfo &NameInfo,
3118 VarTemplateDecl *Template, SourceLocation TemplateLoc,
3119 const TemplateArgumentListInfo *TemplateArgs) {
3120
3121 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
3122 *TemplateArgs);
3123 if (Decl.isInvalid())
3124 return ExprError();
3125
3126 VarDecl *Var = cast<VarDecl>(Decl.get());
3127 if (!Var->getTemplateSpecializationKind())
3128 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
3129 NameInfo.getLoc());
3130
3131 // Build an ordinary singleton decl ref.
3132 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00003133 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003134}
3135
John McCalldadc5752010-08-24 06:29:42 +00003136ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003137 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00003138 LookupResult &R,
3139 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003140 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00003141 // FIXME: Can we do any checking at this point? I guess we could check the
3142 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00003143 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00003144 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00003145 // foo<int> could identify a single function unambiguously
3146 // This approach does NOT work, since f<int>(1);
3147 // gets resolved prior to resorting to overload resolution
3148 // i.e., template<class T> void f(double);
3149 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00003150
3151 // These should be filtered out by our callers.
3152 assert(!R.empty() && "empty lookup results when building templateid");
3153 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
3154
Larisse Voufo39a1e502013-08-06 01:03:05 +00003155 // In C++1y, check variable template ids.
Richard Smithd7d11ef2014-02-03 20:09:56 +00003156 bool InstantiationDependent;
3157 if (R.getAsSingle<VarTemplateDecl>() &&
3158 !TemplateSpecializationType::anyDependentTemplateArguments(
3159 *TemplateArgs, InstantiationDependent)) {
3160 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
3161 R.getAsSingle<VarTemplateDecl>(),
3162 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003163 }
3164
John McCall58cc69d2010-01-27 01:50:18 +00003165 // We don't want lookup warnings at this point.
3166 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003167
John McCalle66edc12009-11-24 19:00:30 +00003168 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00003169 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00003170 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003171 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003172 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003173 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00003174 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00003175
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003176 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00003177}
3178
John McCalle66edc12009-11-24 19:00:30 +00003179// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00003180ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003181Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003182 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003183 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003184 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003185
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003186 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00003187 DeclContext *DC;
3188 if (!(DC = computeDeclContext(SS, false)) ||
3189 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00003190 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00003191 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003192
Douglas Gregor786123d2010-05-21 23:18:07 +00003193 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003194 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Craig Topperc3ec1492014-05-26 06:22:03 +00003195 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
Douglas Gregor786123d2010-05-21 23:18:07 +00003196 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00003197
John McCalle66edc12009-11-24 19:00:30 +00003198 if (R.isAmbiguous())
3199 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003200
John McCalle66edc12009-11-24 19:00:30 +00003201 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003202 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
3203 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00003204 return ExprError();
3205 }
3206
3207 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003208 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00003209 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00003210 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00003211 Diag(Temp->getLocation(), diag::note_referenced_class_template);
3212 return ExprError();
3213 }
3214
Abramo Bagnara7945c982012-01-27 09:46:47 +00003215 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00003216}
3217
Douglas Gregorb67535d2009-03-31 00:43:58 +00003218/// \brief Form a dependent template name.
3219///
3220/// This action forms a dependent template name given the template
3221/// name and its (presumably dependent) scope specifier. For
3222/// example, given "MetaFun::template apply", the scope specifier \p
3223/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
3224/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003225TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00003226 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003227 SourceLocation TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00003228 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00003229 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00003230 bool EnteringContext,
3231 TemplateTy &Result) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00003232 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
3233 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003234 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00003235 diag::warn_cxx98_compat_template_outside_of_template :
3236 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003237 << FixItHint::CreateRemoval(TemplateKWLoc);
3238
Craig Topperc3ec1492014-05-26 06:22:03 +00003239 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00003240 if (SS.isSet())
3241 LookupCtx = computeDeclContext(SS, EnteringContext);
3242 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00003243 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00003244 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00003245 // C++0x [temp.names]p5:
3246 // If a name prefixed by the keyword template is not the name of
3247 // a template, the program is ill-formed. [Note: the keyword
3248 // template may not be applied to non-template members of class
3249 // templates. -end note ] [ Note: as is the case with the
3250 // typename prefix, the template prefix is allowed in cases
3251 // where it is not strictly necessary; i.e., when the
3252 // nested-name-specifier or the expression on the left of the ->
3253 // or . is not dependent on a template-parameter, or the use
3254 // does not appear in the scope of a template. -end note]
3255 //
3256 // Note: C++03 was more strict here, because it banned the use of
3257 // the "template" keyword prior to a template-name that was not a
3258 // dependent name. C++ DR468 relaxed this requirement (the
3259 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00003260 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00003261 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00003262 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00003263 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00003264 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00003265 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
3266 isa<CXXRecordDecl>(LookupCtx) &&
Douglas Gregor5ecbb1b2011-03-11 23:27:41 +00003267 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
3268 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
Douglas Gregorbb119652010-06-16 23:00:59 +00003269 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00003270 } else if (TNK == TNK_Non_template) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003271 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003272 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003273 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003274 << Name.getSourceRange()
3275 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003276 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00003277 } else {
3278 // We found something; return it.
Douglas Gregorbb119652010-06-16 23:00:59 +00003279 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003280 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00003281 }
3282
Aaron Ballman4a979672014-01-03 13:56:08 +00003283 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003284
Douglas Gregor3cf81312009-11-03 23:16:33 +00003285 switch (Name.getKind()) {
3286 case UnqualifiedId::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003287 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00003288 Name.Identifier));
3289 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003290
Douglas Gregor71395fa2009-11-04 00:56:37 +00003291 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00003292 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00003293 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00003294 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00003295
3296 case UnqualifiedId::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00003297 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00003298
Douglas Gregor3cf81312009-11-03 23:16:33 +00003299 default:
3300 break;
3301 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003302
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003303 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003304 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003305 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003306 << Name.getSourceRange()
3307 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003308 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003309}
3310
Mike Stump11289f42009-09-09 15:08:12 +00003311bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003312 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003313 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00003314 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00003315 QualType ArgType;
3316 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00003317
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003318 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003319 switch(Arg.getKind()) {
3320 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003321 // C++ [temp.arg.type]p1:
3322 // A template-argument for a template-parameter which is a
3323 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00003324 ArgType = Arg.getAsType();
3325 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003326 break;
3327 case TemplateArgument::Template: {
3328 // We have a template type parameter but the template argument
3329 // is a template without any arguments.
3330 SourceRange SR = AL.getSourceRange();
3331 TemplateName Name = Arg.getAsTemplate();
3332 Diag(SR.getBegin(), diag::err_template_missing_args)
3333 << Name << SR;
3334 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3335 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003336
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003337 return true;
3338 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003339 case TemplateArgument::Expression: {
3340 // We have a template type parameter but the template argument is an
3341 // expression; see if maybe it is missing the "typename" keyword.
3342 CXXScopeSpec SS;
3343 DeclarationNameInfo NameInfo;
3344
3345 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3346 SS.Adopt(ArgExpr->getQualifierLoc());
3347 NameInfo = ArgExpr->getNameInfo();
3348 } else if (DependentScopeDeclRefExpr *ArgExpr =
3349 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3350 SS.Adopt(ArgExpr->getQualifierLoc());
3351 NameInfo = ArgExpr->getNameInfo();
3352 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3353 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003354 if (ArgExpr->isImplicitAccess()) {
3355 SS.Adopt(ArgExpr->getQualifierLoc());
3356 NameInfo = ArgExpr->getMemberNameInfo();
3357 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003358 }
3359
Reid Kleckner377c1592014-06-10 23:29:48 +00003360 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003361 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3362 LookupParsedName(Result, CurScope, &SS);
3363
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003364 if (Result.getAsSingle<TypeDecl>() ||
3365 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00003366 LookupResult::NotFoundInCurrentInstantiation) {
3367 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003368 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00003369 Diag(Loc, getLangOpts().MSVCCompat
3370 ? diag::ext_ms_template_type_arg_missing_typename
3371 : diag::err_template_arg_must_be_type_suggest)
3372 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003373 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00003374
3375 // Recover by synthesizing a type using the location information that we
3376 // already have.
3377 ArgType =
3378 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3379 TypeLocBuilder TLB;
3380 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3381 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3382 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3383 TL.setNameLoc(NameInfo.getLoc());
3384 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3385
3386 // Overwrite our input TemplateArgumentLoc so that we can recover
3387 // properly.
3388 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3389 TemplateArgumentLocInfo(TSI));
3390
3391 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003392 }
3393 }
3394 // fallthrough
3395 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003396 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003397 // We have a template type parameter but the template argument
3398 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00003399 SourceRange SR = AL.getSourceRange();
3400 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003401 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003402
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003403 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003404 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003405 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003406
Reid Kleckner377c1592014-06-10 23:29:48 +00003407 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003408 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003409
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003410 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00003411 ArgType = Context.getCanonicalType(ArgType);
Simon Pilgrim6905d222016-12-30 22:55:33 +00003412
Douglas Gregore46db902011-06-17 22:11:49 +00003413 // Objective-C ARC:
3414 // If an explicitly-specified template argument type is a lifetime type
3415 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003416 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00003417 ArgType->isObjCLifetimeType() &&
3418 !ArgType.getObjCLifetime()) {
3419 Qualifiers Qs;
3420 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3421 ArgType = Context.getQualifiedType(ArgType, Qs);
3422 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00003423
Douglas Gregore46db902011-06-17 22:11:49 +00003424 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003425 return false;
3426}
3427
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003428/// \brief Substitute template arguments into the default template argument for
3429/// the given template type parameter.
3430///
3431/// \param SemaRef the semantic analysis object for which we are performing
3432/// the substitution.
3433///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003434/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003435/// for.
3436///
3437/// \param TemplateLoc the location of the template name that started the
3438/// template-id we are checking.
3439///
3440/// \param RAngleLoc the location of the right angle bracket ('>') that
3441/// terminates the template-id.
3442///
3443/// \param Param the template template parameter whose default we are
3444/// substituting into.
3445///
3446/// \param Converted the list of template arguments provided for template
3447/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003448/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00003449static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003450SubstDefaultTemplateArgument(Sema &SemaRef,
3451 TemplateDecl *Template,
3452 SourceLocation TemplateLoc,
3453 SourceLocation RAngleLoc,
3454 TemplateTypeParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003455 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00003456 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003457
3458 // If the argument type is dependent, instantiate it now based
3459 // on the previously-computed template arguments.
3460 if (ArgType->getType()->isDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003461 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00003462 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003463 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003464 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00003465 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003466
David Majnemer8b622692016-07-03 21:17:51 +00003467 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00003468
3469 // Only substitute for the innermost template argument list.
3470 MultiLevelTemplateArgumentList TemplateArgLists;
3471 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3472 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3473 TemplateArgLists.addOuterTemplateArguments(None);
3474
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003475 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003476 ArgType =
3477 SemaRef.SubstType(ArgType, TemplateArgLists,
3478 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003479 }
3480
3481 return ArgType;
3482}
3483
3484/// \brief Substitute template arguments into the default template argument for
3485/// the given non-type template parameter.
3486///
3487/// \param SemaRef the semantic analysis object for which we are performing
3488/// the substitution.
3489///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003490/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003491/// for.
3492///
3493/// \param TemplateLoc the location of the template name that started the
3494/// template-id we are checking.
3495///
3496/// \param RAngleLoc the location of the right angle bracket ('>') that
3497/// terminates the template-id.
3498///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003499/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003500/// substituting into.
3501///
3502/// \param Converted the list of template arguments provided for template
3503/// parameters that precede \p Param in the template parameter list.
3504///
3505/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00003506static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003507SubstDefaultTemplateArgument(Sema &SemaRef,
3508 TemplateDecl *Template,
3509 SourceLocation TemplateLoc,
3510 SourceLocation RAngleLoc,
3511 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003512 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003513 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00003514 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003515 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003516 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003517 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003518
David Majnemer8b622692016-07-03 21:17:51 +00003519 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00003520
3521 // Only substitute for the innermost template argument list.
3522 MultiLevelTemplateArgumentList TemplateArgLists;
3523 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3524 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3525 TemplateArgLists.addOuterTemplateArguments(None);
3526
Faisal Vali48401eb2015-11-19 19:20:17 +00003527 EnterExpressionEvaluationContext ConstantEvaluated(SemaRef,
3528 Sema::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00003529 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003530}
3531
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003532/// \brief Substitute template arguments into the default template argument for
3533/// the given template template parameter.
3534///
3535/// \param SemaRef the semantic analysis object for which we are performing
3536/// the substitution.
3537///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003538/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003539/// for.
3540///
3541/// \param TemplateLoc the location of the template name that started the
3542/// template-id we are checking.
3543///
3544/// \param RAngleLoc the location of the right angle bracket ('>') that
3545/// terminates the template-id.
3546///
3547/// \param Param the template template parameter whose default we are
3548/// substituting into.
3549///
3550/// \param Converted the list of template arguments provided for template
3551/// parameters that precede \p Param in the template parameter list.
3552///
Simon Pilgrim6905d222016-12-30 22:55:33 +00003553/// \param QualifierLoc Will be set to the nested-name-specifier (with
Douglas Gregordf846d12011-03-02 18:46:51 +00003554/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00003555///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003556/// \returns the substituted template argument, or NULL if an error occurred.
3557static TemplateName
3558SubstDefaultTemplateArgument(Sema &SemaRef,
3559 TemplateDecl *Template,
3560 SourceLocation TemplateLoc,
3561 SourceLocation RAngleLoc,
3562 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003563 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00003564 NestedNameSpecifierLoc &QualifierLoc) {
Richard Smith54f18e82016-08-31 02:15:21 +00003565 Sema::InstantiatingTemplate Inst(
3566 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
3567 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003568 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003569 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003570
David Majnemer8b622692016-07-03 21:17:51 +00003571 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00003572
3573 // Only substitute for the innermost template argument list.
3574 MultiLevelTemplateArgumentList TemplateArgLists;
3575 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3576 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3577 TemplateArgLists.addOuterTemplateArguments(None);
3578
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003579 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003580 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00003581 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00003582 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003583 QualifierLoc =
3584 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00003585 if (!QualifierLoc)
3586 return TemplateName();
3587 }
David Majnemer89189202013-08-28 23:48:32 +00003588
3589 return SemaRef.SubstTemplateName(
3590 QualifierLoc,
3591 Param->getDefaultArgument().getArgument().getAsTemplate(),
3592 Param->getDefaultArgument().getTemplateNameLoc(),
3593 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003594}
3595
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003596/// \brief If the given template parameter has a default template
3597/// argument, substitute into that default template argument and
3598/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003599TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003600Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3601 SourceLocation TemplateLoc,
3602 SourceLocation RAngleLoc,
3603 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00003604 SmallVectorImpl<TemplateArgument>
3605 &Converted,
3606 bool &HasDefaultArg) {
3607 HasDefaultArg = false;
3608
3609 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003610 if (!hasVisibleDefaultArgument(TypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003611 return TemplateArgumentLoc();
3612
Richard Smithc87b9382013-07-04 01:01:24 +00003613 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00003614 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003615 TemplateLoc,
3616 RAngleLoc,
3617 TypeParm,
3618 Converted);
3619 if (DI)
3620 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3621
3622 return TemplateArgumentLoc();
3623 }
3624
3625 if (NonTypeTemplateParmDecl *NonTypeParm
3626 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003627 if (!hasVisibleDefaultArgument(NonTypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003628 return TemplateArgumentLoc();
3629
Richard Smithc87b9382013-07-04 01:01:24 +00003630 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00003631 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00003632 TemplateLoc,
3633 RAngleLoc,
3634 NonTypeParm,
3635 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003636 if (Arg.isInvalid())
3637 return TemplateArgumentLoc();
3638
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003639 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003640 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3641 }
3642
3643 TemplateTemplateParmDecl *TempTempParm
3644 = cast<TemplateTemplateParmDecl>(Param);
Richard Smith95d83952015-06-10 20:36:34 +00003645 if (!hasVisibleDefaultArgument(TempTempParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003646 return TemplateArgumentLoc();
3647
Richard Smithc87b9382013-07-04 01:01:24 +00003648 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00003649 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003650 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003651 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003652 RAngleLoc,
3653 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003654 Converted,
3655 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003656 if (TName.isNull())
3657 return TemplateArgumentLoc();
3658
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003659 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00003660 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003661 TempTempParm->getDefaultArgument().getTemplateNameLoc());
3662}
3663
Douglas Gregorda0fb532009-11-11 19:31:23 +00003664/// \brief Check that the given template argument corresponds to the given
3665/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003666///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003667/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003668/// checked.
3669///
Richard Trieu15b66532015-01-24 02:48:32 +00003670/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003671///
3672/// \param Template The template in which the template argument resides.
3673///
3674/// \param TemplateLoc The location of the template name for the template
3675/// whose argument list we're matching.
3676///
3677/// \param RAngleLoc The location of the right angle bracket ('>') that closes
3678/// the template argument list.
3679///
3680/// \param ArgumentPackIndex The index into the argument pack where this
3681/// argument will be placed. Only valid if the parameter is a parameter pack.
3682///
3683/// \param Converted The checked, converted argument will be added to the
3684/// end of this small vector.
3685///
3686/// \param CTAK Describes how we arrived at this particular template argument:
3687/// explicitly written, deduced, etc.
3688///
3689/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003690bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003691 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00003692 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003693 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003694 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003695 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003696 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003697 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00003698 // Check template type parameters.
3699 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003700 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003701
Douglas Gregoreebed722009-11-11 19:41:09 +00003702 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003703 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003704 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00003705 // with the template arguments we've seen thus far. But if the
3706 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003707 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003708 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3709 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003710
Peter Collingbourne01687632010-12-10 17:08:53 +00003711 if (NTTPType->isDependentType() &&
3712 !isa<TemplateTemplateParmDecl>(Template) &&
3713 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003714 // Do substitution on the type of the non-type template parameter.
3715 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003716 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003717 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003718 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003719 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003720
3721 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00003722 Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003723 NTTPType = SubstType(NTTPType,
3724 MultiLevelTemplateArgumentList(TemplateArgs),
3725 NTTP->getLocation(),
3726 NTTP->getDeclName());
3727 // If that worked, check the non-type template parameter type
3728 // for validity.
3729 if (!NTTPType.isNull())
3730 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3731 NTTP->getLocation());
3732 if (NTTPType.isNull())
3733 return true;
3734 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003735
Douglas Gregorda0fb532009-11-11 19:31:23 +00003736 switch (Arg.getArgument().getKind()) {
3737 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003738 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003739
Douglas Gregorda0fb532009-11-11 19:31:23 +00003740 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003741 TemplateArgument Result;
John Wiegley01296292011-04-08 18:41:53 +00003742 ExprResult Res =
3743 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3744 Result, CTAK);
3745 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003746 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003747
Richard Trieu15b66532015-01-24 02:48:32 +00003748 // If the resulting expression is new, then use it in place of the
3749 // old expression in the template argument.
3750 if (Res.get() != Arg.getArgument().getAsExpr()) {
3751 TemplateArgument TA(Res.get());
3752 Arg = TemplateArgumentLoc(TA, Res.get());
3753 }
3754
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003755 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003756 break;
3757 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003758
Douglas Gregorda0fb532009-11-11 19:31:23 +00003759 case TemplateArgument::Declaration:
3760 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00003761 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003762 // We've already checked this template argument, so just copy
3763 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003764 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003765 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003766
Douglas Gregorda0fb532009-11-11 19:31:23 +00003767 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003768 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003769 // We were given a template template argument. It may not be ill-formed;
3770 // see below.
3771 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003772 = Arg.getArgument().getAsTemplateOrTemplatePattern()
3773 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003774 // We have a template argument such as \c T::template X, which we
3775 // parsed as a template template argument. However, since we now
3776 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003777 // template name into an expression.
3778
3779 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3780 Arg.getTemplateNameLoc());
3781
Douglas Gregor3a43fd62011-02-25 20:49:16 +00003782 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00003783 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00003784 // FIXME: the template-template arg was a DependentTemplateName,
3785 // so it was provided with a template keyword. However, its source
3786 // location is not stored in the template argument structure.
3787 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003788 ExprResult E = DependentScopeDeclRefExpr::Create(
3789 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
3790 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003791
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003792 // If we parsed the template argument as a pack expansion, create a
3793 // pack expansion expression.
3794 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003795 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00003796 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003797 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003798 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003799
Douglas Gregorda0fb532009-11-11 19:31:23 +00003800 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003801 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00003802 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003803 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003804
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003805 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003806 break;
3807 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003808
Douglas Gregorda0fb532009-11-11 19:31:23 +00003809 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00003810 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00003811 // therefore cannot be a non-type template argument.
3812 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3813 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003814
Douglas Gregorda0fb532009-11-11 19:31:23 +00003815 Diag(Param->getLocation(), diag::note_template_param_here);
3816 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003817
Douglas Gregorda0fb532009-11-11 19:31:23 +00003818 case TemplateArgument::Type: {
3819 // We have a non-type template parameter but the template
3820 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003821
Douglas Gregorda0fb532009-11-11 19:31:23 +00003822 // C++ [temp.arg]p2:
3823 // In a template-argument, an ambiguity between a type-id and
3824 // an expression is resolved to a type-id, regardless of the
3825 // form of the corresponding template-parameter.
3826 //
3827 // We warn specifically about this case, since it can be rather
3828 // confusing for users.
3829 QualType T = Arg.getArgument().getAsType();
3830 SourceRange SR = Arg.getSourceRange();
3831 if (T->isFunctionType())
3832 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3833 else
3834 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
3835 Diag(Param->getLocation(), diag::note_template_param_here);
3836 return true;
3837 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003838
Douglas Gregorda0fb532009-11-11 19:31:23 +00003839 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003840 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003841 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003842
Douglas Gregorda0fb532009-11-11 19:31:23 +00003843 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003844 }
3845
3846
Douglas Gregorda0fb532009-11-11 19:31:23 +00003847 // Check template template parameters.
3848 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003849
Douglas Gregorda0fb532009-11-11 19:31:23 +00003850 // Substitute into the template parameter list of the template
3851 // template parameter, since previously-supplied template arguments
3852 // may appear within the template template parameter.
3853 {
3854 // Set up a template instantiation context.
3855 LocalInstantiationScope Scope(*this);
3856 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003857 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003858 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003859 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003860 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003861
David Majnemer8b622692016-07-03 21:17:51 +00003862 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003863 TempParm = cast_or_null<TemplateTemplateParmDecl>(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003864 SubstDecl(TempParm, CurContext,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003865 MultiLevelTemplateArgumentList(TemplateArgs)));
3866 if (!TempParm)
3867 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003868 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003869
Douglas Gregorda0fb532009-11-11 19:31:23 +00003870 switch (Arg.getArgument().getKind()) {
3871 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003872 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003873
Douglas Gregorda0fb532009-11-11 19:31:23 +00003874 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003875 case TemplateArgument::TemplateExpansion:
Richard Smith1fde8ec2012-09-07 02:06:42 +00003876 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003877 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003878
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003879 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003880 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003881
Douglas Gregorda0fb532009-11-11 19:31:23 +00003882 case TemplateArgument::Expression:
3883 case TemplateArgument::Type:
3884 // We have a template template parameter but the template
3885 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003886 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003887 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003888 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003889
Douglas Gregorda0fb532009-11-11 19:31:23 +00003890 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00003891 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003892 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00003893 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00003894 case TemplateArgument::NullPtr:
3895 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003896
Douglas Gregorda0fb532009-11-11 19:31:23 +00003897 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003898 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003899 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003900
Douglas Gregorda0fb532009-11-11 19:31:23 +00003901 return false;
3902}
3903
Simon Pilgrim6905d222016-12-30 22:55:33 +00003904/// \brief Diagnose an arity mismatch in the
Douglas Gregor8e072612012-02-03 07:34:46 +00003905static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
3906 SourceLocation TemplateLoc,
3907 TemplateArgumentListInfo &TemplateArgs) {
3908 TemplateParameterList *Params = Template->getTemplateParameters();
3909 unsigned NumParams = Params->size();
3910 unsigned NumArgs = TemplateArgs.size();
3911
3912 SourceRange Range;
3913 if (NumArgs > NumParams)
Simon Pilgrim6905d222016-12-30 22:55:33 +00003914 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
Douglas Gregor8e072612012-02-03 07:34:46 +00003915 TemplateArgs.getRAngleLoc());
3916 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3917 << (NumArgs > NumParams)
3918 << (isa<ClassTemplateDecl>(Template)? 0 :
3919 isa<FunctionTemplateDecl>(Template)? 1 :
3920 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3921 << Template << Range;
3922 S.Diag(Template->getLocation(), diag::note_template_decl_here)
3923 << Params->getSourceRange();
3924 return true;
3925}
3926
Richard Smith1fde8ec2012-09-07 02:06:42 +00003927/// \brief Check whether the template parameter is a pack expansion, and if so,
3928/// determine the number of parameters produced by that expansion. For instance:
3929///
3930/// \code
3931/// template<typename ...Ts> struct A {
3932/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3933/// };
3934/// \endcode
3935///
3936/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3937/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00003938static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003939 if (NonTypeTemplateParmDecl *NTTP
3940 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3941 if (NTTP->isExpandedParameterPack())
3942 return NTTP->getNumExpansionTypes();
3943 }
3944
3945 if (TemplateTemplateParmDecl *TTP
3946 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3947 if (TTP->isExpandedParameterPack())
3948 return TTP->getNumExpansionTemplateParameters();
3949 }
3950
David Blaikie7a30dc52013-02-21 01:47:18 +00003951 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00003952}
3953
Richard Smith35c1df52015-06-17 20:16:32 +00003954/// Diagnose a missing template argument.
3955template<typename TemplateParmDecl>
3956static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
3957 TemplateDecl *TD,
3958 const TemplateParmDecl *D,
3959 TemplateArgumentListInfo &Args) {
3960 // Dig out the most recent declaration of the template parameter; there may be
3961 // declarations of the template that are more recent than TD.
3962 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
3963 ->getTemplateParameters()
3964 ->getParam(D->getIndex()));
3965
3966 // If there's a default argument that's not visible, diagnose that we're
3967 // missing a module import.
3968 llvm::SmallVector<Module*, 8> Modules;
3969 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
3970 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
3971 D->getDefaultArgumentLoc(), Modules,
3972 Sema::MissingImportKind::DefaultArgument,
Richard Smith6739a102016-05-05 00:56:12 +00003973 /*Recover*/true);
Richard Smith35c1df52015-06-17 20:16:32 +00003974 return true;
3975 }
3976
3977 // FIXME: If there's a more recent default argument that *is* visible,
3978 // diagnose that it was declared too late.
3979
3980 return diagnoseArityMismatch(S, TD, Loc, Args);
3981}
3982
Douglas Gregord32e0282009-02-09 23:23:08 +00003983/// \brief Check that the given template argument list is well-formed
3984/// for specializing the given template.
3985bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
3986 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003987 TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00003988 bool PartialTemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00003989 SmallVectorImpl<TemplateArgument> &Converted) {
Richard Trieu15b66532015-01-24 02:48:32 +00003990 // Make a copy of the template arguments for processing. Only make the
3991 // changes at the end when successful in matching the arguments to the
3992 // template.
3993 TemplateArgumentListInfo NewArgs = TemplateArgs;
3994
Douglas Gregord32e0282009-02-09 23:23:08 +00003995 TemplateParameterList *Params = Template->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00003996
Richard Trieu15b66532015-01-24 02:48:32 +00003997 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00003998
Mike Stump11289f42009-09-09 15:08:12 +00003999 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00004000 // [...] The type and form of each template-argument specified in
4001 // a template-id shall match the type and form specified for the
4002 // corresponding parameter declared by the template in its
4003 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00004004 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004005 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00004006 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00004007 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00004008 for (TemplateParameterList::iterator Param = Params->begin(),
4009 ParamEnd = Params->end();
4010 Param != ParamEnd; /* increment in loop */) {
4011 // If we have an expanded parameter pack, make sure we don't have too
4012 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00004013 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00004014 if (*Expansions == ArgumentPack.size()) {
4015 // We're done with this parameter pack. Pack up its arguments and add
4016 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00004017 Converted.push_back(
Benjamin Kramercce63472015-08-05 09:40:22 +00004018 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00004019 ArgumentPack.clear();
4020
Richard Smith1fde8ec2012-09-07 02:06:42 +00004021 // This argument is assigned to the next parameter.
4022 ++Param;
4023 continue;
4024 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
4025 // Not enough arguments for this parameter pack.
4026 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4027 << false
4028 << (isa<ClassTemplateDecl>(Template)? 0 :
4029 isa<FunctionTemplateDecl>(Template)? 1 :
4030 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
4031 << Template;
4032 Diag(Template->getLocation(), diag::note_template_decl_here)
4033 << Params->getSourceRange();
4034 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004035 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00004036 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004037
Richard Smith1fde8ec2012-09-07 02:06:42 +00004038 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00004039 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00004040 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004041 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004042 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00004043 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004044
Richard Smith96d71c32014-11-12 23:38:38 +00004045 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00004046 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00004047 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
4048 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00004049 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00004050 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00004051 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00004052 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00004053 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00004054 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00004055 Diag((*Param)->getLocation(), diag::note_template_param_here);
4056 return true;
4057 }
4058
Richard Smith1fde8ec2012-09-07 02:06:42 +00004059 // We're now done with this argument.
4060 ++ArgIdx;
4061
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004062 if ((*Param)->isTemplateParameterPack()) {
4063 // The template parameter was a template parameter pack, so take the
4064 // deduced argument and place it on the argument pack. Note that we
4065 // stay on the same template parameter so that we can deduce more
4066 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00004067 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004068 } else {
4069 // Move to the next template parameter.
4070 ++Param;
4071 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00004072
Richard Smith96d71c32014-11-12 23:38:38 +00004073 // If we just saw a pack expansion into a non-pack, then directly convert
4074 // the remaining arguments, because we don't know what parameters they'll
4075 // match up with.
4076 if (PackExpansionIntoNonPack) {
4077 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00004078 // If we were part way through filling in an expanded parameter pack,
4079 // fall back to just producing individual arguments.
4080 Converted.insert(Converted.end(),
4081 ArgumentPack.begin(), ArgumentPack.end());
4082 ArgumentPack.clear();
4083 }
4084
4085 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00004086 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00004087 ++ArgIdx;
4088 }
4089
Richard Smith1fde8ec2012-09-07 02:06:42 +00004090 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00004091 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00004092
Douglas Gregor84d49a22009-11-11 21:54:23 +00004093 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00004094 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004095
Douglas Gregor2f157c92011-06-03 02:59:40 +00004096 // If we're checking a partial template argument list, we're done.
4097 if (PartialTemplateArgs) {
4098 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
Benjamin Kramercce63472015-08-05 09:40:22 +00004099 Converted.push_back(
4100 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4101
Richard Smith1fde8ec2012-09-07 02:06:42 +00004102 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00004103 }
4104
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004105 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004106 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00004107 if ((*Param)->isTemplateParameterPack()) {
4108 assert(!getExpandedPackSize(*Param) &&
4109 "Should have dealt with this already");
4110
4111 // A non-expanded parameter pack before the end of the parameter list
4112 // only occurs for an ill-formed template parameter list, unless we've
4113 // got a partial argument list for a function template, so just bail out.
4114 if (Param + 1 != ParamEnd)
4115 return true;
4116
Benjamin Kramercce63472015-08-05 09:40:22 +00004117 Converted.push_back(
4118 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00004119 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00004120
4121 ++Param;
4122 continue;
4123 }
4124
Douglas Gregor8e072612012-02-03 07:34:46 +00004125 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00004126 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004127
Douglas Gregor84d49a22009-11-11 21:54:23 +00004128 // Retrieve the default template argument from the template
4129 // parameter. For each kind of template parameter, we substitute the
4130 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004131 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00004132 // the default argument.
4133 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004134 if (!hasVisibleDefaultArgument(TTP))
Richard Smith35c1df52015-06-17 20:16:32 +00004135 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
4136 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004137
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004138 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004139 Template,
4140 TemplateLoc,
4141 RAngleLoc,
4142 TTP,
4143 Converted);
4144 if (!ArgType)
4145 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004146
Douglas Gregor84d49a22009-11-11 21:54:23 +00004147 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
4148 ArgType);
4149 } else if (NonTypeTemplateParmDecl *NTTP
4150 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004151 if (!hasVisibleDefaultArgument(NTTP))
Richard Smith35c1df52015-06-17 20:16:32 +00004152 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
4153 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004154
John McCalldadc5752010-08-24 06:29:42 +00004155 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004156 TemplateLoc,
4157 RAngleLoc,
4158 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004159 Converted);
4160 if (E.isInvalid())
4161 return true;
4162
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004163 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00004164 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
4165 } else {
4166 TemplateTemplateParmDecl *TempParm
4167 = cast<TemplateTemplateParmDecl>(*Param);
4168
Richard Smith95d83952015-06-10 20:36:34 +00004169 if (!hasVisibleDefaultArgument(TempParm))
Richard Smith35c1df52015-06-17 20:16:32 +00004170 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
4171 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004172
Douglas Gregordf846d12011-03-02 18:46:51 +00004173 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00004174 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004175 TemplateLoc,
4176 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004177 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00004178 Converted,
4179 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004180 if (Name.isNull())
4181 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004182
Douglas Gregor9d802122011-03-02 17:09:35 +00004183 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
4184 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00004185 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004186
Douglas Gregor84d49a22009-11-11 21:54:23 +00004187 // Introduce an instantiation record that describes where we are using
Richard Smith54f18e82016-08-31 02:15:21 +00004188 // the default template argument. We're not actually instantiating a
4189 // template here, we just create this object to put a note into the
4190 // context stack.
Alp Tokerd4a72d52013-10-08 08:09:04 +00004191 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
4192 SourceRange(TemplateLoc, RAngleLoc));
4193 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004194 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004195
Douglas Gregor84d49a22009-11-11 21:54:23 +00004196 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00004197 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004198 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004199 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004200
Richard Trieu15b66532015-01-24 02:48:32 +00004201 // Core issue 150 (assumed resolution): if this is a template template
4202 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00004203 // template definition.
4204 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00004205 NewArgs.addArgument(Arg);
4206
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004207 // Move to the next template parameter and argument.
4208 ++Param;
4209 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00004210 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004211
Richard Smith07f79912014-06-06 16:00:50 +00004212 // If we're performing a partial argument substitution, allow any trailing
4213 // pack expansions; they might be empty. This can happen even if
4214 // PartialTemplateArgs is false (the list of arguments is complete but
4215 // still dependent).
4216 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
4217 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00004218 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
4219 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00004220 }
4221
Douglas Gregor8e072612012-02-03 07:34:46 +00004222 // If we have any leftover arguments, then there were too many arguments.
4223 // Complain and fail.
4224 if (ArgIdx < NumArgs)
Richard Trieu15b66532015-01-24 02:48:32 +00004225 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
4226
4227 // No problems found with the new argument list, propagate changes back
4228 // to caller.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00004229 TemplateArgs = std::move(NewArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004230
Richard Smith1fde8ec2012-09-07 02:06:42 +00004231 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00004232}
4233
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004234namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004235 class UnnamedLocalNoLinkageFinder
4236 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004237 {
4238 Sema &S;
4239 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004240
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004241 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004242
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004243 public:
4244 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
4245
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004246 bool Visit(QualType T) {
4247 return inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004248 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004249
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004250#define TYPE(Class, Parent) \
4251 bool Visit##Class##Type(const Class##Type *);
4252#define ABSTRACT_TYPE(Class, Parent) \
4253 bool Visit##Class##Type(const Class##Type *) { return false; }
4254#define NON_CANONICAL_TYPE(Class, Parent) \
4255 bool Visit##Class##Type(const Class##Type *) { return false; }
4256#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004257
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004258 bool VisitTagDecl(const TagDecl *Tag);
4259 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
4260 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004261} // end anonymous namespace
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004262
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004263bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004264 return false;
4265}
4266
4267bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
4268 return Visit(T->getElementType());
4269}
4270
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004271bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004272 return Visit(T->getPointeeType());
4273}
4274
4275bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004276 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004277 return Visit(T->getPointeeType());
4278}
4279
4280bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004281 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004282 return Visit(T->getPointeeType());
4283}
4284
4285bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004286 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004287 return Visit(T->getPointeeType());
4288}
4289
4290bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004291 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004292 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
4293}
4294
4295bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004296 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004297 return Visit(T->getElementType());
4298}
4299
4300bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004301 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004302 return Visit(T->getElementType());
4303}
4304
4305bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004306 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004307 return Visit(T->getElementType());
4308}
4309
4310bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004311 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004312 return Visit(T->getElementType());
4313}
4314
4315bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004316 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004317 return Visit(T->getElementType());
4318}
4319
4320bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
4321 return Visit(T->getElementType());
4322}
4323
4324bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
4325 return Visit(T->getElementType());
4326}
4327
4328bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
4329 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004330 for (const auto &A : T->param_types()) {
4331 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004332 return true;
4333 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004334
Alp Toker314cc812014-01-25 16:55:45 +00004335 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004336}
4337
4338bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
4339 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00004340 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004341}
4342
4343bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
4344 const UnresolvedUsingType*) {
4345 return false;
4346}
4347
4348bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
4349 return false;
4350}
4351
4352bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4353 return Visit(T->getUnderlyingType());
4354}
4355
4356bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4357 return false;
4358}
4359
Alexis Hunte852b102011-05-24 22:41:36 +00004360bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4361 const UnaryTransformType*) {
4362 return false;
4363}
4364
Richard Smith30482bc2011-02-20 03:19:35 +00004365bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4366 return Visit(T->getDeducedType());
4367}
4368
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004369bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4370 return VisitTagDecl(T->getDecl());
4371}
4372
4373bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4374 return VisitTagDecl(T->getDecl());
4375}
4376
4377bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4378 const TemplateTypeParmType*) {
4379 return false;
4380}
4381
Douglas Gregorada4b792011-01-14 02:55:32 +00004382bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4383 const SubstTemplateTypeParmPackType *) {
4384 return false;
4385}
4386
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004387bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4388 const TemplateSpecializationType*) {
4389 return false;
4390}
4391
4392bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4393 const InjectedClassNameType* T) {
4394 return VisitTagDecl(T->getDecl());
4395}
4396
4397bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4398 const DependentNameType* T) {
4399 return VisitNestedNameSpecifier(T->getQualifier());
4400}
4401
4402bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4403 const DependentTemplateSpecializationType* T) {
4404 return VisitNestedNameSpecifier(T->getQualifier());
4405}
4406
Douglas Gregord2fa7662010-12-20 02:24:11 +00004407bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4408 const PackExpansionType* T) {
4409 return Visit(T->getPattern());
4410}
4411
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004412bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4413 return false;
4414}
4415
4416bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4417 const ObjCInterfaceType *) {
4418 return false;
4419}
4420
4421bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4422 const ObjCObjectPointerType *) {
4423 return false;
4424}
4425
Eli Friedman0dfb8892011-10-06 23:00:33 +00004426bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4427 return Visit(T->getValueType());
4428}
4429
Xiuli Pan9c14e282016-01-09 12:53:17 +00004430bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
4431 return false;
4432}
4433
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004434bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4435 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004436 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004437 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004438 diag::warn_cxx98_compat_template_arg_local_type :
4439 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004440 << S.Context.getTypeDeclType(Tag) << SR;
4441 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004442 }
4443
John McCall5ea95772013-03-09 00:54:27 +00004444 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004445 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004446 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004447 diag::warn_cxx98_compat_template_arg_unnamed_type :
4448 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004449 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4450 return true;
4451 }
4452
4453 return false;
4454}
4455
4456bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4457 NestedNameSpecifier *NNS) {
4458 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4459 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004460
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004461 switch (NNS->getKind()) {
4462 case NestedNameSpecifier::Identifier:
4463 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004464 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004465 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004466 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004467 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004468
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004469 case NestedNameSpecifier::TypeSpec:
4470 case NestedNameSpecifier::TypeSpecWithTemplate:
4471 return Visit(QualType(NNS->getAsType(), 0));
4472 }
David Blaikie8a40f702012-01-17 06:56:22 +00004473 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004474}
4475
Douglas Gregord32e0282009-02-09 23:23:08 +00004476/// \brief Check a template argument against its corresponding
4477/// template type parameter.
4478///
4479/// This routine implements the semantics of C++ [temp.arg.type]. It
4480/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00004481bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00004482 TypeSourceInfo *ArgInfo) {
4483 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00004484 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00004485 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00004486
4487 if (Arg->isVariablyModifiedType()) {
4488 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004489 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004490 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00004491 }
4492
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004493 // C++03 [temp.arg.type]p2:
4494 // A local type, a type with no linkage, an unnamed type or a type
4495 // compounded from any of these types shall not be used as a
4496 // template-argument for a template type-parameter.
4497 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00004498 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004499 // a warning.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004500 bool NeedsCheck;
4501 if (LangOpts.CPlusPlus11)
4502 NeedsCheck =
4503 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_unnamed_type,
4504 SR.getBegin()) ||
4505 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_local_type,
4506 SR.getBegin());
4507 else
4508 NeedsCheck = Arg->hasUnnamedOrLocalType();
4509
4510 if (NeedsCheck) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004511 UnnamedLocalNoLinkageFinder Finder(*this, SR);
4512 (void)Finder.Visit(Context.getCanonicalType(Arg));
4513 }
4514
Douglas Gregord32e0282009-02-09 23:23:08 +00004515 return false;
4516}
4517
Douglas Gregor20fdef32012-04-10 17:08:25 +00004518enum NullPointerValueKind {
4519 NPV_NotNullPointer,
4520 NPV_NullPointer,
4521 NPV_Error
4522};
4523
4524/// \brief Determine whether the given template argument is a null pointer
4525/// value of the appropriate type.
4526static NullPointerValueKind
4527isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
4528 QualType ParamType, Expr *Arg) {
4529 if (Arg->isValueDependent() || Arg->isTypeDependent())
4530 return NPV_NotNullPointer;
David Majnemer69c3ddc2015-09-11 20:18:09 +00004531
Richard Smithdb0ac552015-12-18 22:40:25 +00004532 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
David Majnemerb54368c2015-09-11 20:55:29 +00004533 llvm_unreachable(
4534 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
David Majnemer69c3ddc2015-09-11 20:18:09 +00004535
David Majnemer5c734ad2014-08-14 00:49:23 +00004536 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004537 return NPV_NotNullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00004538
Douglas Gregor20fdef32012-04-10 17:08:25 +00004539 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00004540 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
4541 if (ArgRV.isInvalid())
4542 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004543 Arg = ArgRV.get();
Simon Pilgrim6905d222016-12-30 22:55:33 +00004544
Douglas Gregor20fdef32012-04-10 17:08:25 +00004545 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004546 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00004547 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00004548 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00004549 EvalResult.HasSideEffects) {
4550 SourceLocation DiagLoc = Arg->getExprLoc();
Simon Pilgrim6905d222016-12-30 22:55:33 +00004551
Douglas Gregor350880c2012-04-10 19:03:30 +00004552 // If our only note is the usual "invalid subexpression" note, just point
4553 // the caret at its location rather than producing an essentially
4554 // redundant note.
4555 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4556 diag::note_invalid_subexpr_in_const_expr) {
4557 DiagLoc = Notes[0].first;
4558 Notes.clear();
4559 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00004560
Douglas Gregor350880c2012-04-10 19:03:30 +00004561 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4562 << Arg->getType() << Arg->getSourceRange();
4563 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4564 S.Diag(Notes[I].first, Notes[I].second);
Simon Pilgrim6905d222016-12-30 22:55:33 +00004565
Douglas Gregor350880c2012-04-10 19:03:30 +00004566 S.Diag(Param->getLocation(), diag::note_template_param_here);
4567 return NPV_Error;
4568 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00004569
Douglas Gregor20fdef32012-04-10 17:08:25 +00004570 // C++11 [temp.arg.nontype]p1:
4571 // - an address constant expression of type std::nullptr_t
4572 if (Arg->getType()->isNullPtrType())
4573 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00004574
Douglas Gregor20fdef32012-04-10 17:08:25 +00004575 // - a constant expression that evaluates to a null pointer value (4.10); or
4576 // - a constant expression that evaluates to a null member pointer value
4577 // (4.11); or
4578 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4579 (EvalResult.Val.isMemberPointer() &&
4580 !EvalResult.Val.getMemberPointerDecl())) {
4581 // If our expression has an appropriate type, we've succeeded.
4582 bool ObjCLifetimeConversion;
4583 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4584 S.IsQualificationConversion(Arg->getType(), ParamType, false,
4585 ObjCLifetimeConversion))
4586 return NPV_NullPointer;
Simon Pilgrim6905d222016-12-30 22:55:33 +00004587
Douglas Gregor20fdef32012-04-10 17:08:25 +00004588 // The types didn't match, but we know we got a null pointer; complain,
4589 // then recover as if the types were correct.
4590 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4591 << Arg->getType() << ParamType << Arg->getSourceRange();
4592 S.Diag(Param->getLocation(), diag::note_template_param_here);
4593 return NPV_NullPointer;
4594 }
4595
4596 // If we don't have a null pointer value, but we do have a NULL pointer
4597 // constant, suggest a cast to the appropriate type.
4598 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
4599 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4600 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004601 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4602 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
4603 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00004604 S.Diag(Param->getLocation(), diag::note_template_param_here);
4605 return NPV_NullPointer;
4606 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00004607
Douglas Gregor20fdef32012-04-10 17:08:25 +00004608 // FIXME: If we ever want to support general, address-constant expressions
4609 // as non-type template arguments, we should return the ExprResult here to
4610 // be interpreted by the caller.
4611 return NPV_NotNullPointer;
4612}
4613
David Majnemer61c39a12013-08-23 05:39:39 +00004614/// \brief Checks whether the given template argument is compatible with its
4615/// template parameter.
4616static bool CheckTemplateArgumentIsCompatibleWithParameter(
4617 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4618 Expr *Arg, QualType ArgType) {
4619 bool ObjCLifetimeConversion;
4620 if (ParamType->isPointerType() &&
4621 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4622 S.IsQualificationConversion(ArgType, ParamType, false,
4623 ObjCLifetimeConversion)) {
4624 // For pointer-to-object types, qualification conversions are
4625 // permitted.
4626 } else {
4627 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4628 if (!ParamRef->getPointeeType()->isFunctionType()) {
4629 // C++ [temp.arg.nontype]p5b3:
4630 // For a non-type template-parameter of type reference to
4631 // object, no conversions apply. The type referred to by the
4632 // reference may be more cv-qualified than the (otherwise
4633 // identical) type of the template- argument. The
4634 // template-parameter is bound directly to the
4635 // template-argument, which shall be an lvalue.
4636
4637 // FIXME: Other qualifiers?
4638 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4639 unsigned ArgQuals = ArgType.getCVRQualifiers();
4640
4641 if ((ParamQuals | ArgQuals) != ParamQuals) {
4642 S.Diag(Arg->getLocStart(),
4643 diag::err_template_arg_ref_bind_ignores_quals)
4644 << ParamType << Arg->getType() << Arg->getSourceRange();
4645 S.Diag(Param->getLocation(), diag::note_template_param_here);
4646 return true;
4647 }
4648 }
4649 }
4650
4651 // At this point, the template argument refers to an object or
4652 // function with external linkage. We now need to check whether the
4653 // argument and parameter types are compatible.
4654 if (!S.Context.hasSameUnqualifiedType(ArgType,
4655 ParamType.getNonReferenceType())) {
4656 // We can't perform this conversion or binding.
4657 if (ParamType->isReferenceType())
4658 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4659 << ParamType << ArgIn->getType() << Arg->getSourceRange();
4660 else
4661 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4662 << ArgIn->getType() << ParamType << Arg->getSourceRange();
4663 S.Diag(Param->getLocation(), diag::note_template_param_here);
4664 return true;
4665 }
4666 }
4667
4668 return false;
4669}
4670
Douglas Gregorccb07762009-02-11 19:52:55 +00004671/// \brief Checks whether the given template argument is the address
4672/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004673static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00004674CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
4675 NonTypeTemplateParmDecl *Param,
4676 QualType ParamType,
4677 Expr *ArgIn,
4678 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004679 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004680 Expr *Arg = ArgIn;
4681 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00004682
Douglas Gregorb242683d2010-04-01 18:32:35 +00004683 bool AddressTaken = false;
4684 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00004685 if (S.getLangOpts().MicrosoftExt) {
4686 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4687 // dereference and address-of operators.
4688 Arg = Arg->IgnoreParenCasts();
4689
4690 bool ExtWarnMSTemplateArg = false;
4691 UnaryOperatorKind FirstOpKind;
4692 SourceLocation FirstOpLoc;
4693 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4694 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4695 if (UnOpKind == UO_Deref)
4696 ExtWarnMSTemplateArg = true;
4697 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4698 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4699 if (!AddrOpLoc.isValid()) {
4700 FirstOpKind = UnOpKind;
4701 FirstOpLoc = UnOp->getOperatorLoc();
4702 }
4703 } else
4704 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004705 }
David Majnemer61c39a12013-08-23 05:39:39 +00004706 if (FirstOpLoc.isValid()) {
4707 if (ExtWarnMSTemplateArg)
4708 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4709 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00004710
David Majnemer61c39a12013-08-23 05:39:39 +00004711 if (FirstOpKind == UO_AddrOf)
4712 AddressTaken = true;
4713 else if (Arg->getType()->isPointerType()) {
4714 // We cannot let pointers get dereferenced here, that is obviously not a
4715 // constant expression.
4716 assert(FirstOpKind == UO_Deref);
4717 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4718 << Arg->getSourceRange();
4719 }
4720 }
4721 } else {
4722 // See through any implicit casts we added to fix the type.
4723 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00004724
David Majnemer61c39a12013-08-23 05:39:39 +00004725 // C++ [temp.arg.nontype]p1:
4726 //
4727 // A template-argument for a non-type, non-template
4728 // template-parameter shall be one of: [...]
4729 //
4730 // -- the address of an object or function with external
4731 // linkage, including function templates and function
4732 // template-ids but excluding non-static class members,
4733 // expressed as & id-expression where the & is optional if
4734 // the name refers to a function or array, or if the
4735 // corresponding template-parameter is a reference; or
4736
4737 // In C++98/03 mode, give an extension warning on any extra parentheses.
4738 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4739 bool ExtraParens = false;
4740 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4741 if (!Invalid && !ExtraParens) {
4742 S.Diag(Arg->getLocStart(),
4743 S.getLangOpts().CPlusPlus11
4744 ? diag::warn_cxx98_compat_template_arg_extra_parens
4745 : diag::ext_template_arg_extra_parens)
4746 << Arg->getSourceRange();
4747 ExtraParens = true;
4748 }
4749
4750 Arg = Parens->getSubExpr();
4751 }
4752
4753 while (SubstNonTypeTemplateParmExpr *subst =
4754 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4755 Arg = subst->getReplacement()->IgnoreImpCasts();
4756
4757 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4758 if (UnOp->getOpcode() == UO_AddrOf) {
4759 Arg = UnOp->getSubExpr();
4760 AddressTaken = true;
4761 AddrOpLoc = UnOp->getOperatorLoc();
4762 }
4763 }
4764
4765 while (SubstNonTypeTemplateParmExpr *subst =
4766 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4767 Arg = subst->getReplacement()->IgnoreImpCasts();
4768 }
John McCall7c454bb2011-07-15 05:09:51 +00004769
David Majnemer07910d62014-06-26 07:48:46 +00004770 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4771 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
4772
4773 // If our parameter has pointer type, check for a null template value.
4774 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4775 NullPointerValueKind NPV;
4776 // dllimport'd entities aren't constant but are available inside of template
4777 // arguments.
4778 if (Entity && Entity->hasAttr<DLLImportAttr>())
4779 NPV = NPV_NotNullPointer;
4780 else
4781 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
4782 switch (NPV) {
4783 case NPV_NullPointer:
4784 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004785 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4786 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00004787 return false;
4788
4789 case NPV_Error:
4790 return true;
4791
4792 case NPV_NotNullPointer:
4793 break;
4794 }
4795 }
4796
Chandler Carruth724a8a12010-01-31 10:01:20 +00004797 // Stop checking the precise nature of the argument if it is value dependent,
4798 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00004799 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004800 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00004801 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004802 }
David Majnemer61c39a12013-08-23 05:39:39 +00004803
4804 if (isa<CXXUuidofExpr>(Arg)) {
4805 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4806 ArgIn, Arg, ArgType))
4807 return true;
4808
4809 Converted = TemplateArgument(ArgIn);
4810 return false;
4811 }
4812
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004813 if (!DRE) {
4814 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4815 << Arg->getSourceRange();
4816 S.Diag(Param->getLocation(), diag::note_template_param_here);
4817 return true;
4818 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00004819
Douglas Gregorccb07762009-02-11 19:52:55 +00004820 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00004821 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004822 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
David Majnemer6bedcfa2013-10-26 06:12:44 +00004823 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004824 S.Diag(Param->getLocation(), diag::note_template_param_here);
4825 return true;
4826 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004827
4828 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00004829 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004830 if (!Method->isStatic()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004831 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00004832 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004833 S.Diag(Param->getLocation(), diag::note_template_param_here);
4834 return true;
4835 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004836 }
Mike Stump11289f42009-09-09 15:08:12 +00004837
Richard Smith9380e0e2012-04-04 21:11:30 +00004838 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
4839 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00004840
Richard Smith9380e0e2012-04-04 21:11:30 +00004841 // A non-type template argument must refer to an object or function.
4842 if (!Func && !Var) {
4843 // We found something, but we don't know specifically what it is.
4844 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
4845 << Arg->getSourceRange();
4846 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4847 return true;
4848 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004849
Richard Smith9380e0e2012-04-04 21:11:30 +00004850 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00004851 if (Entity->getFormalLinkage() == InternalLinkage) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004852 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
Richard Smith9380e0e2012-04-04 21:11:30 +00004853 diag::warn_cxx98_compat_template_arg_object_internal :
4854 diag::ext_template_arg_object_internal)
4855 << !Func << Entity << Arg->getSourceRange();
4856 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4857 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00004858 } else if (!Entity->hasLinkage()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004859 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
4860 << !Func << Entity << Arg->getSourceRange();
4861 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4862 << !Func;
4863 return true;
4864 }
4865
4866 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004867 // If the template parameter has pointer type, the function decays.
4868 if (ParamType->isPointerType() && !AddressTaken)
4869 ArgType = S.Context.getPointerType(Func->getType());
4870 else if (AddressTaken && ParamType->isReferenceType()) {
4871 // If we originally had an address-of operator, but the
4872 // parameter has reference type, complain and (if things look
4873 // like they will work) drop the address-of operator.
4874 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
4875 ParamType.getNonReferenceType())) {
4876 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4877 << ParamType;
4878 S.Diag(Param->getLocation(), diag::note_template_param_here);
4879 return true;
4880 }
4881
4882 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4883 << ParamType
4884 << FixItHint::CreateRemoval(AddrOpLoc);
4885 S.Diag(Param->getLocation(), diag::note_template_param_here);
4886
4887 ArgType = Func->getType();
4888 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004889 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004890 // A value of reference type is not an object.
4891 if (Var->getType()->isReferenceType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004892 S.Diag(Arg->getLocStart(),
Douglas Gregorb242683d2010-04-01 18:32:35 +00004893 diag::err_template_arg_reference_var)
4894 << Var->getType() << Arg->getSourceRange();
4895 S.Diag(Param->getLocation(), diag::note_template_param_here);
4896 return true;
4897 }
4898
Richard Smith9380e0e2012-04-04 21:11:30 +00004899 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00004900 if (Var->getTLSKind()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004901 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
4902 << Arg->getSourceRange();
4903 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
4904 return true;
4905 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00004906
4907 // If the template parameter has pointer type, we must have taken
4908 // the address of this object.
4909 if (ParamType->isReferenceType()) {
4910 if (AddressTaken) {
4911 // If we originally had an address-of operator, but the
4912 // parameter has reference type, complain and (if things look
4913 // like they will work) drop the address-of operator.
4914 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
4915 ParamType.getNonReferenceType())) {
4916 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4917 << ParamType;
4918 S.Diag(Param->getLocation(), diag::note_template_param_here);
4919 return true;
4920 }
4921
4922 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4923 << ParamType
4924 << FixItHint::CreateRemoval(AddrOpLoc);
4925 S.Diag(Param->getLocation(), diag::note_template_param_here);
4926
4927 ArgType = Var->getType();
4928 }
4929 } else if (!AddressTaken && ParamType->isPointerType()) {
4930 if (Var->getType()->isArrayType()) {
4931 // Array-to-pointer decay.
4932 ArgType = S.Context.getArrayDecayedType(Var->getType());
4933 } else {
4934 // If the template parameter has pointer type but the address of
4935 // this object was not taken, complain and (possibly) recover by
4936 // taking the address of the entity.
4937 ArgType = S.Context.getPointerType(Var->getType());
4938 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
4939 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4940 << ParamType;
4941 S.Diag(Param->getLocation(), diag::note_template_param_here);
4942 return true;
4943 }
4944
4945 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4946 << ParamType
4947 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
4948
4949 S.Diag(Param->getLocation(), diag::note_template_param_here);
4950 }
4951 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004952 }
Mike Stump11289f42009-09-09 15:08:12 +00004953
David Majnemer61c39a12013-08-23 05:39:39 +00004954 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
4955 Arg, ArgType))
4956 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004957
4958 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00004959 Converted =
4960 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Nick Lewycky45b50522013-02-02 00:25:55 +00004961 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00004962 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004963}
4964
4965/// \brief Checks whether the given template argument is a pointer to
4966/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004967static bool CheckTemplateArgumentPointerToMember(Sema &S,
4968 NonTypeTemplateParmDecl *Param,
4969 QualType ParamType,
4970 Expr *&ResultArg,
4971 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004972 bool Invalid = false;
4973
Douglas Gregor20fdef32012-04-10 17:08:25 +00004974 // Check for a null pointer value.
4975 Expr *Arg = ResultArg;
4976 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4977 case NPV_Error:
4978 return true;
4979 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00004980 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004981 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4982 /*isNullPtr*/true);
Douglas Gregor20fdef32012-04-10 17:08:25 +00004983 return false;
4984 case NPV_NotNullPointer:
4985 break;
4986 }
4987
4988 bool ObjCLifetimeConversion;
4989 if (S.IsQualificationConversion(Arg->getType(),
4990 ParamType.getNonReferenceType(),
4991 false, ObjCLifetimeConversion)) {
4992 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004993 Arg->getValueKind()).get();
Douglas Gregor20fdef32012-04-10 17:08:25 +00004994 ResultArg = Arg;
4995 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
4996 ParamType.getNonReferenceType())) {
4997 // We can't perform this conversion.
4998 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4999 << Arg->getType() << ParamType << Arg->getSourceRange();
5000 S.Diag(Param->getLocation(), diag::note_template_param_here);
5001 return true;
5002 }
5003
Douglas Gregorccb07762009-02-11 19:52:55 +00005004 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00005005 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00005006 Arg = Cast->getSubExpr();
5007
5008 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00005009 //
Douglas Gregorccb07762009-02-11 19:52:55 +00005010 // A template-argument for a non-type, non-template
5011 // template-parameter shall be one of: [...]
5012 //
5013 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00005014 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00005015
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00005016 // In C++98/03 mode, give an extension warning on any extra parentheses.
5017 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5018 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00005019 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00005020 if (!Invalid && !ExtraParens) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00005021 S.Diag(Arg->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005022 S.getLangOpts().CPlusPlus11 ?
Douglas Gregor20fdef32012-04-10 17:08:25 +00005023 diag::warn_cxx98_compat_template_arg_extra_parens :
5024 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00005025 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00005026 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00005027 }
5028
5029 Arg = Parens->getSubExpr();
5030 }
5031
John McCall7c454bb2011-07-15 05:09:51 +00005032 while (SubstNonTypeTemplateParmExpr *subst =
5033 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5034 Arg = subst->getReplacement()->IgnoreImpCasts();
5035
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005036 // A pointer-to-member constant written &Class::member.
5037 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00005038 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005039 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
5040 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00005041 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005042 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005043 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005044 // A constant of pointer-to-member type.
5045 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
5046 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
5047 if (VD->getType()->isMemberPointerType()) {
David Majnemercd053cd2013-12-10 00:40:58 +00005048 if (isa<NonTypeTemplateParmDecl>(VD)) {
Eli Friedmanb826a002012-09-26 02:36:12 +00005049 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005050 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00005051 } else {
5052 VD = cast<ValueDecl>(VD->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00005053 Converted = TemplateArgument(VD, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00005054 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005055 return Invalid;
5056 }
5057 }
5058 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005059
Craig Topperc3ec1492014-05-26 06:22:03 +00005060 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00005061 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005062
Douglas Gregorccb07762009-02-11 19:52:55 +00005063 if (!DRE)
Douglas Gregor20fdef32012-04-10 17:08:25 +00005064 return S.Diag(Arg->getLocStart(),
5065 diag::err_template_arg_not_pointer_to_member_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00005066 << Arg->getSourceRange();
5067
David Majnemer3ac84e62013-10-22 21:56:38 +00005068 if (isa<FieldDecl>(DRE->getDecl()) ||
5069 isa<IndirectFieldDecl>(DRE->getDecl()) ||
5070 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005071 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00005072 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00005073 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
5074 "Only non-static member pointers can make it here");
5075
5076 // Okay: this is the address of a non-static member, and therefore
5077 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00005078 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005079 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00005080 } else {
5081 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00005082 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00005083 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005084 return Invalid;
5085 }
5086
5087 // We found something else, but we don't know specifically what it is.
Douglas Gregor20fdef32012-04-10 17:08:25 +00005088 S.Diag(Arg->getLocStart(),
5089 diag::err_template_arg_not_pointer_to_member_form)
5090 << Arg->getSourceRange();
5091 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00005092 return true;
5093}
5094
Douglas Gregord32e0282009-02-09 23:23:08 +00005095/// \brief Check a template argument against its corresponding
5096/// non-type template parameter.
5097///
Douglas Gregor463421d2009-03-03 04:44:36 +00005098/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00005099/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00005100/// returns the converted template argument. \p ParamType is the
5101/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00005102ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00005103 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00005104 TemplateArgument &Converted,
5105 CheckTemplateArgumentKind CTAK) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005106 SourceLocation StartLoc = Arg->getLocStart();
Douglas Gregorc40290e2009-03-09 23:48:35 +00005107
Richard Smith5f274382016-09-28 23:55:27 +00005108 // If the parameter type somehow involves auto, deduce the type now.
5109 if (getLangOpts().CPlusPlus1z && ParamType->isUndeducedType()) {
Richard Smith87d263e2016-12-25 08:05:23 +00005110 // When checking a deduced template argument, deduce from its type even if
5111 // the type is dependent, in order to check the types of non-type template
5112 // arguments line up properly in partial ordering.
5113 Optional<unsigned> Depth;
5114 if (CTAK != CTAK_Specified)
5115 Depth = Param->getDepth() + 1;
Richard Smith5f274382016-09-28 23:55:27 +00005116 if (DeduceAutoType(
5117 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
Richard Smith87d263e2016-12-25 08:05:23 +00005118 Arg, ParamType, Depth) == DAR_Failed) {
Richard Smith5f274382016-09-28 23:55:27 +00005119 Diag(Arg->getExprLoc(),
5120 diag::err_non_type_template_parm_type_deduction_failure)
5121 << Param->getDeclName() << Param->getType() << Arg->getType()
5122 << Arg->getSourceRange();
5123 Diag(Param->getLocation(), diag::note_template_param_here);
5124 return ExprError();
5125 }
5126 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
5127 // an error. The error message normally references the parameter
5128 // declaration, but here we'll pass the argument location because that's
5129 // where the parameter type is deduced.
5130 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
5131 if (ParamType.isNull()) {
5132 Diag(Param->getLocation(), diag::note_template_param_here);
5133 return ExprError();
5134 }
5135 }
5136
Richard Smithd663fdd2014-12-17 20:42:37 +00005137 // We should have already dropped all cv-qualifiers by now.
5138 assert(!ParamType.hasQualifiers() &&
5139 "non-type template parameter type cannot be qualified");
5140
5141 if (CTAK == CTAK_Deduced &&
Richard Smithd92eddf2016-12-27 06:14:37 +00005142 !Context.hasSameType(ParamType.getNonLValueExprType(Context),
Richard Smith0e617ec2016-12-27 07:56:27 +00005143 Arg->getType())) {
Richard Smith4f9b3f42016-12-26 22:28:29 +00005144 // C++ [temp.deduct.type]p17: (DR1770)
5145 // If P has a form that contains <i>, and if the type of i differs from
5146 // the type of the corresponding template parameter of the template named
5147 // by the enclosing simple-template-id, deduction fails.
5148 //
5149 // Note that CTAK will be CTAK_DeducedFromArrayBound if the form was [i]
5150 // rather than <i>.
Richard Smithd92eddf2016-12-27 06:14:37 +00005151 //
5152 // FIXME: We interpret the 'i' here as referring to the expression
5153 // denoting the non-type template parameter rather than the parameter
5154 // itself, and so strip off references before comparing types. It's
5155 // not clear how this is supposed to work for references.
Richard Smithd663fdd2014-12-17 20:42:37 +00005156 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
Richard Smith0e617ec2016-12-27 07:56:27 +00005157 << Arg->getType()
Richard Smithd663fdd2014-12-17 20:42:37 +00005158 << ParamType.getUnqualifiedType();
5159 Diag(Param->getLocation(), diag::note_template_param_here);
5160 return ExprError();
5161 }
5162
Richard Smith87d263e2016-12-25 08:05:23 +00005163 // If either the parameter has a dependent type or the argument is
5164 // type-dependent, there's nothing we can check now.
5165 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
5166 // FIXME: Produce a cloned, canonical expression?
5167 Converted = TemplateArgument(Arg);
5168 return Arg;
5169 }
5170
Richard Smith410cc892014-11-26 03:26:53 +00005171 if (getLangOpts().CPlusPlus1z) {
Richard Smith410cc892014-11-26 03:26:53 +00005172 // C++1z [temp.arg.nontype]p1:
5173 // A template-argument for a non-type template parameter shall be
5174 // a converted constant expression of the type of the template-parameter.
5175 APValue Value;
5176 ExprResult ArgResult = CheckConvertedConstantExpression(
5177 Arg, ParamType, Value, CCEK_TemplateArg);
5178 if (ArgResult.isInvalid())
5179 return ExprError();
5180
Richard Smith52e624f2016-12-21 21:42:57 +00005181 // For a value-dependent argument, CheckConvertedConstantExpression is
5182 // permitted (and expected) to be unable to determine a value.
5183 if (ArgResult.get()->isValueDependent()) {
Richard Smith01bfa682016-12-27 02:02:09 +00005184 Converted = TemplateArgument(ArgResult.get());
5185 return ArgResult;
Richard Smith52e624f2016-12-21 21:42:57 +00005186 }
5187
Richard Smithd663fdd2014-12-17 20:42:37 +00005188 QualType CanonParamType = Context.getCanonicalType(ParamType);
5189
Richard Smith410cc892014-11-26 03:26:53 +00005190 // Convert the APValue to a TemplateArgument.
5191 switch (Value.getKind()) {
5192 case APValue::Uninitialized:
5193 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00005194 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005195 break;
5196 case APValue::Int:
5197 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00005198 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00005199 break;
5200 case APValue::MemberPointer: {
5201 assert(ParamType->isMemberPointerType());
5202
5203 // FIXME: We need TemplateArgument representation and mangling for these.
5204 if (!Value.getMemberPointerPath().empty()) {
5205 Diag(Arg->getLocStart(),
5206 diag::err_template_arg_member_ptr_base_derived_not_supported)
5207 << Value.getMemberPointerDecl() << ParamType
5208 << Arg->getSourceRange();
5209 return ExprError();
5210 }
5211
5212 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00005213 Converted = VD ? TemplateArgument(VD, CanonParamType)
5214 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005215 break;
5216 }
5217 case APValue::LValue: {
5218 // For a non-type template-parameter of pointer or reference type,
5219 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00005220 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
5221 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00005222 // -- a temporary object
5223 // -- a string literal
5224 // -- the result of a typeid expression, or
5225 // -- a predefind __func__ variable
5226 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
5227 if (isa<CXXUuidofExpr>(E)) {
5228 Converted = TemplateArgument(const_cast<Expr*>(E));
5229 break;
5230 }
5231 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5232 << Arg->getSourceRange();
5233 return ExprError();
5234 }
5235 auto *VD = const_cast<ValueDecl *>(
5236 Value.getLValueBase().dyn_cast<const ValueDecl *>());
5237 // -- a subobject
5238 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
5239 VD && VD->getType()->isArrayType() &&
5240 Value.getLValuePath()[0].ArrayIndex == 0 &&
5241 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
5242 // Per defect report (no number yet):
5243 // ... other than a pointer to the first element of a complete array
5244 // object.
5245 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
5246 Value.isLValueOnePastTheEnd()) {
5247 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
5248 << Value.getAsString(Context, ParamType);
5249 return ExprError();
5250 }
Richard Smithd663fdd2014-12-17 20:42:37 +00005251 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00005252 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00005253 assert((!VD || !ParamType->isNullPtrType()) &&
5254 "non-null value of type nullptr_t?");
5255 Converted = VD ? TemplateArgument(VD, CanonParamType)
5256 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005257 break;
5258 }
5259 case APValue::AddrLabelDiff:
5260 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
5261 case APValue::Float:
5262 case APValue::ComplexInt:
5263 case APValue::ComplexFloat:
5264 case APValue::Vector:
5265 case APValue::Array:
5266 case APValue::Struct:
5267 case APValue::Union:
5268 llvm_unreachable("invalid kind for template argument");
5269 }
5270
5271 return ArgResult.get();
5272 }
5273
Douglas Gregor86560402009-02-10 23:36:10 +00005274 // C++ [temp.arg.nontype]p5:
5275 // The following conversions are performed on each expression used
5276 // as a non-type template-argument. If a non-type
5277 // template-argument cannot be converted to the type of the
5278 // corresponding template-parameter then the program is
5279 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00005280 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00005281 // C++11:
5282 // -- for a non-type template-parameter of integral or
5283 // enumeration type, conversions permitted in a converted
5284 // constant expression are applied.
5285 //
5286 // C++98:
5287 // -- for a non-type template-parameter of integral or
5288 // enumeration type, integral promotions (4.5) and integral
5289 // conversions (4.7) are applied.
5290
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005291 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00005292 // C++ [temp.arg.nontype]p1:
5293 // A template-argument for a non-type, non-template template-parameter
5294 // shall be one of:
5295 //
5296 // -- for a non-type template-parameter of integral or enumeration
5297 // type, a converted constant expression of the type of the
5298 // template-parameter; or
5299 llvm::APSInt Value;
5300 ExprResult ArgResult =
5301 CheckConvertedConstantExpression(Arg, ParamType, Value,
5302 CCEK_TemplateArg);
5303 if (ArgResult.isInvalid())
5304 return ExprError();
5305
Richard Smith01bfa682016-12-27 02:02:09 +00005306 // We can't check arbitrary value-dependent arguments.
5307 if (ArgResult.get()->isValueDependent()) {
5308 Converted = TemplateArgument(ArgResult.get());
5309 return ArgResult;
5310 }
5311
Richard Smithf8379a02012-01-18 23:55:52 +00005312 // Widen the argument value to sizeof(parameter type). This is almost
5313 // always a no-op, except when the parameter type is bool. In
5314 // that case, this may extend the argument from 1 bit to 8 bits.
5315 QualType IntegerType = ParamType;
5316 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5317 IntegerType = Enum->getDecl()->getIntegerType();
5318 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
5319
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005320 Converted = TemplateArgument(Context, Value,
5321 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00005322 return ArgResult;
5323 }
5324
Richard Smith08b12f12011-10-27 22:11:44 +00005325 ExprResult ArgResult = DefaultLvalueConversion(Arg);
5326 if (ArgResult.isInvalid())
5327 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005328 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00005329
5330 QualType ArgType = Arg->getType();
5331
Douglas Gregor86560402009-02-10 23:36:10 +00005332 // C++ [temp.arg.nontype]p1:
5333 // A template-argument for a non-type, non-template
5334 // template-parameter shall be one of:
5335 //
5336 // -- an integral constant-expression of integral or enumeration
5337 // type; or
5338 // -- the name of a non-type template-parameter; or
5339 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005340 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00005341 if (!ArgType->isIntegralOrEnumerationType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005342 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005343 diag::err_template_arg_not_integral_or_enumeral)
5344 << ArgType << Arg->getSourceRange();
5345 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005346 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00005347 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005348 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
5349 QualType T;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005350
Douglas Gregore2b37442012-05-04 22:38:52 +00005351 public:
5352 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00005353
5354 void diagnoseNotICE(Sema &S, SourceLocation Loc,
5355 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00005356 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
5357 }
5358 } Diagnoser(ArgType);
5359
5360 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005361 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00005362 if (!Arg)
5363 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005364 }
5365
Richard Smithd663fdd2014-12-17 20:42:37 +00005366 // From here on out, all we care about is the unqualified form
5367 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005368 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00005369
5370 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00005371 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00005372 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00005373 } else if (ParamType->isBooleanType()) {
5374 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005375 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005376 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
5377 !ParamType->isEnumeralType()) {
5378 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005379 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005380 } else {
5381 // We can't perform this conversion.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005382 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005383 diag::err_template_arg_not_convertible)
Richard Smithd663fdd2014-12-17 20:42:37 +00005384 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00005385 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005386 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005387 }
5388
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005389 // Add the value of this argument to the list of converted
5390 // arguments. We use the bitwidth and signedness of the template
5391 // parameter.
5392 if (Arg->isValueDependent()) {
5393 // The argument is value-dependent. Create a new
5394 // TemplateArgument with the converted expression.
5395 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005396 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005397 }
5398
Douglas Gregor52aba872009-03-14 00:20:21 +00005399 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00005400 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00005401 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00005402
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005403 if (ParamType->isBooleanType()) {
5404 // Value must be zero or one.
5405 Value = Value != 0;
5406 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5407 if (Value.getBitWidth() != AllowedBits)
5408 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005409 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005410 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005411 llvm::APSInt OldValue = Value;
Simon Pilgrim6905d222016-12-30 22:55:33 +00005412
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005413 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005414 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005415 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005416 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005417 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005418 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Simon Pilgrim6905d222016-12-30 22:55:33 +00005419
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005420 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005421 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005422 && (OldValue.isSigned() && OldValue.isNegative())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005423 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005424 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5425 << Arg->getSourceRange();
5426 Diag(Param->getLocation(), diag::note_template_param_here);
5427 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005428
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005429 // Complain if we overflowed the template parameter's type.
5430 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005431 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005432 RequiredBits = OldValue.getActiveBits();
5433 else if (OldValue.isUnsigned())
5434 RequiredBits = OldValue.getActiveBits() + 1;
5435 else
5436 RequiredBits = OldValue.getMinSignedBits();
5437 if (RequiredBits > AllowedBits) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005438 Diag(Arg->getLocStart(),
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005439 diag::warn_template_arg_too_large)
5440 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5441 << Arg->getSourceRange();
5442 Diag(Param->getLocation(), diag::note_template_param_here);
5443 }
Douglas Gregor52aba872009-03-14 00:20:21 +00005444 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005445
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005446 Converted = TemplateArgument(Context, Value,
Simon Pilgrim6905d222016-12-30 22:55:33 +00005447 ParamType->isEnumeralType()
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00005448 ? Context.getCanonicalType(ParamType)
5449 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005450 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00005451 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005452
Richard Smith08b12f12011-10-27 22:11:44 +00005453 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00005454 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
5455
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005456 // Handle pointer-to-function, reference-to-function, and
5457 // pointer-to-member-function all in (roughly) the same way.
5458 if (// -- For a non-type template-parameter of type pointer to
5459 // function, only the function-to-pointer conversion (4.3) is
5460 // applied. If the template-argument represents a set of
5461 // overloaded functions (or a pointer to such), the matching
5462 // function is selected from the set (13.4).
5463 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005464 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005465 // -- For a non-type template-parameter of type reference to
5466 // function, no conversions apply. If the template-argument
5467 // represents a set of overloaded functions, the matching
5468 // function is selected from the set (13.4).
5469 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005470 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005471 // -- For a non-type template-parameter of type pointer to
5472 // member function, no conversions apply. If the
5473 // template-argument represents a set of overloaded member
5474 // functions, the matching member function is selected from
5475 // the set (13.4).
5476 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005477 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005478 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005479
Douglas Gregor064fdb22010-04-14 23:11:21 +00005480 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005481 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00005482 true,
5483 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005484 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005485 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005486
5487 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5488 ArgType = Arg->getType();
5489 } else
John Wiegley01296292011-04-08 18:41:53 +00005490 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005491 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005492
John Wiegley01296292011-04-08 18:41:53 +00005493 if (!ParamType->isMemberPointerType()) {
5494 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5495 ParamType,
5496 Arg, Converted))
5497 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005498 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00005499 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00005500
Douglas Gregor20fdef32012-04-10 17:08:25 +00005501 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5502 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005503 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005504 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005505 }
5506
Chris Lattner696197c2009-02-20 21:37:53 +00005507 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005508 // -- for a non-type template-parameter of type pointer to
5509 // object, qualification conversions (4.4) and the
5510 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00005511 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00005512 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005513 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005514
John Wiegley01296292011-04-08 18:41:53 +00005515 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5516 ParamType,
5517 Arg, Converted))
5518 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005519 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00005520 }
Mike Stump11289f42009-09-09 15:08:12 +00005521
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005522 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005523 // -- For a non-type template-parameter of type reference to
5524 // object, no conversions apply. The type referred to by the
5525 // reference may be more cv-qualified than the (otherwise
5526 // identical) type of the template-argument. The
5527 // template-parameter is bound directly to the
5528 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00005529 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005530 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005531
Douglas Gregor064fdb22010-04-14 23:11:21 +00005532 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005533 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
5534 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00005535 true,
5536 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005537 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005538 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005539
5540 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5541 ArgType = Arg->getType();
5542 } else
John Wiegley01296292011-04-08 18:41:53 +00005543 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005544 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005545
John Wiegley01296292011-04-08 18:41:53 +00005546 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5547 ParamType,
5548 Arg, Converted))
5549 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005550 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005551 }
Douglas Gregor0e558532009-02-11 16:16:59 +00005552
Douglas Gregor20fdef32012-04-10 17:08:25 +00005553 // Deal with parameters of type std::nullptr_t.
5554 if (ParamType->isNullPtrType()) {
5555 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5556 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005557 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005558 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005559
Douglas Gregor20fdef32012-04-10 17:08:25 +00005560 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
5561 case NPV_NotNullPointer:
5562 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
5563 << Arg->getType() << ParamType;
5564 Diag(Param->getLocation(), diag::note_template_param_here);
5565 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005566
Douglas Gregor20fdef32012-04-10 17:08:25 +00005567 case NPV_Error:
5568 return ExprError();
Simon Pilgrim6905d222016-12-30 22:55:33 +00005569
Douglas Gregor20fdef32012-04-10 17:08:25 +00005570 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00005571 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005572 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
5573 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005574 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005575 }
5576 }
5577
Douglas Gregor0e558532009-02-11 16:16:59 +00005578 // -- For a non-type template-parameter of type pointer to data
5579 // member, qualification conversions (4.4) are applied.
5580 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
5581
Douglas Gregor20fdef32012-04-10 17:08:25 +00005582 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5583 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005584 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005585 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00005586}
5587
5588/// \brief Check a template argument against its corresponding
5589/// template template parameter.
5590///
5591/// This routine implements the semantics of C++ [temp.arg.template].
5592/// It returns true if an error occurred, and false otherwise.
5593bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00005594 TemplateArgumentLoc &Arg,
Richard Smith1fde8ec2012-09-07 02:06:42 +00005595 unsigned ArgumentPackIndex) {
Eli Friedmanb826a002012-09-26 02:36:12 +00005596 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005597 TemplateDecl *Template = Name.getAsTemplateDecl();
5598 if (!Template) {
5599 // Any dependent template name is fine.
5600 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5601 return false;
5602 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00005603
Richard Smith3f1b5d02011-05-05 21:57:07 +00005604 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00005605 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00005606 // the name of a class template or an alias template, expressed as an
5607 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00005608 // primary class templates are considered when matching the
5609 // template template argument with the corresponding parameter;
5610 // partial specializations are not considered even if their
5611 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00005612 //
5613 // Note that we also allow template template parameters here, which
5614 // will happen when we are dealing with, e.g., class template
5615 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00005616 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00005617 !isa<TemplateTemplateParmDecl>(Template) &&
David Majnemerc2406d42016-07-11 17:09:56 +00005618 !isa<TypeAliasTemplateDecl>(Template) &&
5619 !isa<BuiltinTemplateDecl>(Template)) {
5620 assert(isa<FunctionTemplateDecl>(Template) &&
5621 "Only function templates are possible here");
Faisal Valib8b04f82016-03-26 20:46:45 +00005622 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
David Majnemerc2406d42016-07-11 17:09:56 +00005623 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
5624 << Template;
Douglas Gregor85e0f662009-02-10 00:24:35 +00005625 }
5626
Richard Smith1fde8ec2012-09-07 02:06:42 +00005627 TemplateParameterList *Params = Param->getTemplateParameters();
5628 if (Param->isExpandedParameterPack())
5629 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5630
Douglas Gregor85e0f662009-02-10 00:24:35 +00005631 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00005632 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005633 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005634 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005635 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00005636}
5637
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005638/// \brief Given a non-type template argument that refers to a
5639/// declaration and the type of its corresponding non-type template
5640/// parameter, produce an expression that properly refers to that
5641/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005642ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005643Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5644 QualType ParamType,
5645 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00005646 // C++ [temp.param]p8:
5647 //
5648 // A non-type template-parameter of type "array of T" or
5649 // "function returning T" is adjusted to be of type "pointer to
5650 // T" or "pointer to function returning T", respectively.
5651 if (ParamType->isArrayType())
5652 ParamType = Context.getArrayDecayedType(ParamType);
5653 else if (ParamType->isFunctionType())
5654 ParamType = Context.getPointerType(ParamType);
5655
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005656 // For a NULL non-type template argument, return nullptr casted to the
5657 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00005658 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005659 return ImpCastExprToType(
5660 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
5661 ParamType,
5662 ParamType->getAs<MemberPointerType>()
5663 ? CK_NullToMemberPointer
5664 : CK_NullToPointer);
5665 }
Eli Friedmanb826a002012-09-26 02:36:12 +00005666 assert(Arg.getKind() == TemplateArgument::Declaration &&
5667 "Only declaration template arguments permitted here");
5668
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005669 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5670
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005671 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00005672 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5673 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005674 // If the value is a class member, we might have a pointer-to-member.
5675 // Determine whether the non-type template template parameter is of
5676 // pointer-to-member type. If so, we need to build an appropriate
5677 // expression for a pointer-to-member, since a "normal" DeclRefExpr
5678 // would refer to the member itself.
5679 if (ParamType->isMemberPointerType()) {
5680 QualType ClassType
5681 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5682 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00005683 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00005684 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005685 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00005686 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00005687
5688 // The actual value-ness of this is unimportant, but for
5689 // internal consistency's sake, references to instance methods
5690 // are r-values.
5691 ExprValueKind VK = VK_LValue;
5692 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5693 VK = VK_RValue;
5694
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005695 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00005696 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00005697 VK,
John McCall7decc9e2010-11-18 06:31:45 +00005698 Loc,
5699 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005700 if (RefExpr.isInvalid())
5701 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005702
John McCalle3027922010-08-25 11:45:40 +00005703 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005704
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005705 // We might need to perform a trailing qualification conversion, since
5706 // the element type on the parameter could be more qualified than the
5707 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00005708 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005709 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00005710 ParamType.getUnqualifiedType(), false,
5711 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005712 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005713
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005714 assert(!RefExpr.isInvalid() &&
5715 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005716 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005717 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005718 }
5719 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005720
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005721 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005722
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005723 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005724 // When the non-type template parameter is a pointer, take the
5725 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00005726 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005727 if (RefExpr.isInvalid())
5728 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005729
5730 if (T->isFunctionType() || T->isArrayType()) {
5731 // Decay functions and arrays.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005732 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00005733 if (RefExpr.isInvalid())
5734 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005735
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005736 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005737 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005738
Douglas Gregorb242683d2010-04-01 18:32:35 +00005739 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00005740 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005741 }
5742
John McCall7decc9e2010-11-18 06:31:45 +00005743 ExprValueKind VK = VK_RValue;
5744
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005745 // If the non-type template parameter has reference type, qualify the
5746 // resulting declaration reference with the extra qualifiers on the
5747 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00005748 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5749 VK = VK_LValue;
5750 T = Context.getQualifiedType(T,
5751 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005752 } else if (isa<FunctionDecl>(VD)) {
5753 // References to functions are always lvalues.
5754 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00005755 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005756
John McCall7decc9e2010-11-18 06:31:45 +00005757 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005758}
5759
5760/// \brief Construct a new expression that refers to the given
5761/// integral template argument with the given source-location
5762/// information.
5763///
5764/// This routine takes care of the mapping from an integral template
5765/// argument (which may have any integral type) to the appropriate
5766/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005767ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005768Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5769 SourceLocation Loc) {
5770 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00005771 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005772 QualType OrigT = Arg.getIntegralType();
5773
5774 // If this is an enum type that we're instantiating, we need to use an integer
5775 // type the same size as the enumerator. We don't want to build an
5776 // IntegerLiteral with enum type. The integer type of an enum type can be of
5777 // any integral type with C++11 enum classes, make sure we create the right
5778 // type of literal for it.
5779 QualType T = OrigT;
5780 if (const EnumType *ET = OrigT->getAs<EnumType>())
5781 T = ET->getDecl()->getIntegerType();
5782
5783 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00005784 if (T->isAnyCharacterType()) {
Aaron Ballman9a17c852016-01-07 20:59:26 +00005785 // This does not need to handle u8 character literals because those are
5786 // of type char, and so can also be covered by an ASCII character literal.
Douglas Gregorfb65e592011-07-27 05:40:30 +00005787 CharacterLiteral::CharacterKind Kind;
5788 if (T->isWideCharType())
5789 Kind = CharacterLiteral::Wide;
5790 else if (T->isChar16Type())
5791 Kind = CharacterLiteral::UTF16;
5792 else if (T->isChar32Type())
5793 Kind = CharacterLiteral::UTF32;
5794 else
5795 Kind = CharacterLiteral::Ascii;
5796
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005797 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
5798 Kind, T, Loc);
5799 } else if (T->isBooleanType()) {
5800 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
5801 T, Loc);
5802 } else if (T->isNullPtrType()) {
5803 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
5804 } else {
5805 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00005806 }
5807
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005808 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00005809 // FIXME: This is a hack. We need a better way to handle substituted
5810 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00005811 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
5812 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005813 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00005814 Loc, Loc);
5815 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00005816
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005817 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005818}
5819
Douglas Gregor641040a2011-01-12 23:45:44 +00005820/// \brief Match two template parameters within template parameter lists.
5821static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
5822 bool Complain,
5823 Sema::TemplateParameterListEqualKind Kind,
5824 SourceLocation TemplateArgLoc) {
5825 // Check the actual kind (type, non-type, template).
5826 if (Old->getKind() != New->getKind()) {
5827 if (Complain) {
5828 unsigned NextDiag = diag::err_template_param_different_kind;
5829 if (TemplateArgLoc.isValid()) {
5830 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5831 NextDiag = diag::note_template_param_different_kind;
5832 }
5833 S.Diag(New->getLocation(), NextDiag)
5834 << (Kind != Sema::TPL_TemplateMatch);
5835 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
5836 << (Kind != Sema::TPL_TemplateMatch);
5837 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005838
Douglas Gregor641040a2011-01-12 23:45:44 +00005839 return false;
5840 }
5841
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005842 // Check that both are parameter packs are neither are parameter packs.
5843 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005844 // template template parameter, the template template parameter can have
5845 // a parameter pack where the template template argument does not.
5846 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
5847 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5848 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00005849 if (Complain) {
5850 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
5851 if (TemplateArgLoc.isValid()) {
5852 S.Diag(TemplateArgLoc,
5853 diag::err_template_arg_template_params_mismatch);
5854 NextDiag = diag::note_template_parameter_pack_non_pack;
5855 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005856
Douglas Gregor641040a2011-01-12 23:45:44 +00005857 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
5858 : isa<NonTypeTemplateParmDecl>(New)? 1
5859 : 2;
5860 S.Diag(New->getLocation(), NextDiag)
5861 << ParamKind << New->isParameterPack();
5862 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
5863 << ParamKind << Old->isParameterPack();
5864 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005865
Douglas Gregor641040a2011-01-12 23:45:44 +00005866 return false;
5867 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005868
Douglas Gregor641040a2011-01-12 23:45:44 +00005869 // For non-type template parameters, check the type of the parameter.
5870 if (NonTypeTemplateParmDecl *OldNTTP
5871 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
5872 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005873
Douglas Gregor641040a2011-01-12 23:45:44 +00005874 // If we are matching a template template argument to a template
5875 // template parameter and one of the non-type template parameter types
5876 // is dependent, then we must wait until template instantiation time
5877 // to actually compare the arguments.
5878 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5879 (OldNTTP->getType()->isDependentType() ||
5880 NewNTTP->getType()->isDependentType()))
5881 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005882
Douglas Gregor641040a2011-01-12 23:45:44 +00005883 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
5884 if (Complain) {
5885 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
5886 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005887 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00005888 diag::err_template_arg_template_params_mismatch);
5889 NextDiag = diag::note_template_nontype_parm_different_type;
5890 }
5891 S.Diag(NewNTTP->getLocation(), NextDiag)
5892 << NewNTTP->getType()
5893 << (Kind != Sema::TPL_TemplateMatch);
5894 S.Diag(OldNTTP->getLocation(),
5895 diag::note_template_nontype_parm_prev_declaration)
5896 << OldNTTP->getType();
5897 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005898
Douglas Gregor641040a2011-01-12 23:45:44 +00005899 return false;
5900 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005901
Douglas Gregor641040a2011-01-12 23:45:44 +00005902 return true;
5903 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005904
Douglas Gregor641040a2011-01-12 23:45:44 +00005905 // For template template parameters, check the template parameter types.
5906 // The template parameter lists of template template
5907 // parameters must agree.
5908 if (TemplateTemplateParmDecl *OldTTP
5909 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005910 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00005911 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
5912 OldTTP->getTemplateParameters(),
5913 Complain,
5914 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005915 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00005916 : Kind),
5917 TemplateArgLoc);
5918 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005919
Douglas Gregor641040a2011-01-12 23:45:44 +00005920 return true;
5921}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005922
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005923/// \brief Diagnose a known arity mismatch when comparing template argument
5924/// lists.
5925static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005926void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005927 TemplateParameterList *New,
5928 TemplateParameterList *Old,
5929 Sema::TemplateParameterListEqualKind Kind,
5930 SourceLocation TemplateArgLoc) {
5931 unsigned NextDiag = diag::err_template_param_list_different_arity;
5932 if (TemplateArgLoc.isValid()) {
5933 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5934 NextDiag = diag::note_template_param_list_different_arity;
5935 }
5936 S.Diag(New->getTemplateLoc(), NextDiag)
5937 << (New->size() > Old->size())
5938 << (Kind != Sema::TPL_TemplateMatch)
5939 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
5940 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
5941 << (Kind != Sema::TPL_TemplateMatch)
5942 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
5943}
5944
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005945/// \brief Determine whether the given template parameter lists are
5946/// equivalent.
5947///
Mike Stump11289f42009-09-09 15:08:12 +00005948/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005949/// source code as part of a new template declaration.
5950///
5951/// \param Old The old template parameter list, typically found via
5952/// name lookup of the template declared with this template parameter
5953/// list.
5954///
5955/// \param Complain If true, this routine will produce a diagnostic if
5956/// the template parameter lists are not equivalent.
5957///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005958/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00005959///
5960/// \param TemplateArgLoc If this source location is valid, then we
5961/// are actually checking the template parameter list of a template
5962/// argument (New) against the template parameter list of its
5963/// corresponding template template parameter (Old). We produce
5964/// slightly different diagnostics in this scenario.
5965///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005966/// \returns True if the template parameter lists are equal, false
5967/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005968bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005969Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
5970 TemplateParameterList *Old,
5971 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005972 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00005973 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005974 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
5975 if (Complain)
5976 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5977 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005978
5979 return false;
5980 }
5981
Douglas Gregor641040a2011-01-12 23:45:44 +00005982 // C++0x [temp.arg.template]p3:
5983 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005984 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00005985 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005986 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005987 // template-parameter-list of P. [...]
5988 TemplateParameterList::iterator NewParm = New->begin();
5989 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005990 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005991 OldParmEnd = Old->end();
5992 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00005993 if (Kind != TPL_TemplateTemplateArgumentMatch ||
5994 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005995 if (NewParm == NewParmEnd) {
5996 if (Complain)
5997 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5998 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005999
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006000 return false;
6001 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006002
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006003 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6004 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006005 return false;
6006
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006007 ++NewParm;
6008 continue;
6009 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006010
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006011 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00006012 // [...] When P's template- parameter-list contains a template parameter
6013 // pack (14.5.3), the template parameter pack will match zero or more
6014 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006015 // template-parameter-list of A with the same type and form as the
6016 // template parameter pack in P (ignoring whether those template
6017 // parameters are template parameter packs).
6018 for (; NewParm != NewParmEnd; ++NewParm) {
6019 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6020 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006021 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006022 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006023 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006024
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006025 // Make sure we exhausted all of the arguments.
6026 if (NewParm != NewParmEnd) {
6027 if (Complain)
6028 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6029 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006030
Douglas Gregorfd4344b2011-01-13 00:08:50 +00006031 return false;
6032 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006033
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006034 return true;
6035}
6036
6037/// \brief Check whether a template can be declared within this scope.
6038///
6039/// If the template declaration is valid in this scope, returns
6040/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00006041bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006042Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00006043 if (!S)
6044 return false;
6045
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006046 // Find the nearest enclosing declaration scope.
6047 while ((S->getFlags() & Scope::DeclScope) == 0 ||
6048 (S->getFlags() & Scope::TemplateParamScope) != 0)
6049 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00006050
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00006051 // C++ [temp]p4:
6052 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00006053 DeclContext *Ctx = S->getEntity();
Alex Lorenz560ae562016-11-02 15:46:34 +00006054 if (Ctx && Ctx->isExternCContext()) {
6055 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
6056 << TemplateParams->getSourceRange();
6057 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
6058 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
6059 return true;
6060 }
Richard Smith8df390f2016-09-08 23:14:54 +00006061 Ctx = Ctx->getRedeclContext();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006062
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00006063 // C++ [temp]p2:
6064 // A template-declaration can appear only as a namespace scope or
6065 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00006066 if (Ctx) {
6067 if (Ctx->isFileContext())
6068 return false;
6069 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
6070 // C++ [temp.mem]p2:
6071 // A local class shall not have member templates.
6072 if (RD->isLocalClass())
6073 return Diag(TemplateParams->getTemplateLoc(),
6074 diag::err_template_inside_local_class)
6075 << TemplateParams->getSourceRange();
6076 else
6077 return false;
6078 }
6079 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006080
Mike Stump11289f42009-09-09 15:08:12 +00006081 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006082 diag::err_template_outside_namespace_or_class_scope)
6083 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006084}
Douglas Gregor67a65642009-02-17 23:15:12 +00006085
Douglas Gregor54888652009-10-07 00:13:32 +00006086/// \brief Determine what kind of template specialization the given declaration
6087/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006088static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00006089 if (!D)
6090 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006091
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006092 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
6093 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00006094 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
6095 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00006096 if (VarDecl *Var = dyn_cast<VarDecl>(D))
6097 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006098
Douglas Gregor54888652009-10-07 00:13:32 +00006099 return TSK_Undeclared;
6100}
6101
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006102/// \brief Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006103/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00006104///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006105/// This routine determines whether a template specialization can be declared
6106/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00006107///
6108/// \param S the semantic analysis object for which this check is being
6109/// performed.
6110///
6111/// \param Specialized the entity being specialized or instantiated, which
6112/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006113/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00006114/// member class).
6115///
6116/// \param PrevDecl the previous declaration of this entity, if any.
6117///
6118/// \param Loc the location of the explicit specialization or instantiation of
6119/// this entity.
6120///
6121/// \param IsPartialSpecialization whether this is a partial specialization of
6122/// a class template.
6123///
Douglas Gregor54888652009-10-07 00:13:32 +00006124/// \returns true if there was an error that we cannot recover from, false
6125/// otherwise.
6126static bool CheckTemplateSpecializationScope(Sema &S,
6127 NamedDecl *Specialized,
6128 NamedDecl *PrevDecl,
6129 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006130 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00006131 // Keep these "kind" numbers in sync with the %select statements in the
6132 // various diagnostics emitted by this routine.
6133 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00006134 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006135 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006136 else if (isa<VarTemplateDecl>(Specialized))
6137 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00006138 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006139 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006140 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006141 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006142 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00006143 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006144 else if (isa<RecordDecl>(Specialized))
6145 EntityKind = 7;
6146 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
6147 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00006148 else {
Richard Smith7d137e32012-03-23 03:33:32 +00006149 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006150 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006151 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00006152 return true;
6153 }
6154
Douglas Gregorf47b9112009-02-25 22:02:03 +00006155 // C++ [temp.expl.spec]p2:
6156 // An explicit specialization shall be declared in the namespace
6157 // of which the template is a member, or, for member templates, in
6158 // the namespace of which the enclosing class or enclosing class
6159 // template is a member. An explicit specialization of a member
6160 // function, member class or static data member of a class
6161 // template shall be declared in the namespace of which the class
6162 // template is a member. Such a declaration may also be a
6163 // definition. If the declaration is not a definition, the
6164 // specialization may be defined later in the name- space in which
6165 // the explicit specialization was declared, or in a namespace
6166 // that encloses the one in which the explicit specialization was
6167 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00006168 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00006169 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006170 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00006171 return true;
6172 }
Douglas Gregore4b05162009-10-07 17:21:34 +00006173
Douglas Gregor40fb7442009-10-07 17:30:37 +00006174 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006175 if (S.getLangOpts().MicrosoftExt) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006176 // Do not warn for class scope explicit specialization during
6177 // instantiation, warning was already emitted during pattern
6178 // semantic analysis.
6179 if (!S.ActiveTemplateInstantiations.size())
6180 S.Diag(Loc, diag::ext_function_specialization_in_class)
6181 << Specialized;
6182 } else {
6183 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
6184 << Specialized;
6185 return true;
6186 }
Douglas Gregor40fb7442009-10-07 17:30:37 +00006187 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006188
Douglas Gregor44e5a0a2011-10-20 16:41:18 +00006189 if (S.CurContext->isRecord() &&
6190 !S.CurContext->Equals(Specialized->getDeclContext())) {
6191 // Make sure that we're specializing in the right record context.
6192 // Otherwise, things can go horribly wrong.
6193 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
6194 << Specialized;
6195 return true;
6196 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00006197
Douglas Gregore4b05162009-10-07 17:21:34 +00006198 // C++ [temp.class.spec]p6:
6199 // A class template partial specialization may be declared or redeclared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006200 // in any namespace scope in which its definition may be defined (14.5.1
6201 // and 14.5.2).
Richard Smitha98f8fc2013-12-07 05:09:50 +00006202 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00006203 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00006204 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00006205
6206 // Make sure that this redeclaration (or definition) occurs in an enclosing
6207 // namespace.
6208 // Note that HandleDeclarator() performs this check for explicit
6209 // specializations of function templates, static data members, and member
6210 // functions, so we skip the check here for those kinds of entities.
6211 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
6212 // Should we refactor that check, so that it occurs later?
6213 if (!DC->Encloses(SpecializedContext) &&
6214 !(isa<FunctionTemplateDecl>(Specialized) ||
6215 isa<FunctionDecl>(Specialized) ||
6216 isa<VarTemplateDecl>(Specialized) ||
6217 isa<VarDecl>(Specialized))) {
6218 if (isa<TranslationUnitDecl>(SpecializedContext))
6219 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
6220 << EntityKind << Specialized;
Alexey Bataev0068cb22015-03-20 07:21:46 +00006221 else if (isa<NamespaceDecl>(SpecializedContext)) {
6222 int Diag = diag::err_template_spec_redecl_out_of_scope;
6223 if (S.getLangOpts().MicrosoftExt)
6224 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
6225 S.Diag(Loc, Diag) << EntityKind << Specialized
6226 << cast<NamedDecl>(SpecializedContext);
6227 } else
Richard Smitha98f8fc2013-12-07 05:09:50 +00006228 llvm_unreachable("unexpected namespace context for specialization");
6229
6230 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
6231 } else if ((!PrevDecl ||
6232 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
6233 getTemplateSpecializationKind(PrevDecl) ==
6234 TSK_ImplicitInstantiation)) {
Douglas Gregorb1aab432010-09-12 05:08:28 +00006235 // C++ [temp.exp.spec]p2:
6236 // An explicit specialization shall be declared in the namespace of which
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006237 // the template is a member, or, for member templates, in the namespace
Douglas Gregorb1aab432010-09-12 05:08:28 +00006238 // of which the enclosing class or enclosing class template is a member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006239 // An explicit specialization of a member function, member class or
6240 // static data member of a class template shall be declared in the
Douglas Gregorb1aab432010-09-12 05:08:28 +00006241 // namespace of which the class template is a member.
6242 //
Richard Smitha98f8fc2013-12-07 05:09:50 +00006243 // C++11 [temp.expl.spec]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006244 // An explicit specialization shall be declared in a namespace enclosing
Douglas Gregorb1aab432010-09-12 05:08:28 +00006245 // the specialized template.
Richard Smitha98f8fc2013-12-07 05:09:50 +00006246 // C++11 [temp.explicit]p3:
6247 // An explicit instantiation shall appear in an enclosing namespace of its
6248 // template.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006249 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006250 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
Richard Smith0bf8a4922011-10-18 20:49:44 +00006251 if (isa<TranslationUnitDecl>(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006252 assert(!IsCPlusPlus11Extension &&
Richard Smith0bf8a4922011-10-18 20:49:44 +00006253 "DC encloses TU but isn't in enclosing namespace set");
6254 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor8ce63152010-09-12 05:24:55 +00006255 << EntityKind << Specialized;
Richard Smith0bf8a4922011-10-18 20:49:44 +00006256 } else if (isa<NamespaceDecl>(SpecializedContext)) {
6257 int Diag;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006258 if (!IsCPlusPlus11Extension)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006259 Diag = diag::err_template_spec_decl_out_of_scope;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006260 else if (!S.getLangOpts().CPlusPlus11)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006261 Diag = diag::ext_template_spec_decl_out_of_scope;
6262 else
6263 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
6264 S.Diag(Loc, Diag)
6265 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
6266 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006267
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006268 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00006269 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006270 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006271
Douglas Gregorf47b9112009-02-25 22:02:03 +00006272 return false;
6273}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006274
Richard Smith57aae072016-12-28 02:37:25 +00006275static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
6276 if (!E->isTypeDependent())
Richard Smith6056d5e2014-02-09 00:54:43 +00006277 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00006278 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00006279 Checker.TraverseStmt(E);
Richard Smith57aae072016-12-28 02:37:25 +00006280 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00006281 return E->getSourceRange();
6282 return Checker.MatchLoc;
6283}
6284
6285static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
6286 if (!TL.getType()->isDependentType())
6287 return SourceLocation();
Richard Smith57aae072016-12-28 02:37:25 +00006288 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
Richard Smith6056d5e2014-02-09 00:54:43 +00006289 Checker.TraverseTypeLoc(TL);
Richard Smith57aae072016-12-28 02:37:25 +00006290 if (Checker.MatchLoc.isInvalid())
Richard Smith6056d5e2014-02-09 00:54:43 +00006291 return TL.getSourceRange();
6292 return Checker.MatchLoc;
6293}
6294
Larisse Voufo39a1e502013-08-06 01:03:05 +00006295/// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006296/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006297static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006298 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
6299 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006300 for (unsigned I = 0; I != NumArgs; ++I) {
6301 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006302 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006303 S, TemplateNameLoc, Param, Args[I].pack_begin(),
6304 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006305 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006306
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006307 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006308 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006309
Eli Friedmanb826a002012-09-26 02:36:12 +00006310 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006311 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00006312
6313 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006314
Douglas Gregor98318c22011-01-03 21:37:45 +00006315 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006316 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
6317 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00006318
6319 // Strip off any implicit casts we added as part of type checking.
6320 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
6321 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006322
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006323 // C++ [temp.class.spec]p8:
6324 // A non-type argument is non-specialized if it is the name of a
6325 // non-type parameter. All other non-type arguments are
6326 // specialized.
6327 //
6328 // Below, we check the two conditions that only apply to
6329 // specialized non-type arguments, so skip any non-specialized
6330 // arguments.
6331 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00006332 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006333 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006334
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006335 // C++ [temp.class.spec]p9:
6336 // Within the argument list of a class template partial
6337 // specialization, the following restrictions apply:
6338 // -- A partially specialized non-type argument expression
6339 // shall not involve a template parameter of the partial
6340 // specialization except when the argument expression is a
6341 // simple identifier.
Richard Smith57aae072016-12-28 02:37:25 +00006342 // -- The type of a template parameter corresponding to a
6343 // specialized non-type argument shall not be dependent on a
6344 // parameter of the specialization.
6345 // DR1315 removes the first bullet, leaving an incoherent set of rules.
6346 // We implement a compromise between the original rules and DR1315:
6347 // -- A specialized non-type template argument shall not be
6348 // type-dependent and the corresponding template parameter
6349 // shall have a non-dependent type.
Richard Smith6056d5e2014-02-09 00:54:43 +00006350 SourceRange ParamUseRange =
Richard Smith57aae072016-12-28 02:37:25 +00006351 findTemplateParameterInType(Param->getDepth(), ArgExpr);
Richard Smith6056d5e2014-02-09 00:54:43 +00006352 if (ParamUseRange.isValid()) {
6353 if (IsDefaultArgument) {
6354 S.Diag(TemplateNameLoc,
6355 diag::err_dependent_non_type_arg_in_partial_spec);
6356 S.Diag(ParamUseRange.getBegin(),
6357 diag::note_dependent_non_type_default_arg_in_partial_spec)
6358 << ParamUseRange;
6359 } else {
6360 S.Diag(ParamUseRange.getBegin(),
6361 diag::err_dependent_non_type_arg_in_partial_spec)
6362 << ParamUseRange;
6363 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006364 return true;
6365 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006366
Richard Smith6056d5e2014-02-09 00:54:43 +00006367 ParamUseRange = findTemplateParameter(
Richard Smith57aae072016-12-28 02:37:25 +00006368 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
Richard Smith6056d5e2014-02-09 00:54:43 +00006369 if (ParamUseRange.isValid()) {
6370 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
6371 diag::err_dependent_typed_non_type_arg_in_partial_spec)
Richard Smith57aae072016-12-28 02:37:25 +00006372 << Param->getType();
Richard Smith6056d5e2014-02-09 00:54:43 +00006373 S.Diag(Param->getLocation(), diag::note_template_param_here)
Richard Smith57aae072016-12-28 02:37:25 +00006374 << (IsDefaultArgument ? ParamUseRange : SourceRange())
6375 << ParamUseRange;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006376 return true;
6377 }
6378 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006379
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006380 return false;
6381}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006382
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006383/// \brief Check the non-type template arguments of a class template
6384/// partial specialization according to C++ [temp.class.spec]p9.
6385///
Richard Smith6056d5e2014-02-09 00:54:43 +00006386/// \param TemplateNameLoc the location of the template name.
Simon Pilgrim6905d222016-12-30 22:55:33 +00006387/// \param PrimaryTemplate the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00006388/// template.
6389/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00006390/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00006391/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006392///
Richard Smith6056d5e2014-02-09 00:54:43 +00006393/// \returns \c true if there was an error, \c false otherwise.
Richard Smith57aae072016-12-28 02:37:25 +00006394bool Sema::CheckTemplatePartialSpecializationArgs(
6395 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
6396 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
6397 // We have to be conservative when checking a template in a dependent
6398 // context.
6399 if (PrimaryTemplate->getDeclContext()->isDependentContext())
6400 return false;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006401
Richard Smith57aae072016-12-28 02:37:25 +00006402 TemplateParameterList *TemplateParams =
6403 PrimaryTemplate->getTemplateParameters();
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006404 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6405 NonTypeTemplateParmDecl *Param
6406 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
6407 if (!Param)
6408 continue;
6409
Richard Smith57aae072016-12-28 02:37:25 +00006410 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
6411 Param, &TemplateArgs[I],
6412 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006413 return true;
6414 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006415
6416 return false;
6417}
6418
John McCall48871652010-08-21 09:40:31 +00006419DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00006420Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
6421 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00006422 SourceLocation KWLoc,
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006423 SourceLocation ModulePrivateLoc,
Richard Smith4b55a9c2014-04-17 03:29:33 +00006424 TemplateIdAnnotation &TemplateId,
Douglas Gregor67a65642009-02-17 23:15:12 +00006425 AttributeList *Attr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00006426 MultiTemplateParamsArg
6427 TemplateParameterLists,
6428 SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006429 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00006430
Richard Smith4b55a9c2014-04-17 03:29:33 +00006431 CXXScopeSpec &SS = TemplateId.SS;
6432
Abramo Bagnara60804e12011-03-18 15:16:37 +00006433 // NOTE: KWLoc is the location of the tag keyword. This will instead
6434 // store the location of the outermost template keyword in the declaration.
6435 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00006436 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
6437 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
6438 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
6439 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00006440
Douglas Gregor67a65642009-02-17 23:15:12 +00006441 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00006442 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00006443 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00006444 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
6445
6446 if (!ClassTemplate) {
6447 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006448 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00006449 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
6450 return true;
6451 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006452
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006453 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00006454 bool isPartialSpecialization = false;
6455
Douglas Gregorf47b9112009-02-25 22:02:03 +00006456 // Check the validity of the template headers that introduce this
6457 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00006458 // FIXME: We probably shouldn't complain about these headers for
6459 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006460 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00006461 TemplateParameterList *TemplateParams =
6462 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00006463 KWLoc, TemplateNameLoc, SS, &TemplateId,
6464 TemplateParameterLists, TUK == TUK_Friend, isExplicitSpecialization,
6465 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006466 if (Invalid)
6467 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006468
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006469 if (TemplateParams && TemplateParams->size() > 0) {
6470 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00006471
Douglas Gregorec9518b2010-12-21 08:14:57 +00006472 if (TUK == TUK_Friend) {
6473 Diag(KWLoc, diag::err_partial_specialization_friend)
6474 << SourceRange(LAngleLoc, RAngleLoc);
6475 return true;
6476 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006477
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006478 // C++ [temp.class.spec]p10:
6479 // The template parameter list of a specialization shall not
6480 // contain default template argument values.
6481 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6482 Decl *Param = TemplateParams->getParam(I);
6483 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6484 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006485 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006486 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00006487 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006488 }
6489 } else if (NonTypeTemplateParmDecl *NTTP
6490 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6491 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006492 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006493 diag::err_default_arg_in_partial_spec)
6494 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006495 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006496 }
6497 } else {
6498 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006499 if (TTP->hasDefaultArgument()) {
6500 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006501 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006502 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006503 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00006504 }
6505 }
6506 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006507 } else if (TemplateParams) {
6508 if (TUK == TUK_Friend)
6509 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00006510 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006511 SourceRange(TemplateParams->getTemplateLoc(),
6512 TemplateParams->getRAngleLoc()))
6513 << SourceRange(LAngleLoc, RAngleLoc);
6514 else
6515 isExplicitSpecialization = true;
Richard Smith4b55a9c2014-04-17 03:29:33 +00006516 } else {
6517 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006518 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006519
Douglas Gregor67a65642009-02-17 23:15:12 +00006520 // Check that the specialization uses the same tag kind as the
6521 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00006522 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6523 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00006524 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00006525 Kind, TUK == TUK_Definition, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00006526 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00006527 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00006528 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00006529 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00006530 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00006531 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006532 diag::note_previous_use);
6533 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6534 }
6535
Douglas Gregorc40290e2009-03-09 23:48:35 +00006536 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00006537 TemplateArgumentListInfo TemplateArgs =
6538 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00006539
Douglas Gregor14406932011-01-03 20:35:03 +00006540 // Check for unexpanded parameter packs in any of the template arguments.
6541 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006542 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00006543 UPPC_PartialSpecialization))
6544 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006545
Douglas Gregor67a65642009-02-17 23:15:12 +00006546 // Check that the template argument list is well-formed for this
6547 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006548 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00006549 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6550 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006551 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006552
Douglas Gregor2373c592009-05-31 09:31:02 +00006553 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00006554 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00006555 if (isPartialSpecialization) {
Richard Smith57aae072016-12-28 02:37:25 +00006556 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
6557 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006558 return true;
6559
Richard Smith57aae072016-12-28 02:37:25 +00006560 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
6561 // also do it during instantiation.
Douglas Gregor678d76c2011-07-01 01:22:09 +00006562 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006563 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00006564 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00006565 TemplateArgs.arguments(), InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00006566 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
6567 << ClassTemplate->getDeclName();
6568 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00006569 }
6570 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006571
Craig Topperc3ec1492014-05-26 06:22:03 +00006572 void *InsertPos = nullptr;
6573 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00006574
6575 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006576 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00006577 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006578 else
Craig Topper7e0daca2014-06-26 04:58:53 +00006579 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00006580
Craig Topperc3ec1492014-05-26 06:22:03 +00006581 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00006582
Douglas Gregorf47b9112009-02-25 22:02:03 +00006583 // Check whether we can declare a class template specialization in
6584 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00006585 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006586 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
6587 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006588 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006589 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006590
Douglas Gregor15301382009-07-30 17:40:51 +00006591 // The canonical type
6592 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00006593 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00006594 // Build the canonical type that describes the converted template
6595 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00006596 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6597 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00006598 Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006599
6600 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006601 ClassTemplate->getInjectedClassNameSpecialization())) {
6602 // C++ [temp.class.spec]p9b3:
6603 //
6604 // -- The argument list of the specialization shall not be identical
6605 // to the implicit argument list of the primary template.
Richard Smith0e617ec2016-12-27 07:56:27 +00006606 //
6607 // This rule has since been removed, because it's redundant given DR1495,
6608 // but we keep it because it produces better diagnostics and recovery.
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006609 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00006610 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00006611 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006612 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
6613 ClassTemplate->getIdentifier(),
6614 TemplateNameLoc,
6615 Attr,
6616 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00006617 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00006618 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00006619 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006620 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006621 }
Douglas Gregor15301382009-07-30 17:40:51 +00006622
Douglas Gregor2373c592009-05-31 09:31:02 +00006623 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00006624 ClassTemplatePartialSpecializationDecl *PrevPartial
6625 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006626 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00006627 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00006628 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006629 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00006630 TemplateParams,
6631 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00006632 Converted,
John McCall6b51f282009-11-23 01:53:49 +00006633 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00006634 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00006635 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00006636 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006637 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Benjamin Kramer9cc210652015-08-05 09:40:49 +00006638 Partial->setTemplateParameterListsInfo(
6639 Context, TemplateParameterLists.drop_back(1));
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006640 }
Douglas Gregor2373c592009-05-31 09:31:02 +00006641
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006642 if (!PrevPartial)
6643 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006644 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00006645
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006646 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00006647 // template specialization, make a note of that.
6648 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6649 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006650
Richard Smith57aae072016-12-28 02:37:25 +00006651 CheckTemplatePartialSpecialization(Partial);
Douglas Gregor67a65642009-02-17 23:15:12 +00006652 } else {
6653 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00006654 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00006655 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00006656 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00006657 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006658 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006659 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00006660 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00006661 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00006662 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006663 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00006664 Specialization->setTemplateParameterListsInfo(Context,
Benjamin Kramer9cc210652015-08-05 09:40:49 +00006665 TemplateParameterLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006666 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006667
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006668 if (!PrevDecl)
6669 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00006670
David Majnemer678f50b2015-11-18 19:49:19 +00006671 if (CurContext->isDependentContext()) {
6672 // -fms-extensions permits specialization of nested classes without
6673 // fully specializing the outer class(es).
6674 assert(getLangOpts().MicrosoftExt &&
6675 "Only possible with -fms-extensions!");
6676 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6677 CanonType = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00006678 CanonTemplate, Converted);
David Majnemer678f50b2015-11-18 19:49:19 +00006679 } else {
6680 CanonType = Context.getTypeDeclType(Specialization);
6681 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006682 }
6683
Douglas Gregor06db9f52009-10-12 20:18:28 +00006684 // C++ [temp.expl.spec]p6:
6685 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006686 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006687 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006688 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006689 // use occurs; no diagnostic is required.
6690 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006691 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006692 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006693 // Is there any previous explicit specialization declaration?
6694 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6695 Okay = true;
6696 break;
6697 }
6698 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006699
Douglas Gregorc854c662010-02-26 06:03:23 +00006700 if (!Okay) {
6701 SourceRange Range(TemplateNameLoc, RAngleLoc);
6702 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6703 << Context.getTypeDeclType(Specialization) << Range;
6704
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006705 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00006706 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006707 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00006708 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00006709 return true;
6710 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006711 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006712
Douglas Gregor2208a292009-09-26 20:57:03 +00006713 // If this is not a friend, note that this is an explicit specialization.
6714 if (TUK != TUK_Friend)
6715 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00006716
6717 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006718 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00006719 RecordDecl *Def = Specialization->getDefinition();
6720 NamedDecl *Hidden = nullptr;
6721 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
6722 SkipBody->ShouldSkip = true;
6723 makeMergedDefinitionVisible(Hidden, KWLoc);
6724 // From here on out, treat this as just a redeclaration.
6725 TUK = TUK_Declaration;
6726 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00006727 SourceRange Range(TemplateNameLoc, RAngleLoc);
Richard Smith792c22d2016-12-24 04:09:05 +00006728 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00006729 Diag(Def->getLocation(), diag::note_previous_definition);
6730 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00006731 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006732 }
6733 }
6734
John McCall659a3372010-12-18 03:30:47 +00006735 if (Attr)
6736 ProcessDeclAttributeList(S, Specialization, Attr);
6737
Richard Smith034b94a2012-08-17 03:20:55 +00006738 // Add alignment attributes if necessary; these attributes are checked when
6739 // the ASTContext lays out the structure.
6740 if (TUK == TUK_Definition) {
6741 AddAlignmentAttributesForRecord(Specialization);
6742 AddMsStructLayoutForRecord(Specialization);
6743 }
6744
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006745 if (ModulePrivateLoc.isValid())
6746 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6747 << (isPartialSpecialization? 1 : 0)
6748 << FixItHint::CreateRemoval(ModulePrivateLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00006749
Douglas Gregord56a91e2009-02-26 22:19:44 +00006750 // Build the fully-sugared type for this class template
6751 // specialization as the user wrote in the specialization
6752 // itself. This means that we'll pretty-print the type retrieved
6753 // from the specialization's declaration the way that the user
6754 // actually wrote the specialization, rather than formatting the
6755 // name based on the "canonical" representation used to store the
6756 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00006757 TypeSourceInfo *WrittenTy
6758 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6759 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006760 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006761 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006762 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006763 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006764
Douglas Gregor1e249f82009-02-25 22:18:32 +00006765 // C++ [temp.expl.spec]p9:
6766 // A template explicit specialization is in the scope of the
6767 // namespace in which the template was defined.
6768 //
6769 // We actually implement this paragraph where we set the semantic
6770 // context (in the creation of the ClassTemplateSpecializationDecl),
6771 // but we also maintain the lexical context where the actual
6772 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00006773 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00006774
Douglas Gregor67a65642009-02-17 23:15:12 +00006775 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006776 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00006777 Specialization->startDefinition();
6778
Douglas Gregor2208a292009-09-26 20:57:03 +00006779 if (TUK == TUK_Friend) {
6780 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6781 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00006782 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00006783 /*FIXME:*/KWLoc);
6784 Friend->setAccess(AS_public);
6785 CurContext->addDecl(Friend);
6786 } else {
6787 // Add the specialization into its lexical context, so that it can
6788 // be seen when iterating through the list of declarations in that
6789 // context. However, specializations are not found by name lookup.
6790 CurContext->addDecl(Specialization);
6791 }
John McCall48871652010-08-21 09:40:31 +00006792 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00006793}
Douglas Gregor333489b2009-03-27 23:10:48 +00006794
John McCall48871652010-08-21 09:40:31 +00006795Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006796 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00006797 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006798 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00006799 ActOnDocumentableDecl(NewDecl);
6800 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006801}
6802
John McCall4f7ced62010-02-11 01:33:53 +00006803/// \brief Strips various properties off an implicit instantiation
6804/// that has just been explicitly specialized.
6805static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00006806 D->dropAttr<DLLImportAttr>();
6807 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00006808
Nico Webere4974382014-12-19 23:52:45 +00006809 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00006810 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00006811}
6812
Nico Webera8f80b32012-01-09 19:52:25 +00006813/// \brief Compute the diagnostic location for an explicit instantiation
6814// declaration or definition.
6815static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006816 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00006817 // Explicit instantiations following a specialization have no effect and
6818 // hence no PointOfInstantiation. In that case, walk decl backwards
6819 // until a valid name loc is found.
6820 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006821 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
6822 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00006823 PrevDiagLoc = Prev->getLocation();
6824 }
6825 assert(PrevDiagLoc.isValid() &&
6826 "Explicit instantiation without point of instantiation?");
6827 return PrevDiagLoc;
6828}
6829
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006830/// \brief Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006831/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006832/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006833/// new specialization/instantiation will have any effect.
6834///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006835/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006836/// instantiation.
6837///
6838/// \param NewTSK the kind of the new explicit specialization or instantiation.
6839///
6840/// \param PrevDecl the previous declaration of the entity.
6841///
6842/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
6843///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006844/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006845/// declaration was instantiated (either implicitly or explicitly).
6846///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006847/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006848/// specialization or instantiation has no effect and should be ignored.
6849///
6850/// \returns true if there was an error that should prevent the introduction of
6851/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00006852bool
6853Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6854 TemplateSpecializationKind NewTSK,
6855 NamedDecl *PrevDecl,
6856 TemplateSpecializationKind PrevTSK,
6857 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00006858 bool &HasNoEffect) {
6859 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006860
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006861 switch (NewTSK) {
6862 case TSK_Undeclared:
6863 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00006864 assert(
6865 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
6866 "previous declaration must be implicit!");
6867 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006868
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006869 case TSK_ExplicitSpecialization:
6870 switch (PrevTSK) {
6871 case TSK_Undeclared:
6872 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006873 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006874 // explicitly specialized or has merely been mentioned without any
6875 // instantiation.
6876 return false;
6877
6878 case TSK_ImplicitInstantiation:
6879 if (PrevPointOfInstantiation.isInvalid()) {
6880 // The declaration itself has not actually been instantiated, so it is
6881 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00006882 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006883 return false;
6884 }
6885 // Fall through
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006886
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006887 case TSK_ExplicitInstantiationDeclaration:
6888 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006889 assert((PrevTSK == TSK_ImplicitInstantiation ||
6890 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006891 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006892
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006893 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006894 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006895 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006896 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006897 // implicit instantiation to take place, in every translation unit in
6898 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006899 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006900 // Is there any previous explicit specialization declaration?
6901 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
6902 return false;
6903 }
6904
Douglas Gregor1d957a32009-10-27 18:42:08 +00006905 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006906 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00006907 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006908 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006909
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006910 return true;
6911 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006912
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006913 case TSK_ExplicitInstantiationDeclaration:
6914 switch (PrevTSK) {
6915 case TSK_ExplicitInstantiationDeclaration:
6916 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00006917 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006918 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006919
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006920 case TSK_Undeclared:
6921 case TSK_ImplicitInstantiation:
6922 // We're explicitly instantiating something that may have already been
6923 // implicitly instantiated; that's fine.
6924 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006925
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006926 case TSK_ExplicitSpecialization:
6927 // C++0x [temp.explicit]p4:
6928 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006929 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006930 // specialization for that template, the explicit instantiation has no
6931 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00006932 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006933 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006934
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006935 case TSK_ExplicitInstantiationDefinition:
6936 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006937 // If an entity is the subject of both an explicit instantiation
6938 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006939 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006940 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00006941 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00006942
6943 // Explicit instantiations following a specialization have no effect and
6944 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
6945 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00006946 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6947 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006948 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006949 return false;
6950 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006951
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006952 case TSK_ExplicitInstantiationDefinition:
6953 switch (PrevTSK) {
6954 case TSK_Undeclared:
6955 case TSK_ImplicitInstantiation:
6956 // We're explicitly instantiating something that may have already been
6957 // implicitly instantiated; that's fine.
6958 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006959
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006960 case TSK_ExplicitSpecialization:
6961 // C++ DR 259, C++0x [temp.explicit]p4:
6962 // For a given set of template parameters, if an explicit
6963 // instantiation of a template appears after a declaration of
6964 // an explicit specialization for that template, the explicit
6965 // instantiation has no effect.
Richard Smithe4caa482016-08-31 23:23:25 +00006966 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006967 << PrevDecl;
6968 Diag(PrevDecl->getLocation(),
6969 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006970 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006971 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006972
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006973 case TSK_ExplicitInstantiationDeclaration:
6974 // We're explicity instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006975 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00006976
6977 // C++0x [temp.explicit]p4:
6978 // For a given set of template parameters, if an explicit instantiation
6979 // of a template appears after a declaration of an explicit
6980 // specialization for that template, the explicit instantiation has no
6981 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006982 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00006983 // Is there any previous explicit specialization declaration?
6984 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6985 HasNoEffect = true;
6986 break;
6987 }
6988 }
6989
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006990 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006991
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006992 case TSK_ExplicitInstantiationDefinition:
6993 // C++0x [temp.spec]p5:
6994 // For a given template and a given set of template-arguments,
6995 // - an explicit instantiation definition shall appear at most once
6996 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006997
6998 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
6999 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00007000 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00007001 : diag::err_explicit_instantiation_duplicate)
7002 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00007003 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00007004 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007005 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007006 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007007 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007008 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007009
David Blaikie83d382b2011-09-23 05:06:16 +00007010 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007011}
7012
John McCallb9c78482010-04-08 09:05:18 +00007013/// \brief Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00007014/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00007015///
James Dennettf14a6e52012-06-15 22:23:43 +00007016/// The only possible way to get a dependent function template specialization
7017/// is with a friend declaration, like so:
7018///
7019/// \code
7020/// template \<class T> void foo(T);
7021/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00007022/// friend void foo<>(T);
7023/// };
James Dennettf14a6e52012-06-15 22:23:43 +00007024/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00007025///
7026/// There really isn't any useful analysis we can do here, so we
7027/// just store the information.
7028bool
7029Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
7030 const TemplateArgumentListInfo &ExplicitTemplateArgs,
7031 LookupResult &Previous) {
7032 // Remove anything from Previous that isn't a function template in
7033 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00007034 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00007035 LookupResult::Filter F = Previous.makeFilter();
7036 while (F.hasNext()) {
7037 NamedDecl *D = F.next()->getUnderlyingDecl();
7038 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00007039 !FDLookupContext->InEnclosingNamespaceSetOf(
7040 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00007041 F.erase();
7042 }
7043 F.done();
7044
7045 // Should this be diagnosed here?
7046 if (Previous.empty()) return true;
7047
7048 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
7049 ExplicitTemplateArgs);
7050 return false;
7051}
7052
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007053/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007054/// specialization.
7055///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007056/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007057/// explicit function template specialization. On successful completion,
7058/// the function declaration \p FD will become a function template
7059/// specialization.
7060///
7061/// \param FD the function declaration, which will be updated to become a
7062/// function template specialization.
7063///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007064/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
7065/// if any. Note that this may be valid info even when 0 arguments are
7066/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
7067/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007068///
Francois Pichet3a44e432011-07-08 06:21:47 +00007069/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007070/// this function specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007071bool Sema::CheckFunctionTemplateSpecialization(
7072 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
7073 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007074 // The set of function template specializations that could match this
7075 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00007076 UnresolvedSet<8> Candidates;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007077 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
7078 /*ForTakingAddress=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007079
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007080 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
7081 ConvertedTemplateArgs;
7082
Sebastian Redl50c68252010-08-31 00:36:30 +00007083 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00007084 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7085 I != E; ++I) {
7086 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
7087 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007088 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007089 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00007090 if (!FDLookupContext->InEnclosingNamespaceSetOf(
7091 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007092 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007093
Richard Smith574f4f62013-01-14 05:37:29 +00007094 // When matching a constexpr member function template specialization
7095 // against the primary template, we don't yet know whether the
7096 // specialization has an implicit 'const' (because we don't know whether
7097 // it will be a static member function until we know which template it
7098 // specializes), so adjust it now assuming it specializes this template.
7099 QualType FT = FD->getType();
7100 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00007101 CXXMethodDecl *OldMD =
7102 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00007103 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00007104 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00007105 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7106 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00007107 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00007108 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00007109 }
7110 }
7111
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007112 TemplateArgumentListInfo Args;
7113 if (ExplicitTemplateArgs)
7114 Args = *ExplicitTemplateArgs;
7115
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007116 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007117 // A trailing template-argument can be left unspecified in the
7118 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007119 // provided it can be deduced from the function argument type.
7120 // Perform template argument deduction to determine whether we may be
7121 // specializing this template.
7122 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00007123 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00007124 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00007125 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
7126 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
Richard Smithc2bebe92016-05-11 20:37:46 +00007127 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
7128 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00007129 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007130 // that we can provide nifty diagnostics.
Richard Smithc2bebe92016-05-11 20:37:46 +00007131 FailedCandidates.addCandidate().set(
7132 I.getPair(), FunTmpl->getTemplatedDecl(),
7133 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007134 (void)TDK;
7135 continue;
7136 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007137
Artem Belevich64135c32016-12-08 19:38:13 +00007138 // Target attributes are part of the cuda function signature, so
7139 // the deduced template's cuda target must match that of the
7140 // specialization. Given that C++ template deduction does not
7141 // take target attributes into account, we reject candidates
7142 // here that have a different target.
Artem Belevich13e9b4d2016-12-07 19:27:16 +00007143 if (LangOpts.CUDA &&
Artem Belevich64135c32016-12-08 19:38:13 +00007144 IdentifyCUDATarget(Specialization,
7145 /* IgnoreImplicitHDAttributes = */ true) !=
7146 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttributes = */ true)) {
Artem Belevich13e9b4d2016-12-07 19:27:16 +00007147 FailedCandidates.addCandidate().set(
7148 I.getPair(), FunTmpl->getTemplatedDecl(),
7149 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
7150 continue;
7151 }
7152
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007153 // Record this candidate.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007154 if (ExplicitTemplateArgs)
7155 ConvertedTemplateArgs[Specialization] = std::move(Args);
John McCall58cc69d2010-01-27 01:50:18 +00007156 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007157 }
7158 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007159
Douglas Gregor5de279c2009-09-26 03:41:46 +00007160 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007161 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00007162 Candidates.begin(), Candidates.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00007163 FD->getLocation(),
7164 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
7165 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00007166 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00007167 PDiag(diag::note_function_template_spec_matched));
7168
John McCall58cc69d2010-01-27 01:50:18 +00007169 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007170 return true;
John McCall58cc69d2010-01-27 01:50:18 +00007171
7172 // Ignore access information; it doesn't figure into redeclaration checking.
7173 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00007174
Nathan Wilson83839122016-04-09 02:55:27 +00007175 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
7176 // an explicit specialization (14.8.3) [...] of a concept definition.
7177 if (Specialization->getPrimaryTemplate()->isConcept()) {
7178 Diag(FD->getLocation(), diag::err_concept_specialized)
7179 << 0 /*function*/ << 1 /*explicitly specialized*/;
7180 Diag(Specialization->getLocation(), diag::note_previous_declaration);
7181 return true;
7182 }
7183
Abramo Bagnarab9893d62011-03-04 17:20:30 +00007184 FunctionTemplateSpecializationInfo *SpecInfo
7185 = Specialization->getTemplateSpecializationInfo();
7186 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00007187
7188 // Note: do not overwrite location info if previous template
7189 // specialization kind was explicit.
7190 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00007191 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00007192 Specialization->setLocation(FD->getLocation());
Richard Smith5b8b3db2012-02-20 23:28:05 +00007193 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
7194 // function can differ from the template declaration with respect to
7195 // the constexpr specifier.
7196 Specialization->setConstexpr(FD->isConstexpr());
7197 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007198
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007199 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00007200 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00007201
7202 // If this is a friend declaration, then we're not really declaring
7203 // an explicit specialization.
7204 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007205
Douglas Gregor54888652009-10-07 00:13:32 +00007206 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00007207 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007208 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00007209 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007210 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007211 false))
Douglas Gregor54888652009-10-07 00:13:32 +00007212 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00007213
7214 // C++ [temp.expl.spec]p6:
7215 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007216 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007217 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007218 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007219 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007220 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00007221 if (!isFriend &&
7222 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00007223 TSK_ExplicitSpecialization,
7224 Specialization,
7225 SpecInfo->getTemplateSpecializationKind(),
7226 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007227 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007228 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00007229
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007230 // Mark the prior declaration as an explicit specialization, so that later
7231 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007232 if (!isFriend) {
Faisal Vali81a88be2016-06-14 03:23:15 +00007233 // Since explicit specializations do not inherit '=delete' from their
7234 // primary function template - check if the 'specialization' that was
7235 // implicitly generated (during template argument deduction for partial
7236 // ordering) from the most specialized of all the function templates that
7237 // 'FD' could have been specializing, has a 'deleted' definition. If so,
7238 // first check that it was implicitly generated during template argument
7239 // deduction by making sure it wasn't referenced, and then reset the deleted
7240 // flag to not-deleted, so that we can inherit that information from 'FD'.
7241 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
7242 !Specialization->getCanonicalDecl()->isReferenced()) {
7243 assert(
7244 Specialization->getCanonicalDecl() == Specialization &&
7245 "This must be the only existing declaration of this specialization");
7246 Specialization->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007247 }
John McCall816d75b2010-03-24 07:46:06 +00007248 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007249 MarkUnusedFileScopedDecl(Specialization);
7250 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007251
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007252 // Turn the given function declaration into a function template
7253 // specialization, with the template arguments from the previous
7254 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007255 // Take copies of (semantic and syntactic) template argument lists.
7256 const TemplateArgumentList* TemplArgs = new (Context)
7257 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007258 FD->setFunctionTemplateSpecialization(
7259 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
7260 SpecInfo->getTemplateSpecializationKind(),
7261 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00007262
Artem Belevich64135c32016-12-08 19:38:13 +00007263 // A function template specialization inherits the target attributes
7264 // of its template. (We require the attributes explicitly in the
7265 // code to match, but a template may have implicit attributes by
7266 // virtue e.g. of being constexpr, and it passes these implicit
7267 // attributes on to its specializations.)
7268 if (LangOpts.CUDA)
7269 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
7270
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007271 // The "previous declaration" for this function template specialization is
7272 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00007273 Previous.clear();
7274 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007275 return false;
7276}
7277
Douglas Gregor86d142a2009-10-08 07:24:58 +00007278/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007279/// specialization.
7280///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007281/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007282/// explicit member function specialization. On successful completion,
7283/// the function declaration \p FD will become a member function
7284/// specialization.
7285///
Douglas Gregor86d142a2009-10-08 07:24:58 +00007286/// \param Member the member declaration, which will be updated to become a
7287/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007288///
John McCall1f82f242009-11-18 22:49:29 +00007289/// \param Previous the set of declarations, one of which may be specialized
7290/// by this function specialization; the set will be modified to contain the
7291/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007292bool
John McCall1f82f242009-11-18 22:49:29 +00007293Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007294 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00007295
Douglas Gregor86d142a2009-10-08 07:24:58 +00007296 // Try to find the member we are instantiating.
Richard Smith22e7cc62016-05-24 00:01:49 +00007297 NamedDecl *FoundInstantiation = nullptr;
Craig Topperc3ec1492014-05-26 06:22:03 +00007298 NamedDecl *Instantiation = nullptr;
7299 NamedDecl *InstantiatedFrom = nullptr;
7300 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00007301
John McCall1f82f242009-11-18 22:49:29 +00007302 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007303 // Nowhere to look anyway.
7304 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007305 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7306 I != E; ++I) {
7307 NamedDecl *D = (*I)->getUnderlyingDecl();
7308 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00007309 QualType Adjusted = Function->getType();
7310 if (!hasExplicitCallingConv(Adjusted))
7311 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
7312 if (Context.hasSameType(Adjusted, Method->getType())) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007313 FoundInstantiation = *I;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007314 Instantiation = Method;
7315 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007316 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007317 break;
7318 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007319 }
7320 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00007321 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007322 VarDecl *PrevVar;
7323 if (Previous.isSingleResult() &&
7324 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00007325 if (PrevVar->isStaticDataMember()) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007326 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00007327 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007328 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007329 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007330 }
7331 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007332 CXXRecordDecl *PrevRecord;
7333 if (Previous.isSingleResult() &&
7334 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007335 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00007336 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007337 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007338 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007339 }
Richard Smith7d137e32012-03-23 03:33:32 +00007340 } else if (isa<EnumDecl>(Member)) {
7341 EnumDecl *PrevEnum;
7342 if (Previous.isSingleResult() &&
7343 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007344 FoundInstantiation = Previous.getRepresentativeDecl();
Richard Smith7d137e32012-03-23 03:33:32 +00007345 Instantiation = PrevEnum;
7346 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
7347 MSInfo = PrevEnum->getMemberSpecializationInfo();
7348 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007349 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007350
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007351 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007352 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007353 // specializations are always out-of-line, the caller will complain about
7354 // this mismatch later.
7355 return false;
7356 }
John McCalle820e5e2010-04-13 20:37:33 +00007357
7358 // If this is a friend, just bail out here before we start turning
7359 // things into explicit specializations.
7360 if (Member->getFriendObjectKind() != Decl::FOK_None) {
7361 // Preserve instantiation information.
7362 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
7363 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
7364 cast<CXXMethodDecl>(InstantiatedFrom),
7365 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
7366 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
7367 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7368 cast<CXXRecordDecl>(InstantiatedFrom),
7369 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
7370 }
7371
7372 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00007373 Previous.addDecl(FoundInstantiation);
John McCalle820e5e2010-04-13 20:37:33 +00007374 return false;
7375 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007376
Douglas Gregor86d142a2009-10-08 07:24:58 +00007377 // Make sure that this is a specialization of a member.
7378 if (!InstantiatedFrom) {
7379 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
7380 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007381 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
7382 return true;
7383 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007384
Douglas Gregor06db9f52009-10-12 20:18:28 +00007385 // C++ [temp.expl.spec]p6:
7386 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00007387 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007388 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007389 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007390 // use occurs; no diagnostic is required.
7391 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00007392
Abramo Bagnara8075c852010-06-12 07:44:57 +00007393 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00007394 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
7395 TSK_ExplicitSpecialization,
7396 Instantiation,
7397 MSInfo->getTemplateSpecializationKind(),
7398 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007399 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007400 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007401
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007402 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007403 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00007404 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007405 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007406 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007407 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00007408
Douglas Gregor86d142a2009-10-08 07:24:58 +00007409 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007410 // the original declaration to note that it is an explicit specialization
7411 // (if it was previously an implicit instantiation). This latter step
7412 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00007413 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007414 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
7415 if (InstantiationFunction->getTemplateSpecializationKind() ==
7416 TSK_ImplicitInstantiation) {
7417 InstantiationFunction->setTemplateSpecializationKind(
7418 TSK_ExplicitSpecialization);
7419 InstantiationFunction->setLocation(Member->getLocation());
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007420 // Explicit specializations of member functions of class templates do not
7421 // inherit '=delete' from the member function they are specializing.
7422 if (InstantiationFunction->isDeleted()) {
7423 assert(InstantiationFunction->getCanonicalDecl() ==
7424 InstantiationFunction);
Richard Smith5f274382016-09-28 23:55:27 +00007425 InstantiationFunction->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007426 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007427 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007428
Douglas Gregor86d142a2009-10-08 07:24:58 +00007429 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
7430 cast<CXXMethodDecl>(InstantiatedFrom),
7431 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007432 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007433 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007434 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
7435 if (InstantiationVar->getTemplateSpecializationKind() ==
7436 TSK_ImplicitInstantiation) {
7437 InstantiationVar->setTemplateSpecializationKind(
7438 TSK_ExplicitSpecialization);
7439 InstantiationVar->setLocation(Member->getLocation());
7440 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007441
Larisse Voufo39a1e502013-08-06 01:03:05 +00007442 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
7443 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007444 MarkUnusedFileScopedDecl(InstantiationVar);
Richard Smith7d137e32012-03-23 03:33:32 +00007445 } else if (isa<CXXRecordDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007446 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
7447 if (InstantiationClass->getTemplateSpecializationKind() ==
7448 TSK_ImplicitInstantiation) {
7449 InstantiationClass->setTemplateSpecializationKind(
7450 TSK_ExplicitSpecialization);
7451 InstantiationClass->setLocation(Member->getLocation());
7452 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007453
Douglas Gregor86d142a2009-10-08 07:24:58 +00007454 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007455 cast<CXXRecordDecl>(InstantiatedFrom),
7456 TSK_ExplicitSpecialization);
Richard Smith7d137e32012-03-23 03:33:32 +00007457 } else {
7458 assert(isa<EnumDecl>(Member) && "Only member enums remain");
7459 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
7460 if (InstantiationEnum->getTemplateSpecializationKind() ==
7461 TSK_ImplicitInstantiation) {
7462 InstantiationEnum->setTemplateSpecializationKind(
7463 TSK_ExplicitSpecialization);
7464 InstantiationEnum->setLocation(Member->getLocation());
7465 }
7466
7467 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
7468 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007469 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007470
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007471 // Save the caller the trouble of having to figure out which declaration
7472 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00007473 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00007474 Previous.addDecl(FoundInstantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007475 return false;
7476}
7477
Douglas Gregore47f5a72009-10-14 23:41:34 +00007478/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007479///
7480/// \returns true if a serious error occurs, false otherwise.
7481static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00007482 SourceLocation InstLoc,
7483 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00007484 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
7485 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007486
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007487 if (CurContext->isRecord()) {
7488 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
7489 << D;
7490 return true;
7491 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007492
Richard Smith050d2612011-10-18 02:28:33 +00007493 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007494 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00007495 // template. If the name declared in the explicit instantiation is an
7496 // unqualified name, the explicit instantiation shall appear in the
7497 // namespace where its template is declared or, if that namespace is inline
7498 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007499 //
7500 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00007501 if (WasQualifiedName) {
7502 if (CurContext->Encloses(OrigContext))
7503 return false;
7504 } else {
7505 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
7506 return false;
7507 }
7508
7509 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
7510 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007511 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007512 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007513 diag::err_explicit_instantiation_out_of_scope :
7514 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007515 << D << NS;
7516 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007517 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007518 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007519 diag::err_explicit_instantiation_unqualified_wrong_namespace :
7520 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
7521 << D << NS;
7522 } else
7523 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007524 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007525 diag::err_explicit_instantiation_must_be_global :
7526 diag::warn_explicit_instantiation_must_be_global_0x)
7527 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007528 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007529 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007530}
7531
7532/// \brief Determine whether the given scope specifier has a template-id in it.
7533static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
7534 if (!SS.isSet())
7535 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007536
Richard Smith050d2612011-10-18 02:28:33 +00007537 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007538 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007539 // or a static data member of a class template specialization, the name of
7540 // the class template specialization in the qualified-id for the member
7541 // name shall be a simple-template-id.
7542 //
7543 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00007544 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
7545 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00007546 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00007547 if (isa<TemplateSpecializationType>(T))
7548 return true;
7549
7550 return false;
7551}
7552
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00007553/// Make a dllexport or dllimport attr on a class template specialization take
7554/// effect.
7555static void dllExportImportClassTemplateSpecialization(
7556 Sema &S, ClassTemplateSpecializationDecl *Def) {
7557 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
7558 assert(A && "dllExportImportClassTemplateSpecialization called "
7559 "on Def without dllexport or dllimport");
7560
7561 // We reject explicit instantiations in class scope, so there should
7562 // never be any delayed exported classes to worry about.
7563 assert(S.DelayedDllExportClasses.empty() &&
7564 "delayed exports present at explicit instantiation");
7565 S.checkClassLevelDLLAttribute(Def);
7566
7567 // Propagate attribute to base class templates.
7568 for (auto &B : Def->bases()) {
7569 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
7570 B.getType()->getAsCXXRecordDecl()))
7571 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
7572 }
7573
7574 S.referenceDLLExportedClassMethods();
7575}
7576
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007577// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00007578DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007579Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007580 SourceLocation ExternLoc,
7581 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007582 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00007583 SourceLocation KWLoc,
7584 const CXXScopeSpec &SS,
7585 TemplateTy TemplateD,
7586 SourceLocation TemplateNameLoc,
7587 SourceLocation LAngleLoc,
7588 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00007589 SourceLocation RAngleLoc,
7590 AttributeList *Attr) {
7591 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00007592 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00007593 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00007594 // Check that the specialization uses the same tag kind as the
7595 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007596 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7597 assert(Kind != TTK_Enum &&
7598 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00007599
Richard Trieu265c3442016-04-05 21:13:54 +00007600 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
7601
7602 if (!ClassTemplate) {
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00007603 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
7604 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
Richard Trieu265c3442016-04-05 21:13:54 +00007605 Diag(TD->getLocation(), diag::note_previous_use);
Richard Smith392497b2013-06-22 22:03:31 +00007606 return true;
7607 }
7608
Douglas Gregord9034f02009-05-14 16:41:31 +00007609 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007610 Kind, /*isDefinition*/false, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00007611 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007612 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00007613 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007614 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007615 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007616 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00007617 diag::note_previous_use);
7618 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7619 }
7620
Douglas Gregore47f5a72009-10-14 23:41:34 +00007621 // C++0x [temp.explicit]p2:
7622 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007623 // definition and an explicit instantiation declaration. An explicit
7624 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00007625 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
7626 ? TSK_ExplicitInstantiationDefinition
7627 : TSK_ExplicitInstantiationDeclaration;
7628
7629 if (TSK == TSK_ExplicitInstantiationDeclaration) {
7630 // Check for dllexport class template instantiation declarations.
7631 for (AttributeList *A = Attr; A; A = A->getNext()) {
7632 if (A->getKind() == AttributeList::AT_DLLExport) {
7633 Diag(ExternLoc,
7634 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7635 Diag(A->getLoc(), diag::note_attribute);
7636 break;
7637 }
7638 }
7639
7640 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
7641 Diag(ExternLoc,
7642 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7643 Diag(A->getLocation(), diag::note_attribute);
7644 }
7645 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007646
Hans Wennborga86a83b2016-05-26 19:42:56 +00007647 // In MSVC mode, dllimported explicit instantiation definitions are treated as
7648 // instantiation declarations for most purposes.
7649 bool DLLImportExplicitInstantiationDef = false;
7650 if (TSK == TSK_ExplicitInstantiationDefinition &&
7651 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7652 // Check for dllimport class template instantiation definitions.
7653 bool DLLImport =
7654 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
7655 for (AttributeList *A = Attr; A; A = A->getNext()) {
7656 if (A->getKind() == AttributeList::AT_DLLImport)
7657 DLLImport = true;
7658 if (A->getKind() == AttributeList::AT_DLLExport) {
7659 // dllexport trumps dllimport here.
7660 DLLImport = false;
7661 break;
7662 }
7663 }
7664 if (DLLImport) {
7665 TSK = TSK_ExplicitInstantiationDeclaration;
7666 DLLImportExplicitInstantiationDef = true;
7667 }
7668 }
7669
Douglas Gregora1f49972009-05-13 00:25:59 +00007670 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00007671 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00007672 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00007673
7674 // Check that the template argument list is well-formed for this
7675 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007676 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007677 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7678 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00007679 return true;
7680
Douglas Gregora1f49972009-05-13 00:25:59 +00007681 // Find the class template specialization declaration that
7682 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00007683 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007684 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00007685 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00007686
Abramo Bagnara8075c852010-06-12 07:44:57 +00007687 TemplateSpecializationKind PrevDecl_TSK
7688 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
7689
Douglas Gregor54888652009-10-07 00:13:32 +00007690 // C++0x [temp.explicit]p2:
7691 // [...] An explicit instantiation shall appear in an enclosing
7692 // namespace of its template. [...]
7693 //
7694 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007695 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
7696 SS.isSet()))
7697 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007698
Craig Topperc3ec1492014-05-26 06:22:03 +00007699 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007700
Abramo Bagnara8075c852010-06-12 07:44:57 +00007701 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00007702 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00007703 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007704 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00007705 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007706 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00007707 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00007708
Abramo Bagnara8075c852010-06-12 07:44:57 +00007709 // Even though HasNoEffect == true means that this explicit instantiation
7710 // has no effect on semantics, we go on to put its syntax in the AST.
7711
7712 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
7713 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007714 // Since the only prior class template specialization with these
7715 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00007716 // declaration node as our own, updating the source location
7717 // for the template name to reflect our new declaration.
7718 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007719 Specialization = PrevDecl;
7720 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007721 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007722 }
Hans Wennborga86a83b2016-05-26 19:42:56 +00007723
7724 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
7725 DLLImportExplicitInstantiationDef) {
7726 // The new specialization might add a dllimport attribute.
7727 HasNoEffect = false;
7728 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00007729 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00007730
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007731 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00007732 // Create a new class template specialization declaration node for
7733 // this explicit specialization.
7734 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007735 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00007736 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007737 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007738 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007739 Converted,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00007740 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00007741 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00007742
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007743 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007744 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007745 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007746 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007747 }
7748
7749 // Build the fully-sugared type for this explicit instantiation as
7750 // the user wrote in the explicit instantiation itself. This means
7751 // that we'll pretty-print the type retrieved from the
7752 // specialization's declaration the way that the user actually wrote
7753 // the explicit instantiation, rather than formatting the name based
7754 // on the "canonical" representation used to store the template
7755 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007756 TypeSourceInfo *WrittenTy
7757 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7758 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00007759 Context.getTypeDeclType(Specialization));
7760 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00007761
Abramo Bagnara8075c852010-06-12 07:44:57 +00007762 // Set source locations for keywords.
7763 Specialization->setExternLoc(ExternLoc);
7764 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00007765 Specialization->setBraceRange(SourceRange());
Abramo Bagnara8075c852010-06-12 07:44:57 +00007766
Rafael Espindola0b062072012-01-03 06:04:21 +00007767 if (Attr)
7768 ProcessDeclAttributeList(S, Specialization, Attr);
7769
Abramo Bagnara8075c852010-06-12 07:44:57 +00007770 // Add the explicit instantiation into its lexical context. However,
7771 // since explicit instantiations are never found by name lookup, we
7772 // just put it into the declaration context directly.
7773 Specialization->setLexicalDeclContext(CurContext);
7774 CurContext->addDecl(Specialization);
7775
7776 // Syntax is now OK, so return if it has no other effect on semantics.
7777 if (HasNoEffect) {
7778 // Set the template specialization kind.
7779 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00007780 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00007781 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007782
7783 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00007784 // A definition of a class template or class member template
7785 // shall be in scope at the point of the explicit instantiation of
7786 // the class template or class member template.
7787 //
7788 // This check comes when we actually try to perform the
7789 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00007790 ClassTemplateSpecializationDecl *Def
7791 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007792 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007793 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00007794 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007795 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007796 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007797 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
7798 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007799
Douglas Gregor1d957a32009-10-27 18:42:08 +00007800 // Instantiate the members of this class template specialization.
7801 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007802 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00007803 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007804 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007805 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
7806 // TSK_ExplicitInstantiationDefinition
7807 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborga86a83b2016-05-26 19:42:56 +00007808 (TSK == TSK_ExplicitInstantiationDefinition ||
7809 DLLImportExplicitInstantiationDef)) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00007810 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007811 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007812
Hans Wennborgc0875502015-06-09 00:39:05 +00007813 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
Shoaib Meenaiab3f96c2016-11-09 23:52:20 +00007814 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
7815 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
Hans Wennborgc0875502015-06-09 00:39:05 +00007816 // In the MS ABI, an explicit instantiation definition can add a dll
7817 // attribute to a template with a previous instantiation declaration.
7818 // MinGW doesn't allow this.
Hans Wennborg17f9b442015-05-27 00:06:45 +00007819 auto *A = cast<InheritableAttr>(
7820 getDLLAttr(Specialization)->clone(getASTContext()));
7821 A->setInherited(true);
7822 Def->addAttr(A);
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00007823 dllExportImportClassTemplateSpecialization(*this, Def);
Hans Wennborg17f9b442015-05-27 00:06:45 +00007824 }
7825 }
7826
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00007827 // Fix a TSK_ImplicitInstantiation followed by a
7828 // TSK_ExplicitInstantiationDefinition
7829 if (Old_TSK == TSK_ImplicitInstantiation &&
7830 Specialization->hasAttr<DLLExportAttr>() &&
7831 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
7832 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
7833 // In the MS ABI, an explicit instantiation definition can add a dll
7834 // attribute to a template with a previous implicit instantiation.
7835 // MinGW doesn't allow this. We limit clang to only adding dllexport, to
7836 // avoid potentially strange codegen behavior. For example, if we extend
7837 // this conditional to dllimport, and we have a source file calling a
7838 // method on an implicitly instantiated template class instance and then
7839 // declaring a dllimport explicit instantiation definition for the same
7840 // template class, the codegen for the method call will not respect the
7841 // dllimport, while it will with cl. The Def will already have the DLL
7842 // attribute, since the Def and Specialization will be the same in the
7843 // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
7844 // attribute to the Specialization; we just need to make it take effect.
7845 assert(Def == Specialization &&
7846 "Def and Specialization should match for implicit instantiation");
7847 dllExportImportClassTemplateSpecialization(*this, Def);
7848 }
7849
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00007850 // Set the template specialization kind. Make sure it is set before
7851 // instantiating the members which will trigger ASTConsumer callbacks.
7852 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregor12e49d32009-10-15 22:53:21 +00007853 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00007854 } else {
7855
7856 // Set the template specialization kind.
7857 Specialization->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007858 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007859
John McCall48871652010-08-21 09:40:31 +00007860 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00007861}
7862
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007863// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00007864DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007865Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007866 SourceLocation ExternLoc,
7867 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007868 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007869 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007870 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007871 IdentifierInfo *Name,
7872 SourceLocation NameLoc,
7873 AttributeList *Attr) {
7874
Douglas Gregord6ab8742009-05-28 23:31:59 +00007875 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00007876 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00007877 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00007878 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00007879 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007880 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00007881 SourceLocation(), false, TypeResult(),
7882 /*IsTypeSpecifier*/false);
John McCall7f41d982009-09-11 04:59:25 +00007883 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
7884
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007885 if (!TagD)
7886 return true;
7887
John McCall48871652010-08-21 09:40:31 +00007888 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00007889 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007890
Douglas Gregorb8006faf2009-05-27 17:30:49 +00007891 if (Tag->isInvalidDecl())
7892 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007893
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007894 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
7895 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
7896 if (!Pattern) {
7897 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
7898 << Context.getTypeDeclType(Record);
7899 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
7900 return true;
7901 }
7902
Douglas Gregore47f5a72009-10-14 23:41:34 +00007903 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007904 // If the explicit instantiation is for a class or member class, the
7905 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00007906 // simple-template-id.
7907 //
7908 // C++98 has the same restriction, just worded differently.
7909 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00007910 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007911 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007912
Douglas Gregore47f5a72009-10-14 23:41:34 +00007913 // C++0x [temp.explicit]p2:
7914 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007915 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00007916 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00007917 TemplateSpecializationKind TSK
7918 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7919 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007920
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007921 // C++0x [temp.explicit]p2:
7922 // [...] An explicit instantiation shall appear in an enclosing
7923 // namespace of its template. [...]
7924 //
7925 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007926 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007927
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007928 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007929 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00007930 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007931 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00007932 PrevDecl = Record;
7933 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007934 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007935 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007936 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007937 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007938 PrevDecl,
7939 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007940 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007941 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007942 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00007943 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007944 return TagD;
7945 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007946
Douglas Gregor12e49d32009-10-15 22:53:21 +00007947 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007948 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007949 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00007950 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007951 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00007952 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007953 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007954 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00007955 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00007956 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
7957 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00007958 Diag(Pattern->getLocation(), diag::note_forward_declaration)
7959 << Pattern;
7960 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007961 } else {
7962 if (InstantiateClass(NameLoc, Record, Def,
7963 getTemplateInstantiationArgs(Record),
7964 TSK))
7965 return true;
7966
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007967 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00007968 if (!RecordDef)
7969 return true;
7970 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007971 }
7972
Douglas Gregor1d957a32009-10-27 18:42:08 +00007973 // Instantiate all of the members of the class.
7974 InstantiateClassMembers(NameLoc, RecordDef,
7975 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007976
Douglas Gregor88d292c2010-05-13 16:44:06 +00007977 if (TSK == TSK_ExplicitInstantiationDefinition)
7978 MarkVTableUsed(NameLoc, RecordDef, true);
7979
Mike Stump87c57ac2009-05-16 07:39:55 +00007980 // FIXME: We don't have any representation for explicit instantiations of
7981 // member classes. Such a representation is not needed for compilation, but it
7982 // should be available for clients that want to see all of the declarations in
7983 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007984 return TagD;
7985}
7986
John McCallfaf5fb42010-08-26 23:41:50 +00007987DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
7988 SourceLocation ExternLoc,
7989 SourceLocation TemplateLoc,
7990 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007991 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007992 // TODO: check if/when DNInfo should replace Name.
7993 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7994 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00007995 if (!Name) {
7996 if (!D.isInvalidType())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007997 Diag(D.getDeclSpec().getLocStart(),
Douglas Gregor450f00842009-09-25 18:43:00 +00007998 diag::err_explicit_instantiation_requires_name)
7999 << D.getDeclSpec().getSourceRange()
8000 << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008001
Douglas Gregor450f00842009-09-25 18:43:00 +00008002 return true;
8003 }
8004
8005 // The scope passed in may not be a decl scope. Zip up the scope tree until
8006 // we find one that is.
8007 while ((S->getFlags() & Scope::DeclScope) == 0 ||
8008 (S->getFlags() & Scope::TemplateParamScope) != 0)
8009 S = S->getParent();
8010
8011 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00008012 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
8013 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00008014 if (R.isNull())
8015 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008016
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008017 // C++ [dcl.stc]p1:
Simon Pilgrim6905d222016-12-30 22:55:33 +00008018 // A storage-class-specifier shall not be specified in [...] an explicit
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008019 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00008020 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00008021 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
8022 << Name;
8023 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008024 } else if (D.getDeclSpec().getStorageClassSpec()
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008025 != DeclSpec::SCS_unspecified) {
8026 // Complain about then remove the storage class specifier.
8027 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
8028 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Simon Pilgrim6905d222016-12-30 22:55:33 +00008029
Douglas Gregor781ba6e2011-05-21 18:53:30 +00008030 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00008031 }
8032
Douglas Gregor3c74d412009-10-14 20:14:33 +00008033 // C++0x [temp.explicit]p1:
8034 // [...] An explicit instantiation of a function template shall not use the
8035 // inline or constexpr specifiers.
8036 // Presumably, this also applies to member functions of class templates as
8037 // well.
Richard Smith83c19292011-10-18 03:44:03 +00008038 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008039 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008040 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00008041 diag::err_explicit_instantiation_inline :
8042 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00008043 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00008044 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00008045 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
8046 // not already specified.
8047 Diag(D.getDeclSpec().getConstexprSpecLoc(),
8048 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008049
Nathan Wilsonde498452016-02-08 05:34:00 +00008050 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8051 // applied only to the definition of a function template or variable template,
8052 // declared in namespace scope.
8053 if (D.getDeclSpec().isConceptSpecified()) {
8054 Diag(D.getDeclSpec().getConceptSpecLoc(),
8055 diag::err_concept_specified_specialization) << 0;
8056 return true;
8057 }
8058
Douglas Gregore47f5a72009-10-14 23:41:34 +00008059 // C++0x [temp.explicit]p2:
8060 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008061 // definition and an explicit instantiation declaration. An explicit
8062 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00008063 TemplateSpecializationKind TSK
8064 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8065 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008066
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008067 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00008068 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00008069
8070 if (!R->isFunctionType()) {
8071 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008072 // A [...] static data member of a class template can be explicitly
8073 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00008074 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00008075 // C++1y [temp.explicit]p1:
8076 // A [...] variable [...] template specialization can be explicitly
8077 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00008078 if (Previous.isAmbiguous())
8079 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008080
John McCall67c00872009-12-02 08:25:40 +00008081 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00008082 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008083
Larisse Voufo39a1e502013-08-06 01:03:05 +00008084 if (!PrevTemplate) {
8085 if (!Prev || !Prev->isStaticDataMember()) {
8086 // We expect to see a data data member here.
8087 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
8088 << Name;
8089 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
8090 P != PEnd; ++P)
8091 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
8092 return true;
8093 }
8094
8095 if (!Prev->getInstantiatedFromStaticDataMember()) {
8096 // FIXME: Check for explicit specialization?
8097 Diag(D.getIdentifierLoc(),
8098 diag::err_explicit_instantiation_data_member_not_instantiated)
8099 << Prev;
8100 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
8101 // FIXME: Can we provide a note showing where this was declared?
8102 return true;
8103 }
8104 } else {
8105 // Explicitly instantiate a variable template.
8106
8107 // C++1y [dcl.spec.auto]p6:
8108 // ... A program that uses auto or decltype(auto) in a context not
8109 // explicitly allowed in this section is ill-formed.
8110 //
8111 // This includes auto-typed variable template instantiations.
8112 if (R->isUndeducedType()) {
8113 Diag(T->getTypeLoc().getLocStart(),
8114 diag::err_auto_not_allowed_var_inst);
8115 return true;
8116 }
8117
Richard Smithef985ac2013-09-18 02:10:12 +00008118 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
8119 // C++1y [temp.explicit]p3:
8120 // If the explicit instantiation is for a variable, the unqualified-id
8121 // in the declaration shall be a template-id.
8122 Diag(D.getIdentifierLoc(),
8123 diag::err_explicit_instantiation_without_template_id)
8124 << PrevTemplate;
8125 Diag(PrevTemplate->getLocation(),
8126 diag::note_explicit_instantiation_here);
8127 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00008128 }
8129
Nathan Wilson83839122016-04-09 02:55:27 +00008130 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
8131 // explicit instantiation (14.8.2) [...] of a concept definition.
8132 if (PrevTemplate->isConcept()) {
8133 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
8134 << 1 /*variable*/ << 0 /*explicitly instantiated*/;
8135 Diag(PrevTemplate->getLocation(), diag::note_previous_declaration);
8136 return true;
8137 }
8138
Richard Smithef985ac2013-09-18 02:10:12 +00008139 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00008140 TemplateArgumentListInfo TemplateArgs =
8141 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00008142
Larisse Voufo39a1e502013-08-06 01:03:05 +00008143 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
8144 D.getIdentifierLoc(), TemplateArgs);
8145 if (Res.isInvalid())
8146 return true;
8147
8148 // Ignore access control bits, we don't need them for redeclaration
8149 // checking.
8150 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00008151 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008152
Douglas Gregore47f5a72009-10-14 23:41:34 +00008153 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008154 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008155 // or a static data member of a class template specialization, the name of
8156 // the class template specialization in the qualified-id for the member
8157 // name shall be a simple-template-id.
8158 //
8159 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00008160 //
Richard Smith5977d872013-09-18 21:55:14 +00008161 // This does not apply to variable template specializations, where the
8162 // template-id is in the unqualified-id instead.
8163 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008164 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00008165 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008166 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008167
Douglas Gregore47f5a72009-10-14 23:41:34 +00008168 // Check the scope of this explicit instantiation.
8169 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008170
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008171 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00008172 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
8173 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00008174 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008175 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00008176 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008177 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008178
Larisse Voufo39a1e502013-08-06 01:03:05 +00008179 if (!HasNoEffect) {
8180 // Instantiate static data member or variable template.
8181
8182 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
8183 if (PrevTemplate) {
8184 // Merge attributes.
8185 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
8186 ProcessDeclAttributeList(S, Prev, Attr);
8187 }
8188 if (TSK == TSK_ExplicitInstantiationDefinition)
8189 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
8190 }
8191
8192 // Check the new variable specialization against the parsed input.
8193 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
8194 Diag(T->getTypeLoc().getLocStart(),
8195 diag::err_invalid_var_template_spec_type)
8196 << 0 << PrevTemplate << R << Prev->getType();
8197 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
8198 << 2 << PrevTemplate->getDeclName();
8199 return true;
8200 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008201
Douglas Gregor450f00842009-09-25 18:43:00 +00008202 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00008203 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008204 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008205
8206 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00008207 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00008208 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00008209 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00008210 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00008211 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00008212 HasExplicitTemplateArgs = true;
8213 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008214
Douglas Gregor450f00842009-09-25 18:43:00 +00008215 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008216 // A [...] function [...] can be explicitly instantiated from its template.
8217 // A member function [...] of a class template can be explicitly
8218 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00008219 // template.
John McCall58cc69d2010-01-27 01:50:18 +00008220 UnresolvedSet<8> Matches;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008221 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
Larisse Voufo98b20f12013-07-19 23:00:19 +00008222 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00008223 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
8224 P != PEnd; ++P) {
8225 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00008226 if (!HasExplicitTemplateArgs) {
8227 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Richard Smithbaa47832016-12-01 02:11:49 +00008228 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
8229 /*AdjustExceptionSpec*/true);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00008230 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
Douglas Gregord90fd522009-09-25 21:45:23 +00008231 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00008232
John McCall58cc69d2010-01-27 01:50:18 +00008233 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00008234 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
8235 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00008236 }
Douglas Gregor450f00842009-09-25 18:43:00 +00008237 }
8238 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008239
Douglas Gregor450f00842009-09-25 18:43:00 +00008240 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
8241 if (!FunTmpl)
8242 continue;
8243
Larisse Voufo98b20f12013-07-19 23:00:19 +00008244 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00008245 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008246 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008247 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00008248 (HasExplicitTemplateArgs ? &TemplateArgs
8249 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00008250 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008251 // Keep track of almost-matches.
8252 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +00008253 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +00008254 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00008255 (void)TDK;
8256 continue;
8257 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008258
Artem Belevich64135c32016-12-08 19:38:13 +00008259 // Target attributes are part of the cuda function signature, so
8260 // the cuda target of the instantiated function must match that of its
8261 // template. Given that C++ template deduction does not take
8262 // target attributes into account, we reject candidates here that
8263 // have a different target.
8264 if (LangOpts.CUDA &&
8265 IdentifyCUDATarget(Specialization,
8266 /* IgnoreImplicitHDAttributes = */ true) !=
8267 IdentifyCUDATarget(Attr)) {
8268 FailedCandidates.addCandidate().set(
8269 P.getPair(), FunTmpl->getTemplatedDecl(),
8270 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
8271 continue;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008272 }
8273
John McCall58cc69d2010-01-27 01:50:18 +00008274 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00008275 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008276
Douglas Gregor450f00842009-09-25 18:43:00 +00008277 // Find the most specialized function template specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008278 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00008279 Matches.begin(), Matches.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00008280 D.getIdentifierLoc(),
8281 PDiag(diag::err_explicit_instantiation_not_known) << Name,
8282 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
8283 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00008284
John McCall58cc69d2010-01-27 01:50:18 +00008285 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00008286 return true;
John McCall58cc69d2010-01-27 01:50:18 +00008287
8288 // Ignore access control bits, we don't need them for redeclaration checking.
8289 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008290
Alexey Bataev73983912014-11-06 10:10:50 +00008291 // C++11 [except.spec]p4
8292 // In an explicit instantiation an exception-specification may be specified,
8293 // but is not required.
8294 // If an exception-specification is specified in an explicit instantiation
8295 // directive, it shall be compatible with the exception-specifications of
8296 // other declarations of that function.
8297 if (auto *FPT = R->getAs<FunctionProtoType>())
8298 if (FPT->hasExceptionSpec()) {
8299 unsigned DiagID =
8300 diag::err_mismatched_exception_spec_explicit_instantiation;
8301 if (getLangOpts().MicrosoftExt)
8302 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
8303 bool Result = CheckEquivalentExceptionSpec(
8304 PDiag(DiagID) << Specialization->getType(),
8305 PDiag(diag::note_explicit_instantiation_here),
8306 Specialization->getType()->getAs<FunctionProtoType>(),
8307 Specialization->getLocation(), FPT, D.getLocStart());
8308 // In Microsoft mode, mismatching exception specifications just cause a
8309 // warning.
8310 if (!getLangOpts().MicrosoftExt && Result)
8311 return true;
8312 }
8313
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008314 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008315 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00008316 diag::err_explicit_instantiation_member_function_not_instantiated)
8317 << Specialization
8318 << (Specialization->getTemplateSpecializationKind() ==
8319 TSK_ExplicitSpecialization);
8320 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
8321 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008322 }
8323
Douglas Gregorec9fd132012-01-14 16:38:05 +00008324 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00008325 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
8326 PrevDecl = Specialization;
8327
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008328 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00008329 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008330 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008331 PrevDecl,
8332 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008333 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008334 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008335 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008336
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008337 // FIXME: We may still want to build some representation of this
8338 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00008339 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00008340 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008341 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00008342
8343 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Rafael Espindola2aa7acf2012-01-04 05:40:59 +00008344 if (Attr)
8345 ProcessDeclAttributeList(S, Specialization, Attr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008346
Richard Smitheb36ddf2014-04-24 22:45:46 +00008347 if (Specialization->isDefined()) {
8348 // Let the ASTConsumer know that this function has been explicitly
8349 // instantiated now, and its linkage might have changed.
8350 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
8351 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00008352 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008353
Douglas Gregore47f5a72009-10-14 23:41:34 +00008354 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008355 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008356 // or a static data member of a class template specialization, the name of
8357 // the class template specialization in the qualified-id for the member
8358 // name shall be a simple-template-id.
8359 //
8360 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008361 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00008362 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008363 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00008364 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008365 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00008366 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008367 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008368
Nathan Wilson83839122016-04-09 02:55:27 +00008369 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
8370 // explicit instantiation (14.8.2) [...] of a concept definition.
8371 if (FunTmpl && FunTmpl->isConcept() &&
8372 !D.getDeclSpec().isConceptSpecified()) {
8373 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
8374 << 0 /*function*/ << 0 /*explicitly instantiated*/;
8375 Diag(FunTmpl->getLocation(), diag::note_previous_declaration);
8376 return true;
8377 }
8378
Douglas Gregore47f5a72009-10-14 23:41:34 +00008379 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008380 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregore47f5a72009-10-14 23:41:34 +00008381 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008382 D.getIdentifierLoc(),
Douglas Gregore47f5a72009-10-14 23:41:34 +00008383 D.getCXXScopeSpec().isSet());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008384
Douglas Gregor450f00842009-09-25 18:43:00 +00008385 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00008386 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008387}
8388
John McCallfaf5fb42010-08-26 23:41:50 +00008389TypeResult
John McCall7f41d982009-09-11 04:59:25 +00008390Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
8391 const CXXScopeSpec &SS, IdentifierInfo *Name,
8392 SourceLocation TagLoc, SourceLocation NameLoc) {
8393 // This has to hold, because SS is expected to be defined.
8394 assert(Name && "Expected a name in a dependent tag");
8395
Aaron Ballman4a979672014-01-03 13:56:08 +00008396 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00008397 if (!NNS)
8398 return true;
8399
Abramo Bagnara6150c882010-05-11 21:36:43 +00008400 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00008401
Douglas Gregorba41d012010-04-24 16:38:41 +00008402 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
8403 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00008404 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00008405 return true;
8406 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00008407
Douglas Gregore7c20652011-03-02 00:47:37 +00008408 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00008409 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00008410 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
Simon Pilgrim6905d222016-12-30 22:55:33 +00008411
Douglas Gregore7c20652011-03-02 00:47:37 +00008412 // Create type-source location information for this type.
8413 TypeLocBuilder TLB;
8414 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008415 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00008416 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8417 TL.setNameLoc(NameLoc);
8418 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00008419}
8420
John McCallfaf5fb42010-08-26 23:41:50 +00008421TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008422Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
8423 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00008424 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008425 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00008426 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008427
Richard Smith0bf8a4922011-10-18 20:49:44 +00008428 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8429 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008430 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008431 diag::warn_cxx98_compat_typename_outside_of_template :
8432 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008433 << FixItHint::CreateRemoval(TypenameLoc);
8434
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008435 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00008436 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
8437 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00008438 if (T.isNull())
8439 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008440
8441 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8442 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00008443 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008444 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008445 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00008446 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00008447 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00008448 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008449 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008450 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00008451 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00008452 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008453
John McCallba7bf592010-08-24 05:47:05 +00008454 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00008455}
8456
John McCallfaf5fb42010-08-26 23:41:50 +00008457TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008458Sema::ActOnTypenameType(Scope *S,
8459 SourceLocation TypenameLoc,
8460 const CXXScopeSpec &SS,
8461 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00008462 TemplateTy TemplateIn,
8463 SourceLocation TemplateNameLoc,
8464 SourceLocation LAngleLoc,
8465 ASTTemplateArgsPtr TemplateArgsIn,
8466 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00008467 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8468 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008469 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008470 diag::warn_cxx98_compat_typename_outside_of_template :
8471 diag::ext_typename_outside_of_template)
8472 << FixItHint::CreateRemoval(TypenameLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00008473
Douglas Gregorb09518c2011-02-27 22:46:49 +00008474 // Translate the parser's template argument list in our AST format.
8475 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
8476 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00008477
Douglas Gregorb09518c2011-02-27 22:46:49 +00008478 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008479 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
8480 // Construct a dependent template specialization type.
8481 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00008482 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008483 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
8484 DTN->getQualifier(),
8485 DTN->getIdentifier(),
8486 TemplateArgs);
Simon Pilgrim6905d222016-12-30 22:55:33 +00008487
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008488 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00008489 TypeLocBuilder Builder;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008490 DependentTemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008491 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008492 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
8493 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00008494 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008495 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008496 SpecTL.setLAngleLoc(LAngleLoc);
8497 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008498 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8499 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008500 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00008501 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00008502
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008503 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
8504 if (T.isNull())
8505 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008506
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008507 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00008508 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008509 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008510 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008511 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
8512 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008513 SpecTL.setLAngleLoc(LAngleLoc);
8514 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008515 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8516 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Simon Pilgrim6905d222016-12-30 22:55:33 +00008517
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008518 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
8519 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008520 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008521 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Simon Pilgrim6905d222016-12-30 22:55:33 +00008522
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008523 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
8524 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00008525}
8526
Douglas Gregorb09518c2011-02-27 22:46:49 +00008527
Richard Smith6f8d2c62012-05-09 05:17:00 +00008528/// Determine whether this failed name lookup should be treated as being
8529/// disabled by a usage of std::enable_if.
8530static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
8531 SourceRange &CondRange) {
8532 // We must be looking for a ::type...
8533 if (!II.isStr("type"))
8534 return false;
8535
8536 // ... within an explicitly-written template specialization...
8537 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
8538 return false;
8539 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00008540 TemplateSpecializationTypeLoc EnableIfTSTLoc =
8541 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
8542 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00008543 return false;
8544 const TemplateSpecializationType *EnableIfTST =
David Blaikie6adc78e2013-02-18 22:06:02 +00008545 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
Richard Smith6f8d2c62012-05-09 05:17:00 +00008546
8547 // ... which names a complete class template declaration...
8548 const TemplateDecl *EnableIfDecl =
8549 EnableIfTST->getTemplateName().getAsTemplateDecl();
8550 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
8551 return false;
8552
8553 // ... called "enable_if".
8554 const IdentifierInfo *EnableIfII =
8555 EnableIfDecl->getDeclName().getAsIdentifierInfo();
8556 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
8557 return false;
8558
8559 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00008560 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Richard Smith6f8d2c62012-05-09 05:17:00 +00008561 return true;
8562}
8563
Douglas Gregor333489b2009-03-27 23:10:48 +00008564/// \brief Build the type that describes a C++ typename specifier,
8565/// e.g., "typename T::type".
8566QualType
Simon Pilgrim6905d222016-12-30 22:55:33 +00008567Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008568 SourceLocation KeywordLoc,
Simon Pilgrim6905d222016-12-30 22:55:33 +00008569 NestedNameSpecifierLoc QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008570 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00008571 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00008572 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008573 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00008574
John McCall0b66eb32010-05-01 00:40:08 +00008575 DeclContext *Ctx = computeDeclContext(SS);
8576 if (!Ctx) {
8577 // If the nested-name-specifier is dependent and couldn't be
8578 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008579 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
Simon Pilgrim6905d222016-12-30 22:55:33 +00008580 return Context.getDependentNameType(Keyword,
8581 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008582 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008583 }
Douglas Gregor333489b2009-03-27 23:10:48 +00008584
John McCall0b66eb32010-05-01 00:40:08 +00008585 // If the nested-name-specifier refers to the current instantiation,
8586 // the "typename" keyword itself is superfluous. In C++03, the
8587 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
8588 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00008589 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008590
John McCall0b66eb32010-05-01 00:40:08 +00008591 if (RequireCompleteDeclContext(SS, Ctx))
8592 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00008593
8594 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00008595 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00008596 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00008597 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00008598 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00008599 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00008600 case LookupResult::NotFound: {
8601 // If we're looking up 'type' within a template named 'enable_if', produce
8602 // a more specific diagnostic.
8603 SourceRange CondRange;
8604 if (isEnableIf(QualifierLoc, II, CondRange)) {
8605 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
8606 << Ctx << CondRange;
8607 return QualType();
8608 }
8609
Douglas Gregore40876a2009-10-13 21:16:44 +00008610 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00008611 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008612 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008613
8614 case LookupResult::FoundUnresolvedValue: {
8615 // We found a using declaration that is a value. Most likely, the using
8616 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008617 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008618 IILoc);
8619 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
8620 << Name << Ctx << FullRange;
8621 if (UnresolvedUsingValueDecl *Using
8622 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008623 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008624 Diag(Loc, diag::note_using_value_decl_missing_typename)
8625 << FixItHint::CreateInsertion(Loc, "typename ");
8626 }
8627 }
8628 // Fall through to create a dependent typename type, from which we can recover
8629 // better.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008630
Douglas Gregord0d2ee02010-01-15 01:44:47 +00008631 case LookupResult::NotFoundInCurrentInstantiation:
8632 // Okay, it's a member of an unknown instantiation.
Simon Pilgrim6905d222016-12-30 22:55:33 +00008633 return Context.getDependentNameType(Keyword,
8634 QualifierLoc.getNestedNameSpecifier(),
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008635 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00008636
8637 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008638 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00008639 // We found a type. Build an ElaboratedType, since the
8640 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00008641 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Simon Pilgrim6905d222016-12-30 22:55:33 +00008642 return Context.getElaboratedType(ETK_Typename,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008643 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00008644 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00008645 }
8646
8647 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00008648 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00008649 break;
8650
8651 case LookupResult::FoundOverloaded:
8652 DiagID = diag::err_typename_nested_not_type;
8653 Referenced = *Result.begin();
8654 break;
8655
John McCall6538c932009-10-10 05:48:19 +00008656 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00008657 return QualType();
8658 }
8659
8660 // If we get here, it's because name lookup did not find a
8661 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008662 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00008663 IILoc);
8664 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00008665 if (Referenced)
8666 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
8667 << Name;
8668 return QualType();
8669}
Douglas Gregor15acfb92009-08-06 16:20:37 +00008670
8671namespace {
8672 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00008673 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00008674 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00008675 SourceLocation Loc;
8676 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00008677
Douglas Gregor15acfb92009-08-06 16:20:37 +00008678 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00008679 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008680
Mike Stump11289f42009-09-09 15:08:12 +00008681 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008682 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00008683 DeclarationName Entity)
8684 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00008685 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00008686
8687 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00008688 /// transformed.
8689 ///
8690 /// For the purposes of type reconstruction, a type has already been
8691 /// transformed if it is NULL or if it is not dependent.
8692 bool AlreadyTransformed(QualType T) {
8693 return T.isNull() || !T->isDependentType();
8694 }
Mike Stump11289f42009-09-09 15:08:12 +00008695
8696 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00008697 /// rebuilt.
8698 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00008699
Douglas Gregor15acfb92009-08-06 16:20:37 +00008700 /// \brief Returns the name of the entity whose type is being rebuilt.
8701 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00008702
Douglas Gregoref6ab412009-10-27 06:26:26 +00008703 /// \brief Sets the "base" location and entity when that
8704 /// information is known based on another transformation.
8705 void setBase(SourceLocation Loc, DeclarationName Entity) {
8706 this->Loc = Loc;
8707 this->Entity = Entity;
8708 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00008709
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00008710 ExprResult TransformLambdaExpr(LambdaExpr *E) {
8711 // Lambdas never need to be transformed.
8712 return E;
8713 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00008714 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008715} // end anonymous namespace
Douglas Gregor15acfb92009-08-06 16:20:37 +00008716
Douglas Gregor15acfb92009-08-06 16:20:37 +00008717/// \brief Rebuilds a type within the context of the current instantiation.
8718///
Mike Stump11289f42009-09-09 15:08:12 +00008719/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00008720/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00008721/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00008722/// partial specialization thereof). This routine will rebuild that type now
8723/// that we have entered the declarator's scope, which may produce different
8724/// canonical types, e.g.,
8725///
8726/// \code
8727/// template<typename T>
8728/// struct X {
8729/// typedef T* pointer;
8730/// pointer data();
8731/// };
8732///
8733/// template<typename T>
8734/// typename X<T>::pointer X<T>::data() { ... }
8735/// \endcode
8736///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00008737/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008738/// since we do not know that we can look into X<T> when we parsed the type.
8739/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00008740/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00008741/// as the canonical type of T*, allowing the return types of the out-of-line
8742/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00008743TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8744 SourceLocation Loc,
8745 DeclarationName Name) {
8746 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00008747 return T;
Mike Stump11289f42009-09-09 15:08:12 +00008748
Douglas Gregor15acfb92009-08-06 16:20:37 +00008749 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
8750 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00008751}
Douglas Gregorbe999392009-09-15 16:23:51 +00008752
John McCalldadc5752010-08-24 06:29:42 +00008753ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00008754 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
8755 DeclarationName());
8756 return Rebuilder.TransformExpr(E);
8757}
8758
John McCall99b2fe52010-04-29 23:50:39 +00008759bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Simon Pilgrim6905d222016-12-30 22:55:33 +00008760 if (SS.isInvalid())
Douglas Gregor10176412011-02-25 16:07:42 +00008761 return true;
John McCall2408e322010-04-27 00:57:59 +00008762
Douglas Gregor10176412011-02-25 16:07:42 +00008763 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00008764 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
8765 DeclarationName());
Simon Pilgrim6905d222016-12-30 22:55:33 +00008766 NestedNameSpecifierLoc Rebuilt
Douglas Gregor10176412011-02-25 16:07:42 +00008767 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
Simon Pilgrim6905d222016-12-30 22:55:33 +00008768 if (!Rebuilt)
Douglas Gregor10176412011-02-25 16:07:42 +00008769 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008770
Douglas Gregor10176412011-02-25 16:07:42 +00008771 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00008772 return false;
John McCall2408e322010-04-27 00:57:59 +00008773}
8774
Douglas Gregor041b0842011-10-14 15:31:12 +00008775/// \brief Rebuild the template parameters now that we know we're in a current
8776/// instantiation.
8777bool Sema::RebuildTemplateParamsInCurrentInstantiation(
8778 TemplateParameterList *Params) {
8779 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8780 Decl *Param = Params->getParam(I);
Simon Pilgrim6905d222016-12-30 22:55:33 +00008781
Douglas Gregor041b0842011-10-14 15:31:12 +00008782 // There is nothing to rebuild in a type parameter.
8783 if (isa<TemplateTypeParmDecl>(Param))
8784 continue;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008785
Douglas Gregor041b0842011-10-14 15:31:12 +00008786 // Rebuild the template parameter list of a template template parameter.
Simon Pilgrim6905d222016-12-30 22:55:33 +00008787 if (TemplateTemplateParmDecl *TTP
Douglas Gregor041b0842011-10-14 15:31:12 +00008788 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
8789 if (RebuildTemplateParamsInCurrentInstantiation(
8790 TTP->getTemplateParameters()))
8791 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008792
Douglas Gregor041b0842011-10-14 15:31:12 +00008793 continue;
8794 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00008795
Douglas Gregor041b0842011-10-14 15:31:12 +00008796 // Rebuild the type of a non-type template parameter.
8797 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
Simon Pilgrim6905d222016-12-30 22:55:33 +00008798 TypeSourceInfo *NewTSI
8799 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
8800 NTTP->getLocation(),
Douglas Gregor041b0842011-10-14 15:31:12 +00008801 NTTP->getDeclName());
8802 if (!NewTSI)
8803 return true;
Simon Pilgrim6905d222016-12-30 22:55:33 +00008804
Douglas Gregor041b0842011-10-14 15:31:12 +00008805 if (NewTSI != NTTP->getTypeSourceInfo()) {
8806 NTTP->setTypeSourceInfo(NewTSI);
8807 NTTP->setType(NewTSI->getType());
8808 }
8809 }
Simon Pilgrim6905d222016-12-30 22:55:33 +00008810
Douglas Gregor041b0842011-10-14 15:31:12 +00008811 return false;
8812}
8813
Douglas Gregorbe999392009-09-15 16:23:51 +00008814/// \brief Produces a formatted string that describes the binding of
8815/// template parameters to template arguments.
8816std::string
8817Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8818 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008819 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00008820}
8821
8822std::string
8823Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8824 const TemplateArgument *Args,
8825 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008826 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +00008827 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +00008828
Douglas Gregore62e6a02009-11-11 19:13:48 +00008829 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008830 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008831
Douglas Gregorbe999392009-09-15 16:23:51 +00008832 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00008833 if (I >= NumArgs)
8834 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008835
Douglas Gregorbe999392009-09-15 16:23:51 +00008836 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008837 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +00008838 else
Douglas Gregor0192c232010-12-20 16:52:59 +00008839 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008840
Douglas Gregorbe999392009-09-15 16:23:51 +00008841 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +00008842 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +00008843 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +00008844 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +00008845 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008846
Douglas Gregor0192c232010-12-20 16:52:59 +00008847 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +00008848 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +00008849 }
Douglas Gregor0192c232010-12-20 16:52:59 +00008850
8851 Out << ']';
8852 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +00008853}
Francois Pichet1c229c02011-04-22 22:18:13 +00008854
Richard Smithe40f2ba2013-08-07 21:41:30 +00008855void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
8856 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +00008857 if (!FD)
8858 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +00008859
Justin Lebar28f09c52016-10-10 16:26:08 +00008860 auto LPT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00008861
8862 // Take tokens to avoid allocations
8863 LPT->Toks.swap(Toks);
8864 LPT->D = FnD;
Justin Lebar28f09c52016-10-10 16:26:08 +00008865 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008866
8867 FD->setLateTemplateParsed(true);
8868}
8869
8870void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
8871 if (!FD)
8872 return;
8873 FD->setLateTemplateParsed(false);
8874}
Francois Pichet1c229c02011-04-22 22:18:13 +00008875
8876bool Sema::IsInsideALocalClassWithinATemplateFunction() {
8877 DeclContext *DC = CurContext;
8878
8879 while (DC) {
8880 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
8881 const FunctionDecl *FD = RD->isLocalClass();
8882 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
8883 } else if (DC->isTranslationUnit() || DC->isNamespace())
8884 return false;
8885
8886 DC = DC->getParent();
8887 }
8888 return false;
8889}
Richard Smith6739a102016-05-05 00:56:12 +00008890
Benjamin Kramera0a13c32016-08-06 11:21:04 +00008891namespace {
Richard Smith6739a102016-05-05 00:56:12 +00008892/// \brief Walk the path from which a declaration was instantiated, and check
8893/// that every explicit specialization along that path is visible. This enforces
8894/// C++ [temp.expl.spec]/6:
8895///
8896/// If a template, a member template or a member of a class template is
8897/// explicitly specialized then that specialization shall be declared before
8898/// the first use of that specialization that would cause an implicit
8899/// instantiation to take place, in every translation unit in which such a
8900/// use occurs; no diagnostic is required.
8901///
8902/// and also C++ [temp.class.spec]/1:
8903///
8904/// A partial specialization shall be declared before the first use of a
8905/// class template specialization that would make use of the partial
8906/// specialization as the result of an implicit or explicit instantiation
8907/// in every translation unit in which such a use occurs; no diagnostic is
8908/// required.
8909class ExplicitSpecializationVisibilityChecker {
8910 Sema &S;
8911 SourceLocation Loc;
8912 llvm::SmallVector<Module *, 8> Modules;
8913
8914public:
8915 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
8916 : S(S), Loc(Loc) {}
8917
8918 void check(NamedDecl *ND) {
8919 if (auto *FD = dyn_cast<FunctionDecl>(ND))
8920 return checkImpl(FD);
8921 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
8922 return checkImpl(RD);
8923 if (auto *VD = dyn_cast<VarDecl>(ND))
8924 return checkImpl(VD);
8925 if (auto *ED = dyn_cast<EnumDecl>(ND))
8926 return checkImpl(ED);
8927 }
8928
8929private:
8930 void diagnose(NamedDecl *D, bool IsPartialSpec) {
8931 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
8932 : Sema::MissingImportKind::ExplicitSpecialization;
8933 const bool Recover = true;
8934
8935 // If we got a custom set of modules (because only a subset of the
8936 // declarations are interesting), use them, otherwise let
8937 // diagnoseMissingImport intelligently pick some.
8938 if (Modules.empty())
8939 S.diagnoseMissingImport(Loc, D, Kind, Recover);
8940 else
8941 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
8942 }
8943
8944 // Check a specific declaration. There are three problematic cases:
8945 //
8946 // 1) The declaration is an explicit specialization of a template
8947 // specialization.
8948 // 2) The declaration is an explicit specialization of a member of an
8949 // templated class.
8950 // 3) The declaration is an instantiation of a template, and that template
8951 // is an explicit specialization of a member of a templated class.
8952 //
8953 // We don't need to go any deeper than that, as the instantiation of the
8954 // surrounding class / etc is not triggered by whatever triggered this
8955 // instantiation, and thus should be checked elsewhere.
8956 template<typename SpecDecl>
8957 void checkImpl(SpecDecl *Spec) {
8958 bool IsHiddenExplicitSpecialization = false;
8959 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
8960 IsHiddenExplicitSpecialization =
8961 Spec->getMemberSpecializationInfo()
8962 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
8963 : !S.hasVisibleDeclaration(Spec);
8964 } else {
8965 checkInstantiated(Spec);
8966 }
8967
8968 if (IsHiddenExplicitSpecialization)
8969 diagnose(Spec->getMostRecentDecl(), false);
8970 }
8971
8972 void checkInstantiated(FunctionDecl *FD) {
8973 if (auto *TD = FD->getPrimaryTemplate())
8974 checkTemplate(TD);
8975 }
8976
8977 void checkInstantiated(CXXRecordDecl *RD) {
8978 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
8979 if (!SD)
8980 return;
8981
8982 auto From = SD->getSpecializedTemplateOrPartial();
8983 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
8984 checkTemplate(TD);
8985 else if (auto *TD =
8986 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
8987 if (!S.hasVisibleDeclaration(TD))
8988 diagnose(TD, true);
8989 checkTemplate(TD);
8990 }
8991 }
8992
8993 void checkInstantiated(VarDecl *RD) {
8994 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
8995 if (!SD)
8996 return;
8997
8998 auto From = SD->getSpecializedTemplateOrPartial();
8999 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
9000 checkTemplate(TD);
9001 else if (auto *TD =
9002 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
9003 if (!S.hasVisibleDeclaration(TD))
9004 diagnose(TD, true);
9005 checkTemplate(TD);
9006 }
9007 }
9008
9009 void checkInstantiated(EnumDecl *FD) {}
9010
9011 template<typename TemplDecl>
9012 void checkTemplate(TemplDecl *TD) {
9013 if (TD->isMemberSpecialization()) {
9014 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
9015 diagnose(TD->getMostRecentDecl(), false);
9016 }
9017 }
9018};
Benjamin Kramera0a13c32016-08-06 11:21:04 +00009019} // end anonymous namespace
Richard Smith6739a102016-05-05 00:56:12 +00009020
9021void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
9022 if (!getLangOpts().Modules)
9023 return;
9024
9025 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
9026}
9027
9028/// \brief Check whether a template partial specialization that we've discovered
9029/// is hidden, and produce suitable diagnostics if so.
9030void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
9031 NamedDecl *Spec) {
9032 llvm::SmallVector<Module *, 8> Modules;
9033 if (!hasVisibleDeclaration(Spec, &Modules))
9034 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
9035 MissingImportKind::PartialSpecialization,
9036 /*Recover*/true);
9037}