blob: 941672c6e397a7f961f2240e11cad44c8078876d [file] [log] [blame]
Douglas Gregor5101c242008-12-05 18:15:24 +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.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregorfe1e1102009-02-27 19:31:52 +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"
Douglas Gregor5101c242008-12-05 18:15:24 +000021#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000022#include "clang/Basic/PartialDiagnostic.h"
David Majnemer763584d2014-02-06 10:59:19 +000023#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Sema/DeclSpec.h"
25#include "clang/Sema/Lookup.h"
26#include "clang/Sema/ParsedTemplate.h"
27#include "clang/Sema/Scope.h"
28#include "clang/Sema/SemaInternal.h"
29#include "clang/Sema/Template.h"
30#include "clang/Sema/TemplateDeduction.h"
Benjamin Kramere0513cb2012-01-30 16:17:39 +000031#include "llvm/ADT/SmallBitVector.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000032#include "llvm/ADT/SmallString.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000033#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000034using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000035using namespace sema;
Douglas Gregor5101c242008-12-05 18:15:24 +000036
John McCall9b72f892010-11-10 02:40:36 +000037// Exported for use by Parser.
38SourceRange
39clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
40 unsigned N) {
41 if (!N) return SourceRange();
42 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
43}
44
Douglas Gregorb7bfe792009-09-02 22:59:36 +000045/// \brief Determine whether the declaration found is acceptable as the name
46/// of a template and, if so, return that template declaration. Otherwise,
47/// returns NULL.
John McCalle9cccd82010-06-16 08:42:20 +000048static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000049 NamedDecl *Orig,
50 bool AllowFunctionTemplates) {
John McCalle9cccd82010-06-16 08:42:20 +000051 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +000052
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000053 if (isa<TemplateDecl>(D)) {
54 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +000055 return nullptr;
56
John McCalle9cccd82010-06-16 08:42:20 +000057 return Orig;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000058 }
Mike Stump11289f42009-09-09 15:08:12 +000059
Douglas Gregorb7bfe792009-09-02 22:59:36 +000060 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
61 // C++ [temp.local]p1:
62 // Like normal (non-template) classes, class templates have an
63 // injected-class-name (Clause 9). The injected-class-name
64 // can be used with or without a template-argument-list. When
65 // it is used without a template-argument-list, it is
66 // equivalent to the injected-class-name followed by the
67 // template-parameters of the class template enclosed in
68 // <>. When it is used with a template-argument-list, it
69 // refers to the specified class template specialization,
70 // which could be the current specialization or another
71 // specialization.
72 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000073 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000074 if (Record->getDescribedClassTemplate())
75 return Record->getDescribedClassTemplate();
76
77 if (ClassTemplateSpecializationDecl *Spec
78 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
79 return Spec->getSpecializedTemplate();
80 }
Mike Stump11289f42009-09-09 15:08:12 +000081
Craig Topperc3ec1492014-05-26 06:22:03 +000082 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +000083 }
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}
87
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000088void Sema::FilterAcceptableTemplateNames(LookupResult &R,
89 bool AllowFunctionTemplates) {
Douglas Gregor41f90302010-04-12 20:54:26 +000090 // The set of class templates we've already seen.
91 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCalle66edc12009-11-24 19:00:30 +000092 LookupResult::Filter filter = R.makeFilter();
93 while (filter.hasNext()) {
94 NamedDecl *Orig = filter.next();
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000095 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
96 AllowFunctionTemplates);
John McCalle66edc12009-11-24 19:00:30 +000097 if (!Repl)
98 filter.erase();
Douglas Gregor41f90302010-04-12 20:54:26 +000099 else if (Repl != Orig) {
100
101 // C++ [temp.local]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000102 // A lookup that finds an injected-class-name (10.2) can result in an
Douglas Gregor41f90302010-04-12 20:54:26 +0000103 // ambiguity in certain cases (for example, if it is found in more than
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000104 // one base class). If all of the injected-class-names that are found
105 // refer to specializations of the same class template, and if the name
Richard Smith3f1b5d02011-05-05 21:57:07 +0000106 // is used as a template-name, the reference refers to the class
107 // template itself and not a specialization thereof, and is not
Douglas Gregor41f90302010-04-12 20:54:26 +0000108 // ambiguous.
Douglas Gregor41f90302010-04-12 20:54:26 +0000109 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
David Blaikie82e95a32014-11-19 07:49:47 +0000110 if (!ClassTemplates.insert(ClassTmpl).second) {
Douglas Gregor41f90302010-04-12 20:54:26 +0000111 filter.erase();
112 continue;
113 }
John McCallbd8062d2010-08-13 07:02:08 +0000114
115 // FIXME: we promote access to public here as a workaround to
116 // the fact that LookupResult doesn't let us remember that we
117 // found this template through a particular injected class name,
118 // which means we end up doing nasty things to the invariants.
119 // Pretending that access is public is *much* safer.
120 filter.replace(Repl, AS_public);
Douglas Gregor41f90302010-04-12 20:54:26 +0000121 }
John McCalle66edc12009-11-24 19:00:30 +0000122 }
123 filter.done();
124}
125
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000126bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
127 bool AllowFunctionTemplates) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000128 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000129 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000130 return true;
131
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000132 return false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000133}
134
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000135TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000136 CXXScopeSpec &SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000137 bool hasTemplateKeyword,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000138 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +0000139 ParsedType ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000140 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000141 TemplateTy &TemplateResult,
142 bool &MemberOfUnknownSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000143 assert(getLangOpts().CPlusPlus && "No template names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000144
Douglas Gregor3cf81312009-11-03 23:16:33 +0000145 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000146 MemberOfUnknownSpecialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000147
Douglas Gregor3cf81312009-11-03 23:16:33 +0000148 switch (Name.getKind()) {
149 case UnqualifiedId::IK_Identifier:
150 TName = DeclarationName(Name.Identifier);
151 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000152
Douglas Gregor3cf81312009-11-03 23:16:33 +0000153 case UnqualifiedId::IK_OperatorFunctionId:
154 TName = Context.DeclarationNames.getCXXOperatorName(
155 Name.OperatorFunctionId.Operator);
156 break;
157
Alexis Hunted0530f2009-11-28 08:58:14 +0000158 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000159 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
160 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000161
Douglas Gregor3cf81312009-11-03 23:16:33 +0000162 default:
163 return TNK_Non_template;
164 }
Mike Stump11289f42009-09-09 15:08:12 +0000165
John McCallba7bf592010-08-24 05:47:05 +0000166 QualType ObjectType = ObjectTypePtr.get();
Mike Stump11289f42009-09-09 15:08:12 +0000167
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000168 LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +0000169 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
170 MemberOfUnknownSpecialization);
John McCallfb3f9ba2010-08-28 20:17:00 +0000171 if (R.empty()) return TNK_Non_template;
172 if (R.isAmbiguous()) {
173 // Suppress diagnostics; we'll redo this lookup later.
John McCalldcc71402010-08-13 02:23:42 +0000174 R.suppressDiagnostics();
John McCallfb3f9ba2010-08-28 20:17:00 +0000175
176 // FIXME: we might have ambiguous templates, in which case we
177 // should at least parse them properly!
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000178 return TNK_Non_template;
John McCalldcc71402010-08-13 02:23:42 +0000179 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000180
John McCalld28ae272009-12-02 08:04:21 +0000181 TemplateName Template;
182 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000183
John McCalld28ae272009-12-02 08:04:21 +0000184 unsigned ResultCount = R.end() - R.begin();
185 if (ResultCount > 1) {
186 // We assume that we'll preserve the qualifier from a function
187 // template name in other ways.
188 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
189 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000190
191 // We'll do this lookup again later.
192 R.suppressDiagnostics();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000193 } else {
John McCalld28ae272009-12-02 08:04:21 +0000194 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
195
196 if (SS.isSet() && !SS.isInvalid()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000197 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000198 Template = Context.getQualifiedTemplateName(Qualifier,
199 hasTemplateKeyword, TD);
John McCalld28ae272009-12-02 08:04:21 +0000200 } else {
201 Template = TemplateName(TD);
202 }
203
John McCalldcc71402010-08-13 02:23:42 +0000204 if (isa<FunctionTemplateDecl>(TD)) {
John McCalld28ae272009-12-02 08:04:21 +0000205 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000206
207 // We'll do this lookup again later.
208 R.suppressDiagnostics();
209 } else {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000210 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
Larisse Voufo39a1e502013-08-06 01:03:05 +0000211 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD));
212 TemplateKind =
213 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
John McCalld28ae272009-12-02 08:04:21 +0000214 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000215 }
Mike Stump11289f42009-09-09 15:08:12 +0000216
John McCalld28ae272009-12-02 08:04:21 +0000217 TemplateResult = TemplateTy::make(Template);
218 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000219}
220
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000221bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
Douglas Gregor18473f32010-01-12 21:28:44 +0000222 SourceLocation IILoc,
223 Scope *S,
224 const CXXScopeSpec *SS,
225 TemplateTy &SuggestedTemplate,
226 TemplateNameKind &SuggestedKind) {
227 // We can't recover unless there's a dependent scope specifier preceding the
228 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000229 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000230 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
231 computeDeclContext(*SS))
232 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000233
Douglas Gregor18473f32010-01-12 21:28:44 +0000234 // The code is missing a 'template' keyword prior to the dependent template
235 // name.
236 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
237 Diag(IILoc, diag::err_template_kw_missing)
238 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000239 << FixItHint::CreateInsertion(IILoc, "template ");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000240 SuggestedTemplate
Douglas Gregor18473f32010-01-12 21:28:44 +0000241 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
242 SuggestedKind = TNK_Dependent_template_name;
243 return true;
244}
245
John McCalle66edc12009-11-24 19:00:30 +0000246void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000247 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000248 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000249 bool EnteringContext,
250 bool &MemberOfUnknownSpecialization) {
John McCalle66edc12009-11-24 19:00:30 +0000251 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000252 MemberOfUnknownSpecialization = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000253 DeclContext *LookupCtx = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000254 bool isDependent = false;
255 if (!ObjectType.isNull()) {
256 // This nested-name-specifier occurs in a member access expression, e.g.,
257 // x->B::f, and we are looking into the type of the object.
258 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
259 LookupCtx = computeDeclContext(ObjectType);
260 isDependent = ObjectType->isDependentType();
Richard Smith5ed79562013-06-07 20:03:01 +0000261 assert((isDependent || !ObjectType->isIncompleteType() ||
262 ObjectType->castAs<TagType>()->isBeingDefined()) &&
John McCalle66edc12009-11-24 19:00:30 +0000263 "Caller should have completed object type");
Douglas Gregorbf3a8262012-01-12 16:11:24 +0000264
265 // Template names cannot appear inside an Objective-C class or object type.
266 if (ObjectType->isObjCObjectOrInterfaceType()) {
267 Found.clear();
268 return;
269 }
John McCalle66edc12009-11-24 19:00:30 +0000270 } else if (SS.isSet()) {
271 // This nested-name-specifier occurs after another nested-name-specifier,
272 // so long into the context associated with the prior nested-name-specifier.
273 LookupCtx = computeDeclContext(SS, EnteringContext);
274 isDependent = isDependentScopeSpecifier(SS);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000275
John McCalle66edc12009-11-24 19:00:30 +0000276 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000277 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCalle66edc12009-11-24 19:00:30 +0000278 return;
279 }
280
281 bool ObjectTypeSearchedInScope = false;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000282 bool AllowFunctionTemplatesInLookup = true;
John McCalle66edc12009-11-24 19:00:30 +0000283 if (LookupCtx) {
284 // Perform "qualified" name lookup into the declaration context we
285 // computed, which is either the type of the base of a member access
286 // expression or the declaration context associated with a prior
287 // nested-name-specifier.
288 LookupQualifiedName(Found, LookupCtx);
John McCalle66edc12009-11-24 19:00:30 +0000289 if (!ObjectType.isNull() && Found.empty()) {
290 // C++ [basic.lookup.classref]p1:
291 // In a class member access expression (5.2.5), if the . or -> token is
292 // immediately followed by an identifier followed by a <, the
293 // identifier must be looked up to determine whether the < is the
294 // beginning of a template argument list (14.2) or a less-than operator.
295 // The identifier is first looked up in the class of the object
296 // expression. If the identifier is not found, it is then looked up in
297 // the context of the entire postfix-expression and shall name a class
298 // or function template.
John McCalle66edc12009-11-24 19:00:30 +0000299 if (S) LookupName(Found, S);
300 ObjectTypeSearchedInScope = true;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000301 AllowFunctionTemplatesInLookup = false;
John McCalle66edc12009-11-24 19:00:30 +0000302 }
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000303 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregorc119dd52010-01-12 17:06:20 +0000304 // We cannot look into a dependent object type or nested nme
305 // specifier.
Douglas Gregor786123d2010-05-21 23:18:07 +0000306 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000307 return;
308 } else {
309 // Perform unqualified name lookup in the current scope.
310 LookupName(Found, S);
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000311
312 if (!ObjectType.isNull())
313 AllowFunctionTemplatesInLookup = false;
John McCalle66edc12009-11-24 19:00:30 +0000314 }
315
Douglas Gregorc119dd52010-01-12 17:06:20 +0000316 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000317 // If we did not find any names, attempt to correct any typos.
318 DeclarationName Name = Found.getLookupName();
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000319 Found.clear();
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000320 // Simple filter callback that, for keywords, only accepts the C++ *_cast
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000321 auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
322 FilterCCC->WantTypeSpecifiers = false;
323 FilterCCC->WantExpressionKeywords = false;
324 FilterCCC->WantRemainingKeywords = false;
325 FilterCCC->WantCXXNamedCasts = true;
326 if (TypoCorrection Corrected = CorrectTypo(
327 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
328 std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000329 Found.setLookupName(Corrected.getCorrection());
330 if (Corrected.getCorrectionDecl())
331 Found.addDecl(Corrected.getCorrectionDecl());
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000332 FilterAcceptableTemplateNames(Found);
John McCalle9cccd82010-06-16 08:42:20 +0000333 if (!Found.empty()) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000334 if (LookupCtx) {
Richard Smithf9b15102013-08-17 00:46:16 +0000335 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
336 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000337 Name.getAsString() == CorrectedStr;
Richard Smithf9b15102013-08-17 00:46:16 +0000338 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
339 << Name << LookupCtx << DroppedSpecifier
340 << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000341 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000342 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000343 }
John McCalle9cccd82010-06-16 08:42:20 +0000344 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000345 } else {
Douglas Gregorc048c522010-06-29 19:27:42 +0000346 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000347 }
348 }
349
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000350 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000351 if (Found.empty()) {
352 if (isDependent)
353 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000354 return;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000355 }
John McCalle66edc12009-11-24 19:00:30 +0000356
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000357 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
Richard Smithe7d67f22013-09-03 21:22:41 +0000358 !getLangOpts().CPlusPlus11) {
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000359 // C++03 [basic.lookup.classref]p1:
John McCalle66edc12009-11-24 19:00:30 +0000360 // [...] If the lookup in the class of the object expression finds a
361 // template, the name is also looked up in the context of the entire
362 // postfix-expression and [...]
363 //
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000364 // Note: C++11 does not perform this second lookup.
John McCalle66edc12009-11-24 19:00:30 +0000365 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
366 LookupOrdinaryName);
367 LookupName(FoundOuter, S);
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000368 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000369
John McCalle66edc12009-11-24 19:00:30 +0000370 if (FoundOuter.empty()) {
371 // - if the name is not found, the name found in the class of the
372 // object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000373 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
374 FoundOuter.isAmbiguous()) {
John McCalle66edc12009-11-24 19:00:30 +0000375 // - if the name is found in the context of the entire
376 // postfix-expression and does not name a class template, the name
377 // found in the class of the object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000378 FoundOuter.clear();
John McCalle9cccd82010-06-16 08:42:20 +0000379 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000380 // - if the name found is a class template, it must refer to the same
381 // entity as the one found in the class of the object expression,
382 // otherwise the program is ill-formed.
383 if (!Found.isSingleResult() ||
384 Found.getFoundDecl()->getCanonicalDecl()
385 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000386 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000387 diag::ext_nested_name_member_ref_lookup_ambiguous)
388 << Found.getLookupName()
389 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000390 Diag(Found.getRepresentativeDecl()->getLocation(),
391 diag::note_ambig_member_ref_object_type)
392 << ObjectType;
393 Diag(FoundOuter.getFoundDecl()->getLocation(),
394 diag::note_ambig_member_ref_scope);
395
396 // Recover by taking the template that we found in the object
397 // expression's type.
398 }
399 }
400 }
401}
402
John McCallcd4b4772009-12-02 03:53:29 +0000403/// ActOnDependentIdExpression - Handle a dependent id-expression that
404/// was just parsed. This is only possible with an explicit scope
405/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000406ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000407Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000408 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000409 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000410 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000411 const TemplateArgumentListInfo *TemplateArgs) {
John McCall87fe5d52010-05-20 01:18:31 +0000412 DeclContext *DC = getFunctionLevelDeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000413
John McCallcd4b4772009-12-02 03:53:29 +0000414 if (!isAddressOfOperand &&
John McCall87fe5d52010-05-20 01:18:31 +0000415 isa<CXXMethodDecl>(DC) &&
416 cast<CXXMethodDecl>(DC)->isInstance()) {
417 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000418
John McCalle66edc12009-11-24 19:00:30 +0000419 // Since the 'this' expression is synthesized, we don't need to
420 // perform the double-lookup check.
Craig Topperc3ec1492014-05-26 06:22:03 +0000421 NamedDecl *FirstQualifierInScope = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000422
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000423 return CXXDependentScopeMemberExpr::Create(
424 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
425 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
426 FirstQualifierInScope, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000427 }
428
Abramo Bagnara7945c982012-01-27 09:46:47 +0000429 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000430}
431
John McCalldadc5752010-08-24 06:29:42 +0000432ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000433Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000434 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000435 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000436 const TemplateArgumentListInfo *TemplateArgs) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000437 return DependentScopeDeclRefExpr::Create(
438 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
439 TemplateArgs);
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000440}
441
Douglas Gregor5101c242008-12-05 18:15:24 +0000442/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
443/// that the template parameter 'PrevDecl' is being shadowed by a new
444/// declaration at location Loc. Returns true to indicate that this is
445/// an error, and false otherwise.
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000446void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000447 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000448
449 // Microsoft Visual C++ permits template parameters to be shadowed.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000450 if (getLangOpts().MicrosoftExt)
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000451 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000452
453 // C++ [temp.local]p4:
454 // A template-parameter shall not be redeclared within its
455 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000456 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000457 << cast<NamedDecl>(PrevDecl)->getDeclName();
458 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000459 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000460}
461
Douglas Gregor463421d2009-03-03 04:44:36 +0000462/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000463/// the parameter D to reference the templated declaration and return a pointer
464/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000465TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
466 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
467 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000468 return Temp;
469 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000470 return nullptr;
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000471}
472
Douglas Gregoreb29d182011-01-05 17:40:24 +0000473ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
474 SourceLocation EllipsisLoc) const {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000475 assert(Kind == Template &&
Douglas Gregoreb29d182011-01-05 17:40:24 +0000476 "Only template template arguments can be pack expansions here");
477 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
478 "Template template argument pack expansion without packs");
479 ParsedTemplateArgument Result(*this);
480 Result.EllipsisLoc = EllipsisLoc;
481 return Result;
482}
483
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000484static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
485 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000486
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000487 switch (Arg.getKind()) {
488 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000489 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000490 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000491 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000492 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000493 return TemplateArgumentLoc(TemplateArgument(T), DI);
494 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000495
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000496 case ParsedTemplateArgument::NonType: {
497 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
498 return TemplateArgumentLoc(TemplateArgument(E), E);
499 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000500
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000501 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000502 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregore1d60df2011-01-14 23:41:42 +0000503 TemplateArgument TArg;
504 if (Arg.getEllipsisLoc().isValid())
David Blaikie05785d12013-02-20 22:23:23 +0000505 TArg = TemplateArgument(Template, Optional<unsigned int>());
Douglas Gregore1d60df2011-01-14 23:41:42 +0000506 else
507 TArg = Template;
508 return TemplateArgumentLoc(TArg,
Douglas Gregor9d802122011-03-02 17:09:35 +0000509 Arg.getScopeSpec().getWithLocInContext(
510 SemaRef.Context),
Douglas Gregoreb29d182011-01-05 17:40:24 +0000511 Arg.getLocation(),
512 Arg.getEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000513 }
514 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000515
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000516 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000517}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000518
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000519/// \brief Translates template arguments as provided by the parser
520/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000521void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
522 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000523 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000524 TemplateArgs.addArgument(translateTemplateArgument(*this,
525 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000526}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000527
Richard Smithb80d5402013-06-25 22:21:36 +0000528static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
529 SourceLocation Loc,
530 IdentifierInfo *Name) {
531 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
532 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
533 if (PrevDecl && PrevDecl->isTemplateParameter())
534 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
535}
536
Douglas Gregor5101c242008-12-05 18:15:24 +0000537/// ActOnTypeParameter - Called when a C++ template type parameter
538/// (e.g., "typename T") has been parsed. Typename specifies whether
539/// the keyword "typename" was used to declare the type parameter
540/// (otherwise, "class" was used), and KeyLoc is the location of the
541/// "class" or "typename" keyword. ParamName is the name of the
542/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth08836322011-05-01 00:51:33 +0000543/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000544/// If the type parameter has a default argument, it will be added
545/// later via ActOnTypeParameterDefault.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000546Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
John McCall48871652010-08-21 09:40:31 +0000547 SourceLocation EllipsisLoc,
548 SourceLocation KeyLoc,
549 IdentifierInfo *ParamName,
550 SourceLocation ParamNameLoc,
551 unsigned Depth, unsigned Position,
552 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000553 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000554 assert(S->isTemplateParamScope() &&
555 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000556 bool Invalid = false;
557
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000558 SourceLocation Loc = ParamNameLoc;
559 if (!ParamName)
560 Loc = KeyLoc;
561
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000562 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregor5101c242008-12-05 18:15:24 +0000563 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000564 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000565 KeyLoc, Loc, Depth, Position, ParamName,
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000566 Typename, IsParameterPack);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000567 Param->setAccess(AS_public);
Douglas Gregor5101c242008-12-05 18:15:24 +0000568 if (Invalid)
569 Param->setInvalidDecl();
570
571 if (ParamName) {
Richard Smithb80d5402013-06-25 22:21:36 +0000572 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
573
Douglas Gregor5101c242008-12-05 18:15:24 +0000574 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000575 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000576 IdResolver.AddDecl(Param);
577 }
578
Douglas Gregorf5500772011-01-05 15:48:55 +0000579 // C++0x [temp.param]p9:
580 // A default template-argument may be specified for any kind of
581 // template-parameter that is not a template parameter pack.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000582 if (DefaultArg && IsParameterPack) {
Douglas Gregorf5500772011-01-05 15:48:55 +0000583 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
584 DefaultArg = ParsedType();
585 }
586
Douglas Gregordc13ded2010-07-01 00:00:45 +0000587 // Handle the default argument, if provided.
588 if (DefaultArg) {
589 TypeSourceInfo *DefaultTInfo;
590 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000591
Douglas Gregordc13ded2010-07-01 00:00:45 +0000592 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000593
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000594 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000595 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000596 UPPC_DefaultArgument))
597 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000598
Douglas Gregordc13ded2010-07-01 00:00:45 +0000599 // Check the template argument itself.
600 if (CheckTemplateArgument(Param, DefaultTInfo)) {
601 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000602 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000603 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000604
Richard Smith1469b912015-06-10 00:29:03 +0000605 Param->setDefaultArgument(DefaultTInfo);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000606 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000607
John McCall48871652010-08-21 09:40:31 +0000608 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000609}
610
Douglas Gregor463421d2009-03-03 04:44:36 +0000611/// \brief Check that the type of a non-type template parameter is
612/// well-formed.
613///
614/// \returns the (possibly-promoted) parameter type if valid;
615/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000616QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000617Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000618 // We don't allow variably-modified types as the type of non-type template
619 // parameters.
620 if (T->isVariablyModifiedType()) {
621 Diag(Loc, diag::err_variably_modified_nontype_template_param)
622 << T;
623 return QualType();
624 }
625
Douglas Gregor463421d2009-03-03 04:44:36 +0000626 // C++ [temp.param]p4:
627 //
628 // A non-type template-parameter shall have one of the following
629 // (optionally cv-qualified) types:
630 //
631 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000632 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000633 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000634 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000635 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000636 T->isReferenceType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000637 // -- pointer to member,
Douglas Gregor463421d2009-03-03 04:44:36 +0000638 T->isMemberPointerType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000639 // -- std::nullptr_t.
640 T->isNullPtrType() ||
Douglas Gregor463421d2009-03-03 04:44:36 +0000641 // If T is a dependent type, we can't do the check now, so we
642 // assume that it is well-formed.
Richard Smithd0e1c952012-03-13 07:21:50 +0000643 T->isDependentType()) {
644 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
645 // are ignored when determining its type.
646 return T.getUnqualifiedType();
647 }
648
Douglas Gregor463421d2009-03-03 04:44:36 +0000649 // C++ [temp.param]p8:
650 //
651 // A non-type template-parameter of type "array of T" or
652 // "function returning T" is adjusted to be of type "pointer to
653 // T" or "pointer to function returning T", respectively.
Richard Smithd663fdd2014-12-17 20:42:37 +0000654 else if (T->isArrayType() || T->isFunctionType())
655 return Context.getDecayedType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000656
Douglas Gregor463421d2009-03-03 04:44:36 +0000657 Diag(Loc, diag::err_template_nontype_parm_bad_type)
658 << T;
659
660 return QualType();
661}
662
John McCall48871652010-08-21 09:40:31 +0000663Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
664 unsigned Depth,
665 unsigned Position,
666 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000667 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000668 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
669 QualType T = TInfo->getType();
Douglas Gregor5101c242008-12-05 18:15:24 +0000670
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000671 assert(S->isTemplateParamScope() &&
672 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000673 bool Invalid = false;
674
Douglas Gregor38ee75e2010-12-16 15:36:43 +0000675 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
676 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000677 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000678 Invalid = true;
679 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000680
Richard Smithb80d5402013-06-25 22:21:36 +0000681 IdentifierInfo *ParamName = D.getIdentifier();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000682 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor5101c242008-12-05 18:15:24 +0000683 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000684 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000685 D.getLocStart(),
John McCallf7b2fb52010-01-22 00:28:27 +0000686 D.getIdentifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000687 Depth, Position, ParamName, T,
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000688 IsParameterPack, TInfo);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000689 Param->setAccess(AS_public);
Richard Smithb80d5402013-06-25 22:21:36 +0000690
Douglas Gregor5101c242008-12-05 18:15:24 +0000691 if (Invalid)
692 Param->setInvalidDecl();
693
Richard Smithb80d5402013-06-25 22:21:36 +0000694 if (ParamName) {
695 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
696 ParamName);
697
Douglas Gregor5101c242008-12-05 18:15:24 +0000698 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000699 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000700 IdResolver.AddDecl(Param);
701 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000702
Douglas Gregorf5500772011-01-05 15:48:55 +0000703 // C++0x [temp.param]p9:
704 // A default template-argument may be specified for any kind of
705 // template-parameter that is not a template parameter pack.
706 if (Default && IsParameterPack) {
707 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
Craig Topperc3ec1492014-05-26 06:22:03 +0000708 Default = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000709 }
710
Douglas Gregordc13ded2010-07-01 00:00:45 +0000711 // Check the well-formedness of the default template argument, if provided.
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000712 if (Default) {
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000713 // Check for unexpanded parameter packs.
714 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
715 return Param;
716
Douglas Gregordc13ded2010-07-01 00:00:45 +0000717 TemplateArgument Converted;
Richard Smithd663fdd2014-12-17 20:42:37 +0000718 ExprResult DefaultRes =
719 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
John Wiegley01296292011-04-08 18:41:53 +0000720 if (DefaultRes.isInvalid()) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000721 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000722 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000723 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000724 Default = DefaultRes.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000725
Richard Smith1469b912015-06-10 00:29:03 +0000726 Param->setDefaultArgument(Default);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000727 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000728
John McCall48871652010-08-21 09:40:31 +0000729 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000730}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000731
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000732/// ActOnTemplateTemplateParameter - Called when a C++ template template
James Dennett2a4d13c2012-06-15 07:13:21 +0000733/// parameter (e.g. T in template <template \<typename> class T> class array)
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000734/// has been parsed. S is the current scope.
John McCall48871652010-08-21 09:40:31 +0000735Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
736 SourceLocation TmpLoc,
Richard Trieu9becef62011-09-09 03:18:59 +0000737 TemplateParameterList *Params,
Douglas Gregorf5500772011-01-05 15:48:55 +0000738 SourceLocation EllipsisLoc,
John McCall48871652010-08-21 09:40:31 +0000739 IdentifierInfo *Name,
740 SourceLocation NameLoc,
741 unsigned Depth,
742 unsigned Position,
743 SourceLocation EqualLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +0000744 ParsedTemplateArgument Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000745 assert(S->isTemplateParamScope() &&
746 "Template template parameter not in template parameter scope!");
747
748 // Construct the parameter object.
Douglas Gregorf5500772011-01-05 15:48:55 +0000749 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000750 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000751 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000752 NameLoc.isInvalid()? TmpLoc : NameLoc,
753 Depth, Position, IsParameterPack,
Douglas Gregorf5500772011-01-05 15:48:55 +0000754 Name, Params);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000755 Param->setAccess(AS_public);
756
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000757 // If the template template parameter has a name, then link the identifier
Douglas Gregordc13ded2010-07-01 00:00:45 +0000758 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000759 if (Name) {
Richard Smithb80d5402013-06-25 22:21:36 +0000760 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
761
John McCall48871652010-08-21 09:40:31 +0000762 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000763 IdResolver.AddDecl(Param);
764 }
765
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000766 if (Params->size() == 0) {
767 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
768 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
769 Param->setInvalidDecl();
770 }
771
Douglas Gregorf5500772011-01-05 15:48:55 +0000772 // C++0x [temp.param]p9:
773 // A default template-argument may be specified for any kind of
774 // template-parameter that is not a template parameter pack.
775 if (IsParameterPack && !Default.isInvalid()) {
776 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
777 Default = ParsedTemplateArgument();
778 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000779
Douglas Gregordc13ded2010-07-01 00:00:45 +0000780 if (!Default.isInvalid()) {
781 // Check only that we have a template template argument. We don't want to
782 // try to check well-formedness now, because our template template parameter
783 // might have dependent types in its template parameters, which we wouldn't
784 // be able to match now.
785 //
786 // If none of the template template parameter's template arguments mention
787 // other template parameters, we could actually perform more checking here.
788 // However, it isn't worth doing.
789 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
790 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
791 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
792 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +0000793 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000794 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000795
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000796 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000797 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000798 DefaultArg.getArgument().getAsTemplate(),
799 UPPC_DefaultArgument))
800 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000801
Richard Smith1469b912015-06-10 00:29:03 +0000802 Param->setDefaultArgument(Context, DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000803 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000804
John McCall48871652010-08-21 09:40:31 +0000805 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +0000806}
807
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000808/// ActOnTemplateParameterList - Builds a TemplateParameterList that
809/// contains the template parameters in Params/NumParams.
Richard Trieu9becef62011-09-09 03:18:59 +0000810TemplateParameterList *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000811Sema::ActOnTemplateParameterList(unsigned Depth,
812 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000813 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000814 SourceLocation LAngleLoc,
John McCall48871652010-08-21 09:40:31 +0000815 Decl **Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000816 SourceLocation RAngleLoc) {
817 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000818 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000819
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000820 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000821 (NamedDecl**)Params, NumParams,
Douglas Gregorbe999392009-09-15 16:23:51 +0000822 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000823}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000824
John McCall3e11ebe2010-03-15 10:12:16 +0000825static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
826 if (SS.isSet())
Douglas Gregor14454802011-02-25 02:25:35 +0000827 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +0000828}
829
John McCallfaf5fb42010-08-26 23:41:50 +0000830DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000831Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000832 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000833 IdentifierInfo *Name, SourceLocation NameLoc,
834 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000835 TemplateParameterList *TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +0000836 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
Nikola Smiljanic4fc91532014-07-17 01:59:34 +0000837 SourceLocation FriendLoc,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +0000838 unsigned NumOuterTemplateParamLists,
Richard Smithbe3980b2015-03-27 00:41:57 +0000839 TemplateParameterList** OuterTemplateParamLists,
Richard Smithd9ba2242015-05-07 03:54:19 +0000840 SkipBodyInfo *SkipBody) {
Mike Stump11289f42009-09-09 15:08:12 +0000841 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000842 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000843 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000844 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000845
846 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000847 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000848 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000849
Abramo Bagnara6150c882010-05-11 21:36:43 +0000850 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
851 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000852
853 // There is no such thing as an unnamed class template.
854 if (!Name) {
855 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000856 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000857 }
858
Richard Smith6483d222012-04-21 01:27:54 +0000859 // Find any previous declaration with this name. For a friend with no
860 // scope explicitly specified, we only look for tag declarations (per
861 // C++11 [basic.lookup.elab]p2).
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000862 DeclContext *SemanticContext;
Richard Smith6483d222012-04-21 01:27:54 +0000863 LookupResult Previous(*this, Name, NameLoc,
864 (SS.isEmpty() && TUK == TUK_Friend)
865 ? LookupTagName : LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000866 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000867 if (SS.isNotEmpty() && !SS.isInvalid()) {
868 SemanticContext = computeDeclContext(SS, true);
869 if (!SemanticContext) {
Douglas Gregor67daacb2012-03-30 16:20:47 +0000870 // FIXME: Horrible, horrible hack! We can't currently represent this
871 // in the AST, and historically we have just ignored such friend
872 // class templates, so don't complain here.
Richard Smithcd556eb2013-11-08 18:59:56 +0000873 Diag(NameLoc, TUK == TUK_Friend
874 ? diag::warn_template_qualified_friend_ignored
875 : diag::err_template_qualified_declarator_no_match)
Douglas Gregor67daacb2012-03-30 16:20:47 +0000876 << SS.getScopeRep() << SS.getRange();
Richard Smithcd556eb2013-11-08 18:59:56 +0000877 return TUK != TUK_Friend;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000878 }
Mike Stump11289f42009-09-09 15:08:12 +0000879
John McCall0b66eb32010-05-01 00:40:08 +0000880 if (RequireCompleteDeclContext(SS, SemanticContext))
881 return true;
882
Douglas Gregor041b0842011-10-14 15:31:12 +0000883 // If we're adding a template to a dependent context, we may need to
884 // rebuilding some of the types used within the template parameter list,
885 // now that we know what the current instantiation is.
886 if (SemanticContext->isDependentContext()) {
887 ContextRAII SavedContext(*this, SemanticContext);
888 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
889 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +0000890 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
891 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
Richard Smith6483d222012-04-21 01:27:54 +0000892
John McCall27b18f82009-11-17 02:14:36 +0000893 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000894 } else {
895 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000896 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000897 }
Mike Stump11289f42009-09-09 15:08:12 +0000898
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000899 if (Previous.isAmbiguous())
900 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000901
Craig Topperc3ec1492014-05-26 06:22:03 +0000902 NamedDecl *PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000903 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000904 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000905
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000906 // If there is a previous declaration with the same name, check
907 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000908 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000909 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000910
911 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000912 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000913 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000914 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000915 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
916 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000917 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000918 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
919 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
920 PrevClassTemplate
921 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
922 ->getSpecializedTemplate();
923 }
924 }
925
John McCalld43784f2009-12-18 11:25:59 +0000926 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000927 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000928 // [...] When looking for a prior declaration of a class or a function
929 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +0000930 // function is neither a qualified name nor a template-id, scopes outside
931 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +0000932 if (!SS.isSet()) {
933 DeclContext *OutermostContext = CurContext;
934 while (!OutermostContext->isFileContext())
935 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000936
Richard Smith61e582f2012-04-20 07:12:26 +0000937 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +0000938 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
939 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
940 SemanticContext = PrevDecl->getDeclContext();
941 } else {
942 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000943 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +0000944 // declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +0000945 PrevDecl = PrevClassTemplate = nullptr;
Douglas Gregorb74b1032010-04-18 17:37:40 +0000946 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +0000947
948 // Check that the chosen semantic context doesn't already contain a
949 // declaration of this name as a non-tag type.
950 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
951 ForRedeclaration);
952 DeclContext *LookupContext = SemanticContext;
953 while (LookupContext->isTransparentContext())
954 LookupContext = LookupContext->getLookupParent();
955 LookupQualifiedName(Previous, LookupContext);
956
957 if (Previous.isAmbiguous())
958 return true;
959
960 if (Previous.begin() != Previous.end())
961 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +0000962 }
John McCall90d3bb92009-12-17 23:21:11 +0000963 }
Richard Smith72bcaec2013-12-05 04:30:04 +0000964 } else if (PrevDecl &&
965 !isDeclInScope(PrevDecl, SemanticContext, S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +0000966 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000967
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000968 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +0000969 // Ensure that the template parameter lists are compatible. Skip this check
970 // for a friend in a dependent context: the template parameter list itself
971 // could be dependent.
972 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
973 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000974 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000975 /*Complain=*/true,
976 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000977 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000978
979 // C++ [temp.class]p4:
980 // In a redeclaration, partial specialization, explicit
981 // specialization or explicit instantiation of a class template,
982 // the class-key shall agree in kind with the original class
983 // template declaration (7.1.5.3).
984 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +0000985 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
986 TUK == TUK_Definition, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000987 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000988 << Name
Douglas Gregora771f462010-03-31 17:46:05 +0000989 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000990 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000991 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000992 }
993
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000994 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000995 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000996 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Richard Smithbe3980b2015-03-27 00:41:57 +0000997 // If we have a prior definition that is not visible, treat this as
998 // simply making that previous definition visible.
999 NamedDecl *Hidden = nullptr;
1000 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
Richard Smithd9ba2242015-05-07 03:54:19 +00001001 SkipBody->ShouldSkip = true;
Richard Smithbe3980b2015-03-27 00:41:57 +00001002 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1003 assert(Tmpl && "original definition of a class template is not a "
1004 "class template?");
Richard Smithd9ba2242015-05-07 03:54:19 +00001005 makeMergedDefinitionVisible(Hidden, KWLoc);
1006 makeMergedDefinitionVisible(Tmpl, KWLoc);
Richard Smithbe3980b2015-03-27 00:41:57 +00001007 return Def;
1008 }
1009
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001010 Diag(NameLoc, diag::err_redefinition) << Name;
1011 Diag(Def->getLocation(), diag::note_previous_definition);
1012 // FIXME: Would it make sense to try to "forget" the previous
1013 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +00001014 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001015 }
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001016 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001017 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
1018 // Maybe we will complain about the shadowed template parameter.
1019 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1020 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00001021 PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001022 } else if (PrevDecl) {
1023 // C++ [temp]p5:
1024 // A class template shall not have the same name as any other
1025 // template, class, function, object, enumeration, enumerator,
1026 // namespace, or type in the same scope (3.3), except as specified
1027 // in (14.5.4).
1028 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1029 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001030 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001031 }
1032
Douglas Gregordba32632009-02-10 19:49:53 +00001033 // Check the template parameter list of this declaration, possibly
1034 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001035 // template declaration. Skip this check for a friend in a dependent
1036 // context, because the template parameter list might be dependent.
1037 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001038 CheckTemplateParameterList(
1039 TemplateParams,
Craig Topperc3ec1492014-05-26 06:22:03 +00001040 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1041 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001042 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1043 SemanticContext->isDependentContext())
1044 ? TPC_ClassTemplateMember
1045 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1046 : TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +00001047 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001048
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001049 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001050 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001051 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001052 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1053 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001054 : diag::err_member_decl_does_not_match)
1055 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001056 Invalid = true;
1057 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001058 }
1059
Mike Stump11289f42009-09-09 15:08:12 +00001060 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001061 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Mike Stump11289f42009-09-09 15:08:12 +00001062 PrevClassTemplate?
Craig Topperc3ec1492014-05-26 06:22:03 +00001063 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001064 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +00001065 SetNestedNameSpecifier(NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001066 if (NumOuterTemplateParamLists > 0)
1067 NewClass->setTemplateParameterListsInfo(Context,
1068 NumOuterTemplateParamLists,
1069 OuterTemplateParamLists);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001070
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001071 // Add alignment attributes if necessary; these attributes are checked when
1072 // the ASTContext lays out the structure.
Eli Friedman0415f3e12012-08-08 21:08:34 +00001073 if (TUK == TUK_Definition) {
1074 AddAlignmentAttributesForRecord(NewClass);
1075 AddMsStructLayoutForRecord(NewClass);
1076 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001077
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001078 ClassTemplateDecl *NewTemplate
1079 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1080 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +00001081 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001082 NewClass->setDescribedClassTemplate(NewTemplate);
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001083
Douglas Gregor21823bf2011-12-20 18:11:52 +00001084 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001085 NewTemplate->setModulePrivate();
Douglas Gregor26701a42011-09-09 02:06:17 +00001086
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001087 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001088 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001089 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001090 assert(T->isDependentType() && "Class template type is not dependent?");
1091 (void)T;
1092
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001093 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001094 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001095 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001096 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1097 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001098
Anders Carlsson137108d2009-03-26 01:24:28 +00001099 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001100 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001101 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001102
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001103 // Set the lexical context of these templates
1104 NewClass->setLexicalDeclContext(CurContext);
1105 NewTemplate->setLexicalDeclContext(CurContext);
1106
John McCall9bb74a52009-07-31 02:45:11 +00001107 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001108 NewClass->startDefinition();
1109
1110 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00001111 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001112
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001113 if (PrevClassTemplate)
1114 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1115
Rafael Espindola385c0422012-07-13 18:04:45 +00001116 AddPushedVisibilityAttribute(NewClass);
1117
Richard Smith234ff472014-08-23 00:49:01 +00001118 if (TUK != TUK_Friend) {
1119 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1120 Scope *Outer = S;
1121 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1122 Outer = Outer->getParent();
1123 PushOnScopeChains(NewTemplate, Outer);
1124 } else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001125 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001126 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001127 NewClass->setAccess(PrevClassTemplate->getAccess());
1128 }
John McCall27b5c252009-09-14 21:59:20 +00001129
Richard Smith64017682013-07-17 23:53:16 +00001130 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001131
John McCall27b5c252009-09-14 21:59:20 +00001132 // Friend templates are visible in fairly strange ways.
1133 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001134 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001135 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001136 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1137 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001138 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001139 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001140
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001141 FriendDecl *Friend = FriendDecl::Create(
1142 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
Douglas Gregor3dad8422009-09-26 06:47:28 +00001143 Friend->setAccess(AS_public);
1144 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001145 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001146
Douglas Gregordba32632009-02-10 19:49:53 +00001147 if (Invalid) {
1148 NewTemplate->setInvalidDecl();
1149 NewClass->setInvalidDecl();
1150 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001151
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001152 ActOnDocumentableDecl(NewTemplate);
1153
John McCall48871652010-08-21 09:40:31 +00001154 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001155}
1156
Douglas Gregored5731f2009-11-25 17:50:39 +00001157/// \brief Diagnose the presence of a default template argument on a
1158/// template parameter, which is ill-formed in certain contexts.
1159///
1160/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001161static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00001162 Sema::TemplateParamListContext TPC,
1163 SourceLocation ParamLoc,
1164 SourceRange DefArgRange) {
1165 switch (TPC) {
1166 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00001167 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00001168 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001169 return false;
1170
1171 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001172 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001173 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00001174 // A default template-argument shall not be specified in a
1175 // function template declaration or a function template
1176 // definition [...]
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001177 // If a friend function template declaration specifies a default
1178 // template-argument, that declaration shall be a definition and shall be
1179 // the only declaration of the function template in the translation unit.
1180 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001181 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00001182 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1183 : diag::ext_template_parameter_default_in_function_template)
1184 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00001185 return false;
1186
1187 case Sema::TPC_ClassTemplateMember:
1188 // C++0x [temp.param]p9:
1189 // A default template-argument shall not be specified in the
1190 // template-parameter-lists of the definition of a member of a
1191 // class template that appears outside of the member's class.
1192 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1193 << DefArgRange;
1194 return true;
1195
David Majnemerba8f17a2013-06-25 22:08:55 +00001196 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001197 case Sema::TPC_FriendFunctionTemplate:
1198 // C++ [temp.param]p9:
1199 // A default template-argument shall not be specified in a
1200 // friend template declaration.
1201 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1202 << DefArgRange;
1203 return true;
1204
1205 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1206 // for friend function templates if there is only a single
1207 // declaration (and it is a definition). Strange!
1208 }
1209
David Blaikie8a40f702012-01-17 06:56:22 +00001210 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00001211}
1212
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001213/// \brief Check for unexpanded parameter packs within the template parameters
1214/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00001215static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1216 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001217 // A template template parameter which is a parameter pack is also a pack
1218 // expansion.
1219 if (TTP->isParameterPack())
1220 return false;
1221
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001222 TemplateParameterList *Params = TTP->getTemplateParameters();
1223 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1224 NamedDecl *P = Params->getParam(I);
1225 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001226 if (!NTTP->isParameterPack() &&
1227 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001228 NTTP->getTypeSourceInfo(),
1229 Sema::UPPC_NonTypeTemplateParameterType))
1230 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001231
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001232 continue;
1233 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001234
1235 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001236 = dyn_cast<TemplateTemplateParmDecl>(P))
1237 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1238 return true;
1239 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001240
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001241 return false;
1242}
1243
Douglas Gregordba32632009-02-10 19:49:53 +00001244/// \brief Checks the validity of a template parameter list, possibly
1245/// considering the template parameter list from a previous
1246/// declaration.
1247///
1248/// If an "old" template parameter list is provided, it must be
1249/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1250/// template parameter list.
1251///
1252/// \param NewParams Template parameter list for a new template
1253/// declaration. This template parameter list will be updated with any
1254/// default arguments that are carried through from the previous
1255/// template parameter list.
1256///
1257/// \param OldParams If provided, template parameter list from a
1258/// previous declaration of the same template. Default template
1259/// arguments will be merged from the old template parameter list to
1260/// the new template parameter list.
1261///
Douglas Gregored5731f2009-11-25 17:50:39 +00001262/// \param TPC Describes the context in which we are checking the given
1263/// template parameter list.
1264///
Douglas Gregordba32632009-02-10 19:49:53 +00001265/// \returns true if an error occurred, false otherwise.
1266bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001267 TemplateParameterList *OldParams,
1268 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001269 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001270
Douglas Gregordba32632009-02-10 19:49:53 +00001271 // C++ [temp.param]p10:
1272 // The set of default template-arguments available for use with a
1273 // template declaration or definition is obtained by merging the
1274 // default arguments from the definition (if in scope) and all
1275 // declarations in scope in the same way default function
1276 // arguments are (8.3.6).
1277 bool SawDefaultArgument = false;
1278 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001279
Mike Stumpc89c8e32009-02-11 23:03:27 +00001280 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001281 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001282 if (OldParams)
1283 OldParam = OldParams->begin();
1284
Douglas Gregor0693def2011-01-27 01:40:17 +00001285 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00001286 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1287 NewParamEnd = NewParams->end();
1288 NewParam != NewParamEnd; ++NewParam) {
1289 // Variables used to diagnose redundant default arguments
1290 bool RedundantDefaultArg = false;
1291 SourceLocation OldDefaultLoc;
1292 SourceLocation NewDefaultLoc;
1293
David Blaikie651c73c2011-10-19 05:19:50 +00001294 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00001295 bool MissingDefaultArg = false;
1296
David Blaikie651c73c2011-10-19 05:19:50 +00001297 // Variable used to diagnose non-final parameter packs
1298 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00001299
Douglas Gregordba32632009-02-10 19:49:53 +00001300 if (TemplateTypeParmDecl *NewTypeParm
1301 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001302 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001303 if (NewTypeParm->hasDefaultArgument() &&
1304 DiagnoseDefaultTemplateArgument(*this, TPC,
1305 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001306 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001307 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001308 NewTypeParm->removeDefaultArgument();
1309
1310 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001311 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001312 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Richard Smithc7d48d12015-05-20 17:50:35 +00001313 // FIXME: There might be a visible declaration of this template parameter.
1314 if (OldTypeParm && !LookupResult::isVisible(*this, OldTypeParm))
1315 OldTypeParm = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001316
Anders Carlsson327865d2009-06-12 23:20:15 +00001317 if (NewTypeParm->isParameterPack()) {
1318 assert(!NewTypeParm->hasDefaultArgument() &&
1319 "Parameter packs can't have a default argument!");
1320 SawParameterPack = true;
Mike Stump11289f42009-09-09 15:08:12 +00001321 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001322 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001323 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1324 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1325 SawDefaultArgument = true;
1326 RedundantDefaultArg = true;
1327 PreviousDefaultArgLoc = NewDefaultLoc;
1328 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1329 // Merge the default argument from the old declaration to the
1330 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001331 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001332 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1333 } else if (NewTypeParm->hasDefaultArgument()) {
1334 SawDefaultArgument = true;
1335 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1336 } else if (SawDefaultArgument)
1337 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001338 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001339 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001340 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001341 if (!NewNonTypeParm->isParameterPack() &&
1342 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001343 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001344 UPPC_NonTypeTemplateParameterType)) {
1345 Invalid = true;
1346 continue;
1347 }
1348
Douglas Gregored5731f2009-11-25 17:50:39 +00001349 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001350 if (NewNonTypeParm->hasDefaultArgument() &&
1351 DiagnoseDefaultTemplateArgument(*this, TPC,
1352 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001353 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001354 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001355 }
1356
Mike Stump12b8ce12009-08-04 21:02:39 +00001357 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001358 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001359 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Richard Smithfd8b64e2015-05-20 18:24:21 +00001360 if (OldNonTypeParm && !LookupResult::isVisible(*this, OldNonTypeParm))
1361 OldNonTypeParm = nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001362 if (NewNonTypeParm->isParameterPack()) {
1363 assert(!NewNonTypeParm->hasDefaultArgument() &&
1364 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001365 if (!NewNonTypeParm->isPackExpansion())
1366 SawParameterPack = true;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001367 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Richard Smith35828f12013-07-22 03:31:14 +00001368 NewNonTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001369 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1370 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1371 SawDefaultArgument = true;
1372 RedundantDefaultArg = true;
1373 PreviousDefaultArgLoc = NewDefaultLoc;
1374 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1375 // Merge the default argument from the old declaration to the
1376 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001377 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001378 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1379 } else if (NewNonTypeParm->hasDefaultArgument()) {
1380 SawDefaultArgument = true;
1381 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1382 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001383 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001384 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00001385 TemplateTemplateParmDecl *NewTemplateParm
1386 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001387
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001388 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00001389 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001390 Invalid = true;
1391 continue;
1392 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001393
David Blaikie651c73c2011-10-19 05:19:50 +00001394 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001395 if (NewTemplateParm->hasDefaultArgument() &&
1396 DiagnoseDefaultTemplateArgument(*this, TPC,
1397 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001398 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001399 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001400
1401 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001402 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001403 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Richard Smithfd8b64e2015-05-20 18:24:21 +00001404 if (OldTemplateParm && !LookupResult::isVisible(*this, OldTemplateParm))
1405 OldTemplateParm = nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001406 if (NewTemplateParm->isParameterPack()) {
1407 assert(!NewTemplateParm->hasDefaultArgument() &&
1408 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001409 if (!NewTemplateParm->isPackExpansion())
1410 SawParameterPack = true;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001411 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001412 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001413 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1414 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001415 SawDefaultArgument = true;
1416 RedundantDefaultArg = true;
1417 PreviousDefaultArgLoc = NewDefaultLoc;
1418 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1419 // Merge the default argument from the old declaration to the
1420 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001421 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001422 PreviousDefaultArgLoc
1423 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001424 } else if (NewTemplateParm->hasDefaultArgument()) {
1425 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001426 PreviousDefaultArgLoc
1427 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001428 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001429 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001430 }
1431
Richard Smith1fde8ec2012-09-07 02:06:42 +00001432 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00001433 // If a template parameter of a primary class template or alias template
1434 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001435 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00001436 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
1437 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00001438 Diag((*NewParam)->getLocation(),
1439 diag::err_template_param_pack_must_be_last_template_parameter);
1440 Invalid = true;
1441 }
1442
Douglas Gregordba32632009-02-10 19:49:53 +00001443 if (RedundantDefaultArg) {
1444 // C++ [temp.param]p12:
1445 // A template-parameter shall not be given default arguments
1446 // by two different declarations in the same scope.
1447 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1448 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1449 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00001450 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00001451 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001452 // If a template-parameter of a class template has a default
1453 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00001454 // have a default template-argument supplied or be a template parameter
1455 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00001456 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001457 diag::err_template_param_default_arg_missing);
1458 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1459 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00001460 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001461 }
1462
1463 // If we have an old template parameter list that we're merging
1464 // in, move on to the next parameter.
1465 if (OldParams)
1466 ++OldParam;
1467 }
1468
Douglas Gregor0693def2011-01-27 01:40:17 +00001469 // We were missing some default arguments at the end of the list, so remove
1470 // all of the default arguments.
1471 if (RemoveDefaultArguments) {
1472 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1473 NewParamEnd = NewParams->end();
1474 NewParam != NewParamEnd; ++NewParam) {
1475 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1476 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001477 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00001478 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1479 NTTP->removeDefaultArgument();
1480 else
1481 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1482 }
1483 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001484
Douglas Gregordba32632009-02-10 19:49:53 +00001485 return Invalid;
1486}
Douglas Gregord32e0282009-02-09 23:23:08 +00001487
John McCalla020a012010-10-20 05:44:58 +00001488namespace {
1489
1490/// A class which looks for a use of a certain level of template
1491/// parameter.
1492struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1493 typedef RecursiveASTVisitor<DependencyChecker> super;
1494
1495 unsigned Depth;
1496 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00001497 SourceLocation MatchLoc;
1498
1499 DependencyChecker(unsigned Depth) : Depth(Depth), Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00001500
1501 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1502 NamedDecl *ND = Params->getParam(0);
1503 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1504 Depth = PD->getDepth();
1505 } else if (NonTypeTemplateParmDecl *PD =
1506 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1507 Depth = PD->getDepth();
1508 } else {
1509 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1510 }
1511 }
1512
Richard Smith6056d5e2014-02-09 00:54:43 +00001513 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
John McCalla020a012010-10-20 05:44:58 +00001514 if (ParmDepth >= Depth) {
1515 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00001516 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00001517 return true;
1518 }
1519 return false;
1520 }
1521
Richard Smith6056d5e2014-02-09 00:54:43 +00001522 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1523 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
1524 }
1525
John McCalla020a012010-10-20 05:44:58 +00001526 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1527 return !Matches(T->getDepth());
1528 }
1529
1530 bool TraverseTemplateName(TemplateName N) {
1531 if (TemplateTemplateParmDecl *PD =
1532 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00001533 if (Matches(PD->getDepth()))
1534 return false;
John McCalla020a012010-10-20 05:44:58 +00001535 return super::TraverseTemplateName(N);
1536 }
1537
1538 bool VisitDeclRefExpr(DeclRefExpr *E) {
1539 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00001540 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
1541 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00001542 return false;
John McCalla020a012010-10-20 05:44:58 +00001543 return super::VisitDeclRefExpr(E);
1544 }
Richard Smith6056d5e2014-02-09 00:54:43 +00001545
1546 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1547 return TraverseType(T->getReplacementType());
1548 }
1549
1550 bool
1551 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
1552 return TraverseTemplateArgument(T->getArgumentPack());
1553 }
1554
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00001555 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1556 return TraverseType(T->getInjectedSpecializationType());
1557 }
John McCalla020a012010-10-20 05:44:58 +00001558};
1559}
1560
Douglas Gregor972fe532011-05-10 18:27:06 +00001561/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00001562/// list.
1563static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00001564DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
John McCalla020a012010-10-20 05:44:58 +00001565 DependencyChecker Checker(Params);
Douglas Gregor972fe532011-05-10 18:27:06 +00001566 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00001567 return Checker.Match;
1568}
1569
Douglas Gregor972fe532011-05-10 18:27:06 +00001570// Find the source range corresponding to the named type in the given
1571// nested-name-specifier, if any.
1572static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1573 QualType T,
1574 const CXXScopeSpec &SS) {
1575 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1576 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1577 if (const Type *CurType = NNS->getAsType()) {
1578 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1579 return NNSLoc.getTypeLoc().getSourceRange();
1580 } else
1581 break;
1582
1583 NNSLoc = NNSLoc.getPrefix();
1584 }
1585
1586 return SourceRange();
1587}
1588
Mike Stump11289f42009-09-09 15:08:12 +00001589/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001590/// specifier, returning the template parameter list that applies to the
1591/// name.
1592///
1593/// \param DeclStartLoc the start of the declaration that has a scope
1594/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001595///
Douglas Gregor972fe532011-05-10 18:27:06 +00001596/// \param DeclLoc The location of the declaration itself.
1597///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001598/// \param SS the scope specifier that will be matched to the given template
1599/// parameter lists. This scope specifier precedes a qualified name that is
1600/// being declared.
1601///
Richard Smith4b55a9c2014-04-17 03:29:33 +00001602/// \param TemplateId The template-id following the scope specifier, if there
1603/// is one. Used to check for a missing 'template<>'.
1604///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001605/// \param ParamLists the template parameter lists, from the outermost to the
1606/// innermost template parameter lists.
1607///
John McCalle820e5e2010-04-13 20:37:33 +00001608/// \param IsFriend Whether to apply the slightly different rules for
1609/// matching template parameters to scope specifiers in friend
1610/// declarations.
1611///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001612/// \param IsExplicitSpecialization will be set true if the entity being
1613/// declared is an explicit specialization, false otherwise.
1614///
Mike Stump11289f42009-09-09 15:08:12 +00001615/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001616/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00001617/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001618/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00001619/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00001620/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001621TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
1622 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001623 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001624 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
1625 bool &IsExplicitSpecialization, bool &Invalid) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001626 IsExplicitSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00001627 Invalid = false;
1628
1629 // The sequence of nested types to which we will match up the template
1630 // parameter lists. We first build this list by starting with the type named
1631 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001632 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00001633 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00001634 if (SS.getScopeRep()) {
1635 if (CXXRecordDecl *Record
1636 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1637 T = Context.getTypeDeclType(Record);
1638 else
1639 T = QualType(SS.getScopeRep()->getAsType(), 0);
1640 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001641
1642 // If we found an explicit specialization that prevents us from needing
1643 // 'template<>' headers, this will be set to the location of that
1644 // explicit specialization.
1645 SourceLocation ExplicitSpecLoc;
1646
1647 while (!T.isNull()) {
1648 NestedTypes.push_back(T);
1649
1650 // Retrieve the parent of a record type.
1651 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1652 // If this type is an explicit specialization, we're done.
1653 if (ClassTemplateSpecializationDecl *Spec
1654 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1655 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1656 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1657 ExplicitSpecLoc = Spec->getLocation();
1658 break;
Douglas Gregor65911492009-11-23 12:11:45 +00001659 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001660 } else if (Record->getTemplateSpecializationKind()
1661 == TSK_ExplicitSpecialization) {
1662 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00001663 break;
1664 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001665
1666 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1667 T = Context.getTypeDeclType(Parent);
1668 else
1669 T = QualType();
1670 continue;
1671 }
1672
1673 if (const TemplateSpecializationType *TST
1674 = T->getAs<TemplateSpecializationType>()) {
1675 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1676 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1677 T = Context.getTypeDeclType(Parent);
1678 else
1679 T = QualType();
1680 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001681 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001682 }
1683
1684 // Look one step prior in a dependent template specialization type.
1685 if (const DependentTemplateSpecializationType *DependentTST
1686 = T->getAs<DependentTemplateSpecializationType>()) {
1687 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1688 T = QualType(NNS->getAsType(), 0);
1689 else
1690 T = QualType();
1691 continue;
1692 }
1693
1694 // Look one step prior in a dependent name type.
1695 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1696 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1697 T = QualType(NNS->getAsType(), 0);
1698 else
1699 T = QualType();
1700 continue;
1701 }
1702
1703 // Retrieve the parent of an enumeration type.
1704 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1705 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1706 // check here.
1707 EnumDecl *Enum = EnumT->getDecl();
1708
1709 // Get to the parent type.
1710 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1711 T = Context.getTypeDeclType(Parent);
1712 else
1713 T = QualType();
1714 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001715 }
Mike Stump11289f42009-09-09 15:08:12 +00001716
Douglas Gregor972fe532011-05-10 18:27:06 +00001717 T = QualType();
1718 }
1719 // Reverse the nested types list, since we want to traverse from the outermost
1720 // to the innermost while checking template-parameter-lists.
1721 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00001722
Douglas Gregor972fe532011-05-10 18:27:06 +00001723 // C++0x [temp.expl.spec]p17:
1724 // A member or a member template may be nested within many
1725 // enclosing class templates. In an explicit specialization for
1726 // such a member, the member declaration shall be preceded by a
1727 // template<> for each enclosing class template that is
1728 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001729 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00001730
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001731 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00001732 if (SawNonEmptyTemplateParameterList) {
1733 Diag(DeclLoc, diag::err_specialize_member_of_template)
1734 << !Recovery << Range;
1735 Invalid = true;
1736 IsExplicitSpecialization = false;
1737 return true;
1738 }
1739
1740 return false;
1741 };
1742
1743 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
1744 // Check that we can have an explicit specialization here.
1745 if (CheckExplicitSpecialization(Range, true))
1746 return true;
1747
1748 // We don't have a template header, but we should.
1749 SourceLocation ExpectedTemplateLoc;
1750 if (!ParamLists.empty())
1751 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1752 else
1753 ExpectedTemplateLoc = DeclStartLoc;
1754
1755 Diag(DeclLoc, diag::err_template_spec_needs_header)
1756 << Range
1757 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1758 return false;
1759 };
1760
Douglas Gregor972fe532011-05-10 18:27:06 +00001761 unsigned ParamIdx = 0;
1762 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1763 ++TypeIdx) {
1764 T = NestedTypes[TypeIdx];
1765
1766 // Whether we expect a 'template<>' header.
1767 bool NeedEmptyTemplateHeader = false;
1768
1769 // Whether we expect a template header with parameters.
1770 bool NeedNonemptyTemplateHeader = false;
1771
1772 // For a dependent type, the set of template parameters that we
1773 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00001774 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001775
Douglas Gregor373af9b2011-05-11 23:26:17 +00001776 // C++0x [temp.expl.spec]p15:
1777 // A member or a member template may be nested within many enclosing
1778 // class templates. In an explicit specialization for such a member, the
1779 // member declaration shall be preceded by a template<> for each
1780 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00001781 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1782 if (ClassTemplatePartialSpecializationDecl *Partial
1783 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1784 ExpectedTemplateParams = Partial->getTemplateParameters();
1785 NeedNonemptyTemplateHeader = true;
1786 } else if (Record->isDependentType()) {
1787 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00001788 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00001789 ->getTemplateParameters();
1790 NeedNonemptyTemplateHeader = true;
1791 }
1792 } else if (ClassTemplateSpecializationDecl *Spec
1793 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1794 // C++0x [temp.expl.spec]p4:
1795 // Members of an explicitly specialized class template are defined
1796 // in the same manner as members of normal classes, and not using
1797 // the template<> syntax.
1798 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1799 NeedEmptyTemplateHeader = true;
1800 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00001801 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001802 } else if (Record->getTemplateSpecializationKind()) {
1803 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00001804 != TSK_ExplicitSpecialization &&
1805 TypeIdx == NumTypes - 1)
1806 IsExplicitSpecialization = true;
1807
1808 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001809 }
1810 } else if (const TemplateSpecializationType *TST
1811 = T->getAs<TemplateSpecializationType>()) {
Nico Weber28900612015-01-30 02:35:21 +00001812 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001813 ExpectedTemplateParams = Template->getTemplateParameters();
1814 NeedNonemptyTemplateHeader = true;
1815 }
1816 } else if (T->getAs<DependentTemplateSpecializationType>()) {
1817 // FIXME: We actually could/should check the template arguments here
1818 // against the corresponding template parameter list.
1819 NeedNonemptyTemplateHeader = false;
1820 }
1821
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001822 // C++ [temp.expl.spec]p16:
1823 // In an explicit specialization declaration for a member of a class
1824 // template or a member template that ap- pears in namespace scope, the
1825 // member template and some of its enclosing class templates may remain
1826 // unspecialized, except that the declaration shall not explicitly
1827 // specialize a class member template if its en- closing class templates
1828 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001829 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001830 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001831 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1832 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00001833 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001834 } else
1835 SawNonEmptyTemplateParameterList = true;
1836 }
1837
Douglas Gregor972fe532011-05-10 18:27:06 +00001838 if (NeedEmptyTemplateHeader) {
1839 // If we're on the last of the types, and we need a 'template<>' header
1840 // here, then it's an explicit specialization.
1841 if (TypeIdx == NumTypes - 1)
1842 IsExplicitSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001843
1844 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001845 if (ParamLists[ParamIdx]->size() > 0) {
1846 // The header has template parameters when it shouldn't. Complain.
1847 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1848 diag::err_template_param_list_matches_nontemplate)
1849 << T
1850 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1851 ParamLists[ParamIdx]->getRAngleLoc())
1852 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1853 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00001854 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001855 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001856
Douglas Gregor972fe532011-05-10 18:27:06 +00001857 // Consume this template header.
1858 ++ParamIdx;
1859 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001860 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001861
1862 if (!IsFriend)
1863 if (DiagnoseMissingExplicitSpecialization(
1864 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00001865 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00001866
Douglas Gregor972fe532011-05-10 18:27:06 +00001867 continue;
1868 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001869
Douglas Gregor972fe532011-05-10 18:27:06 +00001870 if (NeedNonemptyTemplateHeader) {
1871 // In friend declarations we can have template-ids which don't
1872 // depend on the corresponding template parameter lists. But
1873 // assume that empty parameter lists are supposed to match this
1874 // template-id.
1875 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001876 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00001877 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00001878 ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001879 else
1880 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001881 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001882
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001883 if (ParamIdx < ParamLists.size()) {
1884 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00001885 if (ExpectedTemplateParams &&
1886 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1887 ExpectedTemplateParams,
1888 true, TPL_TemplateMatch))
1889 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00001890
Douglas Gregor972fe532011-05-10 18:27:06 +00001891 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00001892 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00001893 TPC_ClassTemplateMember))
1894 Invalid = true;
1895
1896 ++ParamIdx;
1897 continue;
1898 }
1899
1900 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
1901 << T
1902 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1903 Invalid = true;
1904 continue;
1905 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001906 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00001907
Douglas Gregord8d297c2009-07-21 23:53:31 +00001908 // If there were at least as many template-ids as there were template
1909 // parameter lists, then there are no template parameter lists remaining for
1910 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001911 if (ParamIdx >= ParamLists.size()) {
1912 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00001913 // We don't have a template header for the declaration itself, but we
1914 // should.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001915 IsExplicitSpecialization = true;
Richard Smith11a80dc2014-04-17 03:52:20 +00001916 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
1917 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00001918
1919 // Fabricate an empty template parameter list for the invented header.
1920 return TemplateParameterList::Create(Context, SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001921 SourceLocation(), nullptr, 0,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001922 SourceLocation());
1923 }
1924
Craig Topperc3ec1492014-05-26 06:22:03 +00001925 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00001926 }
Mike Stump11289f42009-09-09 15:08:12 +00001927
Douglas Gregord8d297c2009-07-21 23:53:31 +00001928 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001929 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001930 bool HasAnyExplicitSpecHeader = false;
1931 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001932 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001933 if (ParamLists[I]->size() == 0)
1934 HasAnyExplicitSpecHeader = true;
1935 else
1936 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001937 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001938
Douglas Gregor972fe532011-05-10 18:27:06 +00001939 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001940 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
1941 : diag::err_template_spec_extra_headers)
1942 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1943 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00001944
1945 // If there was a specialization somewhere, such that 'template<>' is
1946 // not required, and there were any 'template<>' headers, note where the
1947 // specialization occurred.
1948 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
1949 Diag(ExplicitSpecLoc,
1950 diag::note_explicit_template_spec_does_not_need_header)
1951 << NestedTypes.back();
1952
1953 // We have a template parameter list with no corresponding scope, which
1954 // means that the resulting template declaration can't be instantiated
1955 // properly (we'll end up with dependent nodes when we shouldn't).
1956 if (!AllExplicitSpecHeaders)
1957 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001958 }
Mike Stump11289f42009-09-09 15:08:12 +00001959
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001960 // C++ [temp.expl.spec]p16:
1961 // In an explicit specialization declaration for a member of a class
1962 // template or a member template that ap- pears in namespace scope, the
1963 // member template and some of its enclosing class templates may remain
1964 // unspecialized, except that the declaration shall not explicitly
1965 // specialize a class member template if its en- closing class templates
1966 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00001967 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001968 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1969 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00001970 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00001971
Douglas Gregord8d297c2009-07-21 23:53:31 +00001972 // Return the last template parameter list, which corresponds to the
1973 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001974 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001975}
1976
Douglas Gregor8b6070b2011-03-04 21:37:14 +00001977void Sema::NoteAllFoundTemplates(TemplateName Name) {
1978 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
1979 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00001980 << (isa<FunctionTemplateDecl>(Template)
1981 ? 0
1982 : isa<ClassTemplateDecl>(Template)
1983 ? 1
1984 : isa<VarTemplateDecl>(Template)
1985 ? 2
1986 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
1987 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00001988 return;
1989 }
1990
1991 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
1992 for (OverloadedTemplateStorage::iterator I = OST->begin(),
1993 IEnd = OST->end();
1994 I != IEnd; ++I)
1995 Diag((*I)->getLocation(), diag::note_template_declared_here)
1996 << 0 << (*I)->getDeclName();
1997
1998 return;
1999 }
2000}
2001
Douglas Gregordc572a32009-03-30 22:58:21 +00002002QualType Sema::CheckTemplateIdType(TemplateName Name,
2003 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002004 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00002005 DependentTemplateName *DTN
2006 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00002007 if (DTN && DTN->isIdentifier())
2008 // When building a template-id where the template-name is dependent,
2009 // assume the template is a type template. Either our assumption is
2010 // correct, or the code is ill-formed and will be diagnosed when the
2011 // dependent name is substituted.
2012 return Context.getDependentTemplateSpecializationType(ETK_None,
2013 DTN->getQualifier(),
2014 DTN->getIdentifier(),
2015 TemplateArgs);
2016
Douglas Gregordc572a32009-03-30 22:58:21 +00002017 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00002018 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2019 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002020 // We might have a substituted template template parameter pack. If so,
2021 // build a template specialization type for it.
2022 if (Name.getAsSubstTemplateTemplateParmPack())
2023 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002024
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002025 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2026 << Name;
2027 NoteAllFoundTemplates(Name);
2028 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00002029 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002030
Douglas Gregorc40290e2009-03-09 23:48:35 +00002031 // Check that the template argument list is well-formed for this
2032 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002033 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00002034 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00002035 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00002036 return QualType();
2037
Douglas Gregorc40290e2009-03-09 23:48:35 +00002038 QualType CanonType;
2039
Douglas Gregor678d76c2011-07-01 01:22:09 +00002040 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00002041 if (TypeAliasTemplateDecl *AliasTemplate =
2042 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00002043 // Find the canonical type for this type alias template specialization.
2044 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2045 if (Pattern->isInvalidDecl())
2046 return QualType();
2047
2048 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2049 Converted.data(), Converted.size());
2050
2051 // Only substitute for the innermost template argument list.
2052 MultiLevelTemplateArgumentList TemplateArgLists;
Richard Smith0c4a34b2011-05-14 15:04:18 +00002053 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00002054 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2055 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00002056 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002057
Richard Smith802c4b72012-08-23 06:16:52 +00002058 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002059 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002060 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00002061 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00002062
Richard Smith3f1b5d02011-05-05 21:57:07 +00002063 CanonType = SubstType(Pattern->getUnderlyingType(),
2064 TemplateArgLists, AliasTemplate->getLocation(),
2065 AliasTemplate->getDeclName());
2066 if (CanonType.isNull())
2067 return QualType();
2068 } else if (Name.isDependent() ||
2069 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00002070 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002071 // This class template specialization is a dependent
2072 // type. Therefore, its canonical type is another class template
2073 // specialization type that contains all of the converted
2074 // arguments in canonical form. This ensures that, e.g., A<T> and
2075 // A<T, T> have identical types when A is declared as:
2076 //
2077 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00002078 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002079 CanonType = Context.getTemplateSpecializationType(CanonName,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002080 Converted.data(),
2081 Converted.size());
Mike Stump11289f42009-09-09 15:08:12 +00002082
Douglas Gregora8e02e72009-07-28 23:00:59 +00002083 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00002084 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00002085 // In the future, we need to teach getTemplateSpecializationType to only
2086 // build the canonical type and return that to us.
2087 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00002088
2089 // This might work out to be a current instantiation, in which
2090 // case the canonical type needs to be the InjectedClassNameType.
2091 //
2092 // TODO: in theory this could be a simple hashtable lookup; most
2093 // changes to CurContext don't change the set of current
2094 // instantiations.
2095 if (isa<ClassTemplateDecl>(Template)) {
2096 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2097 // If we get out to a namespace, we're done.
2098 if (Ctx->isFileContext()) break;
2099
2100 // If this isn't a record, keep looking.
2101 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2102 if (!Record) continue;
2103
2104 // Look for one of the two cases with InjectedClassNameTypes
2105 // and check whether it's the same template.
2106 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2107 !Record->getDescribedClassTemplate())
2108 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002109
John McCall2408e322010-04-27 00:57:59 +00002110 // Fetch the injected class name type and check whether its
2111 // injected type is equal to the type we just built.
2112 QualType ICNT = Context.getTypeDeclType(Record);
2113 QualType Injected = cast<InjectedClassNameType>(ICNT)
2114 ->getInjectedSpecializationType();
2115
2116 if (CanonType != Injected->getCanonicalTypeInternal())
2117 continue;
2118
2119 // If so, the canonical type of this TST is the injected
2120 // class name type of the record we just found.
2121 assert(ICNT.isCanonical());
2122 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00002123 break;
2124 }
2125 }
Mike Stump11289f42009-09-09 15:08:12 +00002126 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002127 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002128 // Find the class template specialization declaration that
2129 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002130 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002131 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00002132 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002133 if (!Decl) {
2134 // This is the first time we have referenced this class template
2135 // specialization. Create the canonical declaration and add it to
2136 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002137 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002138 ClassTemplate->getTemplatedDecl()->getTagKind(),
2139 ClassTemplate->getDeclContext(),
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002140 ClassTemplate->getTemplatedDecl()->getLocStart(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002141 ClassTemplate->getLocation(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002142 ClassTemplate,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002143 Converted.data(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002144 Converted.size(), nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00002145 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00002146 if (ClassTemplate->isOutOfLine())
2147 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00002148 }
2149
Chandler Carruth2acfb222013-09-27 22:14:40 +00002150 // Diagnose uses of this specialization.
2151 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2152
Douglas Gregorc40290e2009-03-09 23:48:35 +00002153 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00002154 assert(isa<RecordType>(CanonType) &&
2155 "type of non-dependent specialization is not a RecordType");
Douglas Gregorc40290e2009-03-09 23:48:35 +00002156 }
Mike Stump11289f42009-09-09 15:08:12 +00002157
Douglas Gregorc40290e2009-03-09 23:48:35 +00002158 // Build the fully-sugared type for this class template
2159 // specialization, which refers back to the class template
2160 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00002161 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002162}
2163
John McCallfaf5fb42010-08-26 23:41:50 +00002164TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002165Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00002166 TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002167 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00002168 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002169 SourceLocation RAngleLoc,
2170 bool IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002171 if (SS.isInvalid())
2172 return true;
2173
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002174 TemplateName Template = TemplateD.get();
Douglas Gregor8bf42052009-02-09 18:46:07 +00002175
Douglas Gregorc40290e2009-03-09 23:48:35 +00002176 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00002177 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002178 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00002179
Douglas Gregor5a064722011-02-28 17:23:35 +00002180 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00002181 QualType T
2182 = Context.getDependentTemplateSpecializationType(ETK_None,
2183 DTN->getQualifier(),
2184 DTN->getIdentifier(),
2185 TemplateArgs);
2186 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00002187 TypeLocBuilder TLB;
2188 DependentTemplateSpecializationTypeLoc SpecTL
2189 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002190 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2191 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002192 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002193 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002194 SpecTL.setLAngleLoc(LAngleLoc);
2195 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002196 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2197 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2198 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2199 }
2200
John McCall6b51f282009-11-23 01:53:49 +00002201 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002202
2203 if (Result.isNull())
2204 return true;
2205
Douglas Gregore7c20652011-03-02 00:47:37 +00002206 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002207 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00002208 TemplateSpecializationTypeLoc SpecTL
2209 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002210 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002211 SpecTL.setTemplateNameLoc(TemplateLoc);
2212 SpecTL.setLAngleLoc(LAngleLoc);
2213 SpecTL.setRAngleLoc(RAngleLoc);
2214 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2215 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00002216
Abramo Bagnara4244b432012-01-27 08:46:19 +00002217 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2218 // constructor or destructor name (in such a case, the scope specifier
2219 // will be attached to the enclosing Decl or Expr node).
2220 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002221 // Create an elaborated-type-specifier containing the nested-name-specifier.
2222 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2223 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002224 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00002225 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2226 }
2227
2228 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00002229}
John McCall06f6fe8d2009-09-04 01:14:41 +00002230
Douglas Gregore7c20652011-03-02 00:47:37 +00002231TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00002232 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00002233 SourceLocation TagLoc,
2234 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002235 SourceLocation TemplateKWLoc,
2236 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00002237 SourceLocation TemplateLoc,
2238 SourceLocation LAngleLoc,
2239 ASTTemplateArgsPtr TemplateArgsIn,
2240 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002241 TemplateName Template = TemplateD.get();
Douglas Gregore7c20652011-03-02 00:47:37 +00002242
2243 // Translate the parser's template argument list in our AST format.
2244 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2245 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2246
2247 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00002248 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00002249 ElaboratedTypeKeyword Keyword
2250 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00002251
Douglas Gregore7c20652011-03-02 00:47:37 +00002252 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2253 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2254 DTN->getQualifier(),
2255 DTN->getIdentifier(),
2256 TemplateArgs);
2257
2258 // Build type-source information.
2259 TypeLocBuilder TLB;
2260 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002261 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2262 SpecTL.setElaboratedKeywordLoc(TagLoc);
2263 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002264 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002265 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002266 SpecTL.setLAngleLoc(LAngleLoc);
2267 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002268 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2269 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2270 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2271 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00002272
2273 if (TypeAliasTemplateDecl *TAT =
2274 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2275 // C++0x [dcl.type.elab]p2:
2276 // If the identifier resolves to a typedef-name or the simple-template-id
2277 // resolves to an alias template specialization, the
2278 // elaborated-type-specifier is ill-formed.
2279 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2280 Diag(TAT->getLocation(), diag::note_declared_at);
2281 }
Douglas Gregore7c20652011-03-02 00:47:37 +00002282
2283 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2284 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00002285 return TypeResult(true);
Douglas Gregore7c20652011-03-02 00:47:37 +00002286
2287 // Check the tag kind
2288 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00002289 RecordDecl *D = RT->getDecl();
Douglas Gregore7c20652011-03-02 00:47:37 +00002290
John McCalld8fe9af2009-09-08 17:47:29 +00002291 IdentifierInfo *Id = D->getIdentifier();
2292 assert(Id && "templated class must have an identifier");
Douglas Gregore7c20652011-03-02 00:47:37 +00002293
Richard Trieucaa33d32011-06-10 03:11:26 +00002294 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
2295 TagLoc, *Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00002296 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00002297 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00002298 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00002299 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00002300 }
2301 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002302
Douglas Gregore7c20652011-03-02 00:47:37 +00002303 // Provide source-location information for the template specialization.
2304 TypeLocBuilder TLB;
2305 TemplateSpecializationTypeLoc SpecTL
2306 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002307 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002308 SpecTL.setTemplateNameLoc(TemplateLoc);
2309 SpecTL.setLAngleLoc(LAngleLoc);
2310 SpecTL.setRAngleLoc(RAngleLoc);
2311 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2312 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00002313
Douglas Gregore7c20652011-03-02 00:47:37 +00002314 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002315 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00002316 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2317 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002318 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002319 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2320 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00002321}
2322
Larisse Voufo39a1e502013-08-06 01:03:05 +00002323static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002324 Sema &S, SourceLocation NameLoc, TemplateParameterList *TemplateParams,
2325 unsigned ExplicitArgs, SmallVectorImpl<TemplateArgument> &TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002326
2327static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
2328 NamedDecl *PrevDecl,
2329 SourceLocation Loc,
2330 bool IsPartialSpecialization);
2331
2332static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002333
Richard Smith300e0c32013-09-24 04:49:23 +00002334static bool isTemplateArgumentTemplateParameter(
2335 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
2336 switch (Arg.getKind()) {
2337 case TemplateArgument::Null:
2338 case TemplateArgument::NullPtr:
2339 case TemplateArgument::Integral:
2340 case TemplateArgument::Declaration:
2341 case TemplateArgument::Pack:
2342 case TemplateArgument::TemplateExpansion:
2343 return false;
2344
2345 case TemplateArgument::Type: {
2346 QualType Type = Arg.getAsType();
2347 const TemplateTypeParmType *TPT =
2348 Arg.getAsType()->getAs<TemplateTypeParmType>();
2349 return TPT && !Type.hasQualifiers() &&
2350 TPT->getDepth() == Depth && TPT->getIndex() == Index;
2351 }
2352
2353 case TemplateArgument::Expression: {
2354 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
2355 if (!DRE || !DRE->getDecl())
2356 return false;
2357 const NonTypeTemplateParmDecl *NTTP =
2358 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2359 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
2360 }
2361
2362 case TemplateArgument::Template:
2363 const TemplateTemplateParmDecl *TTP =
2364 dyn_cast_or_null<TemplateTemplateParmDecl>(
2365 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
2366 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
2367 }
2368 llvm_unreachable("unexpected kind of template argument");
2369}
2370
2371static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
2372 ArrayRef<TemplateArgument> Args) {
2373 if (Params->size() != Args.size())
2374 return false;
2375
2376 unsigned Depth = Params->getDepth();
2377
2378 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2379 TemplateArgument Arg = Args[I];
2380
2381 // If the parameter is a pack expansion, the argument must be a pack
2382 // whose only element is a pack expansion.
2383 if (Params->getParam(I)->isParameterPack()) {
2384 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
2385 !Arg.pack_begin()->isPackExpansion())
2386 return false;
2387 Arg = Arg.pack_begin()->getPackExpansionPattern();
2388 }
2389
2390 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
2391 return false;
2392 }
2393
2394 return true;
2395}
2396
Richard Smith4b55a9c2014-04-17 03:29:33 +00002397/// Convert the parser's template argument list representation into our form.
2398static TemplateArgumentListInfo
2399makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
2400 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
2401 TemplateId.RAngleLoc);
2402 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
2403 TemplateId.NumArgs);
2404 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
2405 return TemplateArgs;
2406}
2407
Larisse Voufo39a1e502013-08-06 01:03:05 +00002408DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00002409 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00002410 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00002411 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002412 // D must be variable template id.
2413 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2414 "Variable template specialization is declared with a template it.");
2415
2416 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002417 TemplateArgumentListInfo TemplateArgs =
2418 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002419 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2420 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2421 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002422
Richard Smithbeef3452014-01-16 23:39:20 +00002423 TemplateName Name = TemplateId->Template.get();
2424
2425 // The template-id must name a variable template.
2426 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00002427 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
2428 if (!VarTemplate) {
2429 NamedDecl *FnTemplate;
2430 if (auto *OTS = Name.getAsOverloadedTemplate())
2431 FnTemplate = *OTS->begin();
2432 else
2433 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
2434 if (FnTemplate)
2435 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
2436 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00002437 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
2438 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00002439 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002440
2441 // Check for unexpanded parameter packs in any of the template arguments.
2442 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2443 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2444 UPPC_PartialSpecialization))
2445 return true;
2446
2447 // Check that the template argument list is well-formed for this
2448 // template.
2449 SmallVector<TemplateArgument, 4> Converted;
2450 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2451 false, Converted))
2452 return true;
2453
2454 // Check that the type of this variable template specialization
2455 // matches the expected type.
2456 TypeSourceInfo *ExpectedDI;
2457 {
2458 // Do substitution on the type of the declaration
2459 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2460 Converted.data(), Converted.size());
2461 InstantiatingTemplate Inst(*this, TemplateKWLoc, VarTemplate);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002462 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002463 return true;
2464 VarDecl *Templated = VarTemplate->getTemplatedDecl();
2465 ExpectedDI =
2466 SubstType(Templated->getTypeSourceInfo(),
2467 MultiLevelTemplateArgumentList(TemplateArgList),
2468 Templated->getTypeSpecStartLoc(), Templated->getDeclName());
2469 }
2470 if (!ExpectedDI)
2471 return true;
2472
Larisse Voufo39a1e502013-08-06 01:03:05 +00002473 // Find the variable template (partial) specialization declaration that
2474 // corresponds to these arguments.
2475 if (IsPartialSpecialization) {
2476 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002477 *this, TemplateNameLoc, VarTemplate->getTemplateParameters(),
2478 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002479 return true;
2480
2481 bool InstantiationDependent;
2482 if (!Name.isDependent() &&
2483 !TemplateSpecializationType::anyDependentTemplateArguments(
2484 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
2485 InstantiationDependent)) {
2486 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2487 << VarTemplate->getDeclName();
2488 IsPartialSpecialization = false;
2489 }
Richard Smith300e0c32013-09-24 04:49:23 +00002490
2491 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
2492 Converted)) {
2493 // C++ [temp.class.spec]p9b3:
2494 //
2495 // -- The argument list of the specialization shall not be identical
2496 // to the implicit argument list of the primary template.
2497 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2498 << /*variable template*/ 1
2499 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2500 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2501 // FIXME: Recover from this by treating the declaration as a redeclaration
2502 // of the primary template.
2503 return true;
2504 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002505 }
2506
Craig Topperc3ec1492014-05-26 06:22:03 +00002507 void *InsertPos = nullptr;
2508 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002509
2510 if (IsPartialSpecialization)
2511 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00002512 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002513 else
Craig Topper7e0daca2014-06-26 04:58:53 +00002514 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002515
Craig Topperc3ec1492014-05-26 06:22:03 +00002516 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002517
2518 // Check whether we can declare a variable template specialization in
2519 // the current scope.
2520 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
2521 TemplateNameLoc,
2522 IsPartialSpecialization))
2523 return true;
2524
2525 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2526 // Since the only prior variable template specialization with these
2527 // arguments was referenced but not declared, reuse that
2528 // declaration node as our own, updating its source location and
2529 // the list of outer template parameters to reflect our new declaration.
2530 Specialization = PrevDecl;
2531 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002532 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002533 } else if (IsPartialSpecialization) {
2534 // Create a new class template partial specialization declaration node.
2535 VarTemplatePartialSpecializationDecl *PrevPartial =
2536 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002537 VarTemplatePartialSpecializationDecl *Partial =
2538 VarTemplatePartialSpecializationDecl::Create(
2539 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
2540 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
Richard Smithb2f61b42013-08-22 23:27:37 +00002541 Converted.data(), Converted.size(), TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002542
2543 if (!PrevPartial)
2544 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
2545 Specialization = Partial;
2546
2547 // If we are providing an explicit specialization of a member variable
2548 // template specialization, make a note of that.
2549 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00002550 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002551
2552 // Check that all of the template parameters of the variable template
2553 // partial specialization are deducible from the template
2554 // arguments. If not, this variable template partial specialization
2555 // will never be used.
2556 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
2557 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2558 TemplateParams->getDepth(), DeducibleParams);
2559
2560 if (!DeducibleParams.all()) {
2561 unsigned NumNonDeducible =
2562 DeducibleParams.size() - DeducibleParams.count();
2563 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00002564 << /*variable template*/ 1 << (NumNonDeducible > 1)
2565 << SourceRange(TemplateNameLoc, RAngleLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002566 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2567 if (!DeducibleParams[I]) {
2568 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2569 if (Param->getDeclName())
2570 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2571 << Param->getDeclName();
2572 else
2573 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00002574 << "(anonymous)";
Larisse Voufo39a1e502013-08-06 01:03:05 +00002575 }
2576 }
2577 }
2578 } else {
2579 // Create a new class template specialization declaration node for
2580 // this explicit specialization or friend declaration.
2581 Specialization = VarTemplateSpecializationDecl::Create(
2582 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
2583 VarTemplate, DI->getType(), DI, SC, Converted.data(), Converted.size());
2584 Specialization->setTemplateArgsInfo(TemplateArgs);
2585
2586 if (!PrevDecl)
2587 VarTemplate->AddSpecialization(Specialization, InsertPos);
2588 }
2589
2590 // C++ [temp.expl.spec]p6:
2591 // If a template, a member template or the member of a class template is
2592 // explicitly specialized then that specialization shall be declared
2593 // before the first use of that specialization that would cause an implicit
2594 // instantiation to take place, in every translation unit in which such a
2595 // use occurs; no diagnostic is required.
2596 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2597 bool Okay = false;
2598 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
2599 // Is there any previous explicit specialization declaration?
2600 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
2601 Okay = true;
2602 break;
2603 }
2604 }
2605
2606 if (!Okay) {
2607 SourceRange Range(TemplateNameLoc, RAngleLoc);
2608 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2609 << Name << Range;
2610
2611 Diag(PrevDecl->getPointOfInstantiation(),
2612 diag::note_instantiation_required_here)
2613 << (PrevDecl->getTemplateSpecializationKind() !=
2614 TSK_ImplicitInstantiation);
2615 return true;
2616 }
2617 }
2618
2619 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
2620 Specialization->setLexicalDeclContext(CurContext);
2621
2622 // Add the specialization into its lexical context, so that it can
2623 // be seen when iterating through the list of declarations in that
2624 // context. However, specializations are not found by name lookup.
2625 CurContext->addDecl(Specialization);
2626
2627 // Note that this is an explicit specialization.
2628 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2629
2630 if (PrevDecl) {
2631 // Check that this isn't a redefinition of this specialization,
2632 // merging with previous declarations.
2633 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
2634 ForRedeclaration);
2635 PrevSpec.addDecl(PrevDecl);
2636 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00002637 } else if (Specialization->isStaticDataMember() &&
2638 Specialization->isOutOfLine()) {
2639 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00002640 }
2641
2642 // Link instantiations of static data members back to the template from
2643 // which they were instantiated.
2644 if (Specialization->isStaticDataMember())
2645 Specialization->setInstantiationOfStaticDataMember(
2646 VarTemplate->getTemplatedDecl(),
2647 Specialization->getSpecializationKind());
2648
2649 return Specialization;
2650}
2651
2652namespace {
2653/// \brief A partial specialization whose template arguments have matched
2654/// a given template-id.
2655struct PartialSpecMatchResult {
2656 VarTemplatePartialSpecializationDecl *Partial;
2657 TemplateArgumentList *Args;
2658};
2659}
2660
2661DeclResult
2662Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
2663 SourceLocation TemplateNameLoc,
2664 const TemplateArgumentListInfo &TemplateArgs) {
2665 assert(Template && "A variable template id without template?");
2666
2667 // Check that the template argument list is well-formed for this template.
2668 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002669 if (CheckTemplateArgumentList(
2670 Template, TemplateNameLoc,
2671 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00002672 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002673 return true;
2674
2675 // Find the variable template specialization declaration that
2676 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002677 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002678 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +00002679 Converted, InsertPos))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002680 // If we already have a variable template specialization, return it.
2681 return Spec;
2682
2683 // This is the first time we have referenced this variable template
2684 // specialization. Create the canonical declaration and add it to
2685 // the set of specializations, based on the closest partial specialization
2686 // that it represents. That is,
2687 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
2688 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2689 Converted.data(), Converted.size());
2690 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
2691 bool AmbiguousPartialSpec = false;
2692 typedef PartialSpecMatchResult MatchResult;
2693 SmallVector<MatchResult, 4> Matched;
2694 SourceLocation PointOfInstantiation = TemplateNameLoc;
2695 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2696
2697 // 1. Attempt to find the closest partial specialization that this
2698 // specializes, if any.
2699 // If any of the template arguments is dependent, then this is probably
2700 // a placeholder for an incomplete declarative context; which must be
2701 // complete by instantiation time. Thus, do not search through the partial
2702 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00002703 // TODO: Unify with InstantiateClassTemplateSpecialization()?
2704 // Perhaps better after unification of DeduceTemplateArguments() and
2705 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00002706 bool InstantiationDependent = false;
2707 if (!TemplateSpecializationType::anyDependentTemplateArguments(
2708 TemplateArgs, InstantiationDependent)) {
2709
2710 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2711 Template->getPartialSpecializations(PartialSpecs);
2712
2713 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2714 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2715 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2716
2717 if (TemplateDeductionResult Result =
2718 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
2719 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00002720 // TODO: Actually use the failed-deduction info?
Larisse Voufo39a1e502013-08-06 01:03:05 +00002721 FailedCandidates.addCandidate()
2722 .set(Partial, MakeDeductionFailureInfo(Context, Result, Info));
2723 (void)Result;
2724 } else {
2725 Matched.push_back(PartialSpecMatchResult());
2726 Matched.back().Partial = Partial;
2727 Matched.back().Args = Info.take();
2728 }
2729 }
2730
Larisse Voufo39a1e502013-08-06 01:03:05 +00002731 if (Matched.size() >= 1) {
2732 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
2733 if (Matched.size() == 1) {
2734 // -- If exactly one matching specialization is found, the
2735 // instantiation is generated from that specialization.
2736 // We don't need to do anything for this.
2737 } else {
2738 // -- If more than one matching specialization is found, the
2739 // partial order rules (14.5.4.2) are used to determine
2740 // whether one of the specializations is more specialized
2741 // than the others. If none of the specializations is more
2742 // specialized than all of the other matching
2743 // specializations, then the use of the variable template is
2744 // ambiguous and the program is ill-formed.
2745 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
2746 PEnd = Matched.end();
2747 P != PEnd; ++P) {
2748 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2749 PointOfInstantiation) ==
2750 P->Partial)
2751 Best = P;
2752 }
2753
2754 // Determine if the best partial specialization is more specialized than
2755 // the others.
2756 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2757 PEnd = Matched.end();
2758 P != PEnd; ++P) {
2759 if (P != Best && getMoreSpecializedPartialSpecialization(
2760 P->Partial, Best->Partial,
2761 PointOfInstantiation) != Best->Partial) {
2762 AmbiguousPartialSpec = true;
2763 break;
2764 }
2765 }
2766 }
2767
2768 // Instantiate using the best variable template partial specialization.
2769 InstantiationPattern = Best->Partial;
2770 InstantiationArgs = Best->Args;
2771 } else {
2772 // -- If no match is found, the instantiation is generated
2773 // from the primary template.
2774 // InstantiationPattern = Template->getTemplatedDecl();
2775 }
2776 }
2777
Larisse Voufo39a1e502013-08-06 01:03:05 +00002778 // 2. Create the canonical declaration.
2779 // Note that we do not instantiate the variable just yet, since
2780 // instantiation is handled in DoMarkVarDeclReferenced().
2781 // FIXME: LateAttrs et al.?
2782 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
2783 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
2784 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
2785 if (!Decl)
2786 return true;
2787
2788 if (AmbiguousPartialSpec) {
2789 // Partial ordering did not produce a clear winner. Complain.
2790 Decl->setInvalidDecl();
2791 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2792 << Decl;
2793
2794 // Print the matching partial specializations.
2795 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2796 PEnd = Matched.end();
2797 P != PEnd; ++P)
2798 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2799 << getTemplateArgumentBindingsText(
2800 P->Partial->getTemplateParameters(), *P->Args);
2801 return true;
2802 }
2803
2804 if (VarTemplatePartialSpecializationDecl *D =
2805 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
2806 Decl->setInstantiationOf(D, InstantiationArgs);
2807
2808 assert(Decl && "No variable template specialization?");
2809 return Decl;
2810}
2811
2812ExprResult
2813Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
2814 const DeclarationNameInfo &NameInfo,
2815 VarTemplateDecl *Template, SourceLocation TemplateLoc,
2816 const TemplateArgumentListInfo *TemplateArgs) {
2817
2818 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
2819 *TemplateArgs);
2820 if (Decl.isInvalid())
2821 return ExprError();
2822
2823 VarDecl *Var = cast<VarDecl>(Decl.get());
2824 if (!Var->getTemplateSpecializationKind())
2825 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
2826 NameInfo.getLoc());
2827
2828 // Build an ordinary singleton decl ref.
2829 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00002830 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002831}
2832
John McCalldadc5752010-08-24 06:29:42 +00002833ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002834 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00002835 LookupResult &R,
2836 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002837 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00002838 // FIXME: Can we do any checking at this point? I guess we could check the
2839 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00002840 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00002841 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00002842 // foo<int> could identify a single function unambiguously
2843 // This approach does NOT work, since f<int>(1);
2844 // gets resolved prior to resorting to overload resolution
2845 // i.e., template<class T> void f(double);
2846 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00002847
2848 // These should be filtered out by our callers.
2849 assert(!R.empty() && "empty lookup results when building templateid");
2850 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
2851
Larisse Voufo39a1e502013-08-06 01:03:05 +00002852 // In C++1y, check variable template ids.
Richard Smithd7d11ef2014-02-03 20:09:56 +00002853 bool InstantiationDependent;
2854 if (R.getAsSingle<VarTemplateDecl>() &&
2855 !TemplateSpecializationType::anyDependentTemplateArguments(
2856 *TemplateArgs, InstantiationDependent)) {
2857 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
2858 R.getAsSingle<VarTemplateDecl>(),
2859 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002860 }
2861
John McCall58cc69d2010-01-27 01:50:18 +00002862 // We don't want lookup warnings at this point.
2863 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002864
John McCalle66edc12009-11-24 19:00:30 +00002865 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002866 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002867 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002868 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002869 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002870 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002871 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00002872
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002873 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00002874}
2875
John McCalle66edc12009-11-24 19:00:30 +00002876// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00002877ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002878Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002879 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002880 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002881 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002882
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002883 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00002884 DeclContext *DC;
2885 if (!(DC = computeDeclContext(SS, false)) ||
2886 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00002887 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00002888 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00002889
Douglas Gregor786123d2010-05-21 23:18:07 +00002890 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002891 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Craig Topperc3ec1492014-05-26 06:22:03 +00002892 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
Douglas Gregor786123d2010-05-21 23:18:07 +00002893 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00002894
John McCalle66edc12009-11-24 19:00:30 +00002895 if (R.isAmbiguous())
2896 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002897
John McCalle66edc12009-11-24 19:00:30 +00002898 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002899 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
2900 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002901 return ExprError();
2902 }
2903
2904 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002905 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00002906 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00002907 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002908 Diag(Temp->getLocation(), diag::note_referenced_class_template);
2909 return ExprError();
2910 }
2911
Abramo Bagnara7945c982012-01-27 09:46:47 +00002912 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00002913}
2914
Douglas Gregorb67535d2009-03-31 00:43:58 +00002915/// \brief Form a dependent template name.
2916///
2917/// This action forms a dependent template name given the template
2918/// name and its (presumably dependent) scope specifier. For
2919/// example, given "MetaFun::template apply", the scope specifier \p
2920/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
2921/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002922TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00002923 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002924 SourceLocation TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00002925 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00002926 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00002927 bool EnteringContext,
2928 TemplateTy &Result) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00002929 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
2930 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002931 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002932 diag::warn_cxx98_compat_template_outside_of_template :
2933 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002934 << FixItHint::CreateRemoval(TemplateKWLoc);
2935
Craig Topperc3ec1492014-05-26 06:22:03 +00002936 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00002937 if (SS.isSet())
2938 LookupCtx = computeDeclContext(SS, EnteringContext);
2939 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00002940 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00002941 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00002942 // C++0x [temp.names]p5:
2943 // If a name prefixed by the keyword template is not the name of
2944 // a template, the program is ill-formed. [Note: the keyword
2945 // template may not be applied to non-template members of class
2946 // templates. -end note ] [ Note: as is the case with the
2947 // typename prefix, the template prefix is allowed in cases
2948 // where it is not strictly necessary; i.e., when the
2949 // nested-name-specifier or the expression on the left of the ->
2950 // or . is not dependent on a template-parameter, or the use
2951 // does not appear in the scope of a template. -end note]
2952 //
2953 // Note: C++03 was more strict here, because it banned the use of
2954 // the "template" keyword prior to a template-name that was not a
2955 // dependent name. C++ DR468 relaxed this requirement (the
2956 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00002957 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00002958 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00002959 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002960 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00002961 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00002962 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
2963 isa<CXXRecordDecl>(LookupCtx) &&
Douglas Gregor5ecbb1b2011-03-11 23:27:41 +00002964 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
2965 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
Douglas Gregorbb119652010-06-16 23:00:59 +00002966 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00002967 } else if (TNK == TNK_Non_template) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002968 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00002969 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002970 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00002971 << Name.getSourceRange()
2972 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00002973 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00002974 } else {
2975 // We found something; return it.
Douglas Gregorbb119652010-06-16 23:00:59 +00002976 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00002977 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00002978 }
2979
Aaron Ballman4a979672014-01-03 13:56:08 +00002980 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002981
Douglas Gregor3cf81312009-11-03 23:16:33 +00002982 switch (Name.getKind()) {
2983 case UnqualifiedId::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002984 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00002985 Name.Identifier));
2986 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002987
Douglas Gregor71395fa2009-11-04 00:56:37 +00002988 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00002989 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00002990 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00002991 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00002992
2993 case UnqualifiedId::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00002994 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00002995
Douglas Gregor3cf81312009-11-03 23:16:33 +00002996 default:
2997 break;
2998 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002999
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003000 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003001 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003002 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003003 << Name.getSourceRange()
3004 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003005 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003006}
3007
Mike Stump11289f42009-09-09 15:08:12 +00003008bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003009 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003010 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00003011 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00003012 QualType ArgType;
3013 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00003014
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003015 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003016 switch(Arg.getKind()) {
3017 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003018 // C++ [temp.arg.type]p1:
3019 // A template-argument for a template-parameter which is a
3020 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00003021 ArgType = Arg.getAsType();
3022 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003023 break;
3024 case TemplateArgument::Template: {
3025 // We have a template type parameter but the template argument
3026 // is a template without any arguments.
3027 SourceRange SR = AL.getSourceRange();
3028 TemplateName Name = Arg.getAsTemplate();
3029 Diag(SR.getBegin(), diag::err_template_missing_args)
3030 << Name << SR;
3031 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3032 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003033
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003034 return true;
3035 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003036 case TemplateArgument::Expression: {
3037 // We have a template type parameter but the template argument is an
3038 // expression; see if maybe it is missing the "typename" keyword.
3039 CXXScopeSpec SS;
3040 DeclarationNameInfo NameInfo;
3041
3042 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3043 SS.Adopt(ArgExpr->getQualifierLoc());
3044 NameInfo = ArgExpr->getNameInfo();
3045 } else if (DependentScopeDeclRefExpr *ArgExpr =
3046 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3047 SS.Adopt(ArgExpr->getQualifierLoc());
3048 NameInfo = ArgExpr->getNameInfo();
3049 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3050 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003051 if (ArgExpr->isImplicitAccess()) {
3052 SS.Adopt(ArgExpr->getQualifierLoc());
3053 NameInfo = ArgExpr->getMemberNameInfo();
3054 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003055 }
3056
Reid Kleckner377c1592014-06-10 23:29:48 +00003057 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003058 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3059 LookupParsedName(Result, CurScope, &SS);
3060
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003061 if (Result.getAsSingle<TypeDecl>() ||
3062 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00003063 LookupResult::NotFoundInCurrentInstantiation) {
3064 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003065 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00003066 Diag(Loc, getLangOpts().MSVCCompat
3067 ? diag::ext_ms_template_type_arg_missing_typename
3068 : diag::err_template_arg_must_be_type_suggest)
3069 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003070 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00003071
3072 // Recover by synthesizing a type using the location information that we
3073 // already have.
3074 ArgType =
3075 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3076 TypeLocBuilder TLB;
3077 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3078 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3079 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3080 TL.setNameLoc(NameInfo.getLoc());
3081 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3082
3083 // Overwrite our input TemplateArgumentLoc so that we can recover
3084 // properly.
3085 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3086 TemplateArgumentLocInfo(TSI));
3087
3088 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003089 }
3090 }
3091 // fallthrough
3092 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003093 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003094 // We have a template type parameter but the template argument
3095 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00003096 SourceRange SR = AL.getSourceRange();
3097 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003098 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003099
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003100 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003101 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003102 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003103
Reid Kleckner377c1592014-06-10 23:29:48 +00003104 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003105 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003106
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003107 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00003108 ArgType = Context.getCanonicalType(ArgType);
Douglas Gregore46db902011-06-17 22:11:49 +00003109
3110 // Objective-C ARC:
3111 // If an explicitly-specified template argument type is a lifetime type
3112 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003113 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00003114 ArgType->isObjCLifetimeType() &&
3115 !ArgType.getObjCLifetime()) {
3116 Qualifiers Qs;
3117 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3118 ArgType = Context.getQualifiedType(ArgType, Qs);
3119 }
3120
3121 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003122 return false;
3123}
3124
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003125/// \brief Substitute template arguments into the default template argument for
3126/// the given template type parameter.
3127///
3128/// \param SemaRef the semantic analysis object for which we are performing
3129/// the substitution.
3130///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003131/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003132/// for.
3133///
3134/// \param TemplateLoc the location of the template name that started the
3135/// template-id we are checking.
3136///
3137/// \param RAngleLoc the location of the right angle bracket ('>') that
3138/// terminates the template-id.
3139///
3140/// \param Param the template template parameter whose default we are
3141/// substituting into.
3142///
3143/// \param Converted the list of template arguments provided for template
3144/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003145/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00003146static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003147SubstDefaultTemplateArgument(Sema &SemaRef,
3148 TemplateDecl *Template,
3149 SourceLocation TemplateLoc,
3150 SourceLocation RAngleLoc,
3151 TemplateTypeParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003152 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00003153 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003154
3155 // If the argument type is dependent, instantiate it now based
3156 // on the previously-computed template arguments.
3157 if (ArgType->getType()->isDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003158 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith80934652012-07-16 01:09:10 +00003159 Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003160 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003161 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00003162 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003163
David Majnemer89189202013-08-28 23:48:32 +00003164 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3165 Converted.data(), Converted.size());
3166
3167 // Only substitute for the innermost template argument list.
3168 MultiLevelTemplateArgumentList TemplateArgLists;
3169 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3170 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3171 TemplateArgLists.addOuterTemplateArguments(None);
3172
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003173 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003174 ArgType =
3175 SemaRef.SubstType(ArgType, TemplateArgLists,
3176 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003177 }
3178
3179 return ArgType;
3180}
3181
3182/// \brief Substitute template arguments into the default template argument for
3183/// the given non-type template parameter.
3184///
3185/// \param SemaRef the semantic analysis object for which we are performing
3186/// the substitution.
3187///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003188/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003189/// for.
3190///
3191/// \param TemplateLoc the location of the template name that started the
3192/// template-id we are checking.
3193///
3194/// \param RAngleLoc the location of the right angle bracket ('>') that
3195/// terminates the template-id.
3196///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003197/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003198/// substituting into.
3199///
3200/// \param Converted the list of template arguments provided for template
3201/// parameters that precede \p Param in the template parameter list.
3202///
3203/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00003204static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003205SubstDefaultTemplateArgument(Sema &SemaRef,
3206 TemplateDecl *Template,
3207 SourceLocation TemplateLoc,
3208 SourceLocation RAngleLoc,
3209 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003210 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003211 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith80934652012-07-16 01:09:10 +00003212 Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003213 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003214 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003215 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003216
David Majnemer89189202013-08-28 23:48:32 +00003217 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3218 Converted.data(), Converted.size());
3219
3220 // Only substitute for the innermost template argument list.
3221 MultiLevelTemplateArgumentList TemplateArgLists;
3222 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3223 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3224 TemplateArgLists.addOuterTemplateArguments(None);
3225
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003226 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
Eli Friedmanc25372b2012-04-26 22:43:24 +00003227 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
David Majnemer89189202013-08-28 23:48:32 +00003228 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003229}
3230
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003231/// \brief Substitute template arguments into the default template argument for
3232/// the given template template parameter.
3233///
3234/// \param SemaRef the semantic analysis object for which we are performing
3235/// the substitution.
3236///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003237/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003238/// for.
3239///
3240/// \param TemplateLoc the location of the template name that started the
3241/// template-id we are checking.
3242///
3243/// \param RAngleLoc the location of the right angle bracket ('>') that
3244/// terminates the template-id.
3245///
3246/// \param Param the template template parameter whose default we are
3247/// substituting into.
3248///
3249/// \param Converted the list of template arguments provided for template
3250/// parameters that precede \p Param in the template parameter list.
3251///
Douglas Gregordf846d12011-03-02 18:46:51 +00003252/// \param QualifierLoc Will be set to the nested-name-specifier (with
3253/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00003254///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003255/// \returns the substituted template argument, or NULL if an error occurred.
3256static TemplateName
3257SubstDefaultTemplateArgument(Sema &SemaRef,
3258 TemplateDecl *Template,
3259 SourceLocation TemplateLoc,
3260 SourceLocation RAngleLoc,
3261 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003262 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00003263 NestedNameSpecifierLoc &QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003264 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Template, Converted,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003265 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003266 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003267 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003268
David Majnemer89189202013-08-28 23:48:32 +00003269 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3270 Converted.data(), Converted.size());
3271
3272 // Only substitute for the innermost template argument list.
3273 MultiLevelTemplateArgumentList TemplateArgLists;
3274 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3275 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3276 TemplateArgLists.addOuterTemplateArguments(None);
3277
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003278 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003279 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00003280 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00003281 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003282 QualifierLoc =
3283 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00003284 if (!QualifierLoc)
3285 return TemplateName();
3286 }
David Majnemer89189202013-08-28 23:48:32 +00003287
3288 return SemaRef.SubstTemplateName(
3289 QualifierLoc,
3290 Param->getDefaultArgument().getArgument().getAsTemplate(),
3291 Param->getDefaultArgument().getTemplateNameLoc(),
3292 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003293}
3294
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003295/// \brief If the given template parameter has a default template
3296/// argument, substitute into that default template argument and
3297/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003298TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003299Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3300 SourceLocation TemplateLoc,
3301 SourceLocation RAngleLoc,
3302 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00003303 SmallVectorImpl<TemplateArgument>
3304 &Converted,
3305 bool &HasDefaultArg) {
3306 HasDefaultArg = false;
3307
3308 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003309 if (!TypeParm->hasDefaultArgument())
3310 return TemplateArgumentLoc();
3311
Richard Smithc87b9382013-07-04 01:01:24 +00003312 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00003313 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003314 TemplateLoc,
3315 RAngleLoc,
3316 TypeParm,
3317 Converted);
3318 if (DI)
3319 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3320
3321 return TemplateArgumentLoc();
3322 }
3323
3324 if (NonTypeTemplateParmDecl *NonTypeParm
3325 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3326 if (!NonTypeParm->hasDefaultArgument())
3327 return TemplateArgumentLoc();
3328
Richard Smithc87b9382013-07-04 01:01:24 +00003329 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00003330 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00003331 TemplateLoc,
3332 RAngleLoc,
3333 NonTypeParm,
3334 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003335 if (Arg.isInvalid())
3336 return TemplateArgumentLoc();
3337
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003338 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003339 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3340 }
3341
3342 TemplateTemplateParmDecl *TempTempParm
3343 = cast<TemplateTemplateParmDecl>(Param);
3344 if (!TempTempParm->hasDefaultArgument())
3345 return TemplateArgumentLoc();
3346
Richard Smithc87b9382013-07-04 01:01:24 +00003347 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00003348 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003349 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003350 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003351 RAngleLoc,
3352 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003353 Converted,
3354 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003355 if (TName.isNull())
3356 return TemplateArgumentLoc();
3357
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003358 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00003359 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003360 TempTempParm->getDefaultArgument().getTemplateNameLoc());
3361}
3362
Douglas Gregorda0fb532009-11-11 19:31:23 +00003363/// \brief Check that the given template argument corresponds to the given
3364/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003365///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003366/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003367/// checked.
3368///
Richard Trieu15b66532015-01-24 02:48:32 +00003369/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003370///
3371/// \param Template The template in which the template argument resides.
3372///
3373/// \param TemplateLoc The location of the template name for the template
3374/// whose argument list we're matching.
3375///
3376/// \param RAngleLoc The location of the right angle bracket ('>') that closes
3377/// the template argument list.
3378///
3379/// \param ArgumentPackIndex The index into the argument pack where this
3380/// argument will be placed. Only valid if the parameter is a parameter pack.
3381///
3382/// \param Converted The checked, converted argument will be added to the
3383/// end of this small vector.
3384///
3385/// \param CTAK Describes how we arrived at this particular template argument:
3386/// explicitly written, deduced, etc.
3387///
3388/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003389bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003390 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00003391 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003392 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003393 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003394 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003395 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003396 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00003397 // Check template type parameters.
3398 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003399 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003400
Douglas Gregoreebed722009-11-11 19:41:09 +00003401 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003402 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003403 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00003404 // with the template arguments we've seen thus far. But if the
3405 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003406 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003407 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3408 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003409
Peter Collingbourne01687632010-12-10 17:08:53 +00003410 if (NTTPType->isDependentType() &&
3411 !isa<TemplateTemplateParmDecl>(Template) &&
3412 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003413 // Do substitution on the type of the non-type template parameter.
3414 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003415 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003416 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003417 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003418 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003419
3420 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003421 Converted.data(), Converted.size());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003422 NTTPType = SubstType(NTTPType,
3423 MultiLevelTemplateArgumentList(TemplateArgs),
3424 NTTP->getLocation(),
3425 NTTP->getDeclName());
3426 // If that worked, check the non-type template parameter type
3427 // for validity.
3428 if (!NTTPType.isNull())
3429 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3430 NTTP->getLocation());
3431 if (NTTPType.isNull())
3432 return true;
3433 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003434
Douglas Gregorda0fb532009-11-11 19:31:23 +00003435 switch (Arg.getArgument().getKind()) {
3436 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003437 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003438
Douglas Gregorda0fb532009-11-11 19:31:23 +00003439 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003440 TemplateArgument Result;
John Wiegley01296292011-04-08 18:41:53 +00003441 ExprResult Res =
3442 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3443 Result, CTAK);
3444 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003445 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003446
Richard Trieu15b66532015-01-24 02:48:32 +00003447 // If the resulting expression is new, then use it in place of the
3448 // old expression in the template argument.
3449 if (Res.get() != Arg.getArgument().getAsExpr()) {
3450 TemplateArgument TA(Res.get());
3451 Arg = TemplateArgumentLoc(TA, Res.get());
3452 }
3453
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003454 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003455 break;
3456 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003457
Douglas Gregorda0fb532009-11-11 19:31:23 +00003458 case TemplateArgument::Declaration:
3459 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00003460 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003461 // We've already checked this template argument, so just copy
3462 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003463 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003464 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003465
Douglas Gregorda0fb532009-11-11 19:31:23 +00003466 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003467 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003468 // We were given a template template argument. It may not be ill-formed;
3469 // see below.
3470 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003471 = Arg.getArgument().getAsTemplateOrTemplatePattern()
3472 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003473 // We have a template argument such as \c T::template X, which we
3474 // parsed as a template template argument. However, since we now
3475 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003476 // template name into an expression.
3477
3478 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3479 Arg.getTemplateNameLoc());
3480
Douglas Gregor3a43fd62011-02-25 20:49:16 +00003481 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00003482 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00003483 // FIXME: the template-template arg was a DependentTemplateName,
3484 // so it was provided with a template keyword. However, its source
3485 // location is not stored in the template argument structure.
3486 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003487 ExprResult E = DependentScopeDeclRefExpr::Create(
3488 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
3489 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003490
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003491 // If we parsed the template argument as a pack expansion, create a
3492 // pack expansion expression.
3493 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003494 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00003495 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003496 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003497 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003498
Douglas Gregorda0fb532009-11-11 19:31:23 +00003499 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003500 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00003501 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003502 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003503
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003504 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003505 break;
3506 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003507
Douglas Gregorda0fb532009-11-11 19:31:23 +00003508 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00003509 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00003510 // therefore cannot be a non-type template argument.
3511 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3512 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003513
Douglas Gregorda0fb532009-11-11 19:31:23 +00003514 Diag(Param->getLocation(), diag::note_template_param_here);
3515 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003516
Douglas Gregorda0fb532009-11-11 19:31:23 +00003517 case TemplateArgument::Type: {
3518 // We have a non-type template parameter but the template
3519 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003520
Douglas Gregorda0fb532009-11-11 19:31:23 +00003521 // C++ [temp.arg]p2:
3522 // In a template-argument, an ambiguity between a type-id and
3523 // an expression is resolved to a type-id, regardless of the
3524 // form of the corresponding template-parameter.
3525 //
3526 // We warn specifically about this case, since it can be rather
3527 // confusing for users.
3528 QualType T = Arg.getArgument().getAsType();
3529 SourceRange SR = Arg.getSourceRange();
3530 if (T->isFunctionType())
3531 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3532 else
3533 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
3534 Diag(Param->getLocation(), diag::note_template_param_here);
3535 return true;
3536 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003537
Douglas Gregorda0fb532009-11-11 19:31:23 +00003538 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003539 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003540 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003541
Douglas Gregorda0fb532009-11-11 19:31:23 +00003542 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003543 }
3544
3545
Douglas Gregorda0fb532009-11-11 19:31:23 +00003546 // Check template template parameters.
3547 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003548
Douglas Gregorda0fb532009-11-11 19:31:23 +00003549 // Substitute into the template parameter list of the template
3550 // template parameter, since previously-supplied template arguments
3551 // may appear within the template template parameter.
3552 {
3553 // Set up a template instantiation context.
3554 LocalInstantiationScope Scope(*this);
3555 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003556 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003557 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003558 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003559 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003560
3561 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003562 Converted.data(), Converted.size());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003563 TempParm = cast_or_null<TemplateTemplateParmDecl>(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003564 SubstDecl(TempParm, CurContext,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003565 MultiLevelTemplateArgumentList(TemplateArgs)));
3566 if (!TempParm)
3567 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003568 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003569
Douglas Gregorda0fb532009-11-11 19:31:23 +00003570 switch (Arg.getArgument().getKind()) {
3571 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003572 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003573
Douglas Gregorda0fb532009-11-11 19:31:23 +00003574 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003575 case TemplateArgument::TemplateExpansion:
Richard Smith1fde8ec2012-09-07 02:06:42 +00003576 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003577 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003578
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003579 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003580 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003581
Douglas Gregorda0fb532009-11-11 19:31:23 +00003582 case TemplateArgument::Expression:
3583 case TemplateArgument::Type:
3584 // We have a template template parameter but the template
3585 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003586 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003587 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003588 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003589
Douglas Gregorda0fb532009-11-11 19:31:23 +00003590 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00003591 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003592 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00003593 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00003594 case TemplateArgument::NullPtr:
3595 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003596
Douglas Gregorda0fb532009-11-11 19:31:23 +00003597 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003598 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003599 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003600
Douglas Gregorda0fb532009-11-11 19:31:23 +00003601 return false;
3602}
3603
Douglas Gregor8e072612012-02-03 07:34:46 +00003604/// \brief Diagnose an arity mismatch in the
3605static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
3606 SourceLocation TemplateLoc,
3607 TemplateArgumentListInfo &TemplateArgs) {
3608 TemplateParameterList *Params = Template->getTemplateParameters();
3609 unsigned NumParams = Params->size();
3610 unsigned NumArgs = TemplateArgs.size();
3611
3612 SourceRange Range;
3613 if (NumArgs > NumParams)
3614 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
3615 TemplateArgs.getRAngleLoc());
3616 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3617 << (NumArgs > NumParams)
3618 << (isa<ClassTemplateDecl>(Template)? 0 :
3619 isa<FunctionTemplateDecl>(Template)? 1 :
3620 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3621 << Template << Range;
3622 S.Diag(Template->getLocation(), diag::note_template_decl_here)
3623 << Params->getSourceRange();
3624 return true;
3625}
3626
Richard Smith1fde8ec2012-09-07 02:06:42 +00003627/// \brief Check whether the template parameter is a pack expansion, and if so,
3628/// determine the number of parameters produced by that expansion. For instance:
3629///
3630/// \code
3631/// template<typename ...Ts> struct A {
3632/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3633/// };
3634/// \endcode
3635///
3636/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3637/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00003638static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003639 if (NonTypeTemplateParmDecl *NTTP
3640 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3641 if (NTTP->isExpandedParameterPack())
3642 return NTTP->getNumExpansionTypes();
3643 }
3644
3645 if (TemplateTemplateParmDecl *TTP
3646 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3647 if (TTP->isExpandedParameterPack())
3648 return TTP->getNumExpansionTemplateParameters();
3649 }
3650
David Blaikie7a30dc52013-02-21 01:47:18 +00003651 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00003652}
3653
Douglas Gregord32e0282009-02-09 23:23:08 +00003654/// \brief Check that the given template argument list is well-formed
3655/// for specializing the given template.
3656bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
3657 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003658 TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00003659 bool PartialTemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00003660 SmallVectorImpl<TemplateArgument> &Converted) {
Richard Trieu15b66532015-01-24 02:48:32 +00003661 // Make a copy of the template arguments for processing. Only make the
3662 // changes at the end when successful in matching the arguments to the
3663 // template.
3664 TemplateArgumentListInfo NewArgs = TemplateArgs;
3665
Douglas Gregord32e0282009-02-09 23:23:08 +00003666 TemplateParameterList *Params = Template->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00003667
Richard Trieu15b66532015-01-24 02:48:32 +00003668 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00003669
Mike Stump11289f42009-09-09 15:08:12 +00003670 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00003671 // [...] The type and form of each template-argument specified in
3672 // a template-id shall match the type and form specified for the
3673 // corresponding parameter declared by the template in its
3674 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00003675 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003676 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00003677 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00003678 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00003679 for (TemplateParameterList::iterator Param = Params->begin(),
3680 ParamEnd = Params->end();
3681 Param != ParamEnd; /* increment in loop */) {
3682 // If we have an expanded parameter pack, make sure we don't have too
3683 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00003684 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003685 if (*Expansions == ArgumentPack.size()) {
3686 // We're done with this parameter pack. Pack up its arguments and add
3687 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00003688 Converted.push_back(
3689 TemplateArgument::CreatePackCopy(Context,
3690 ArgumentPack.data(),
3691 ArgumentPack.size()));
3692 ArgumentPack.clear();
3693
Richard Smith1fde8ec2012-09-07 02:06:42 +00003694 // This argument is assigned to the next parameter.
3695 ++Param;
3696 continue;
3697 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
3698 // Not enough arguments for this parameter pack.
3699 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3700 << false
3701 << (isa<ClassTemplateDecl>(Template)? 0 :
3702 isa<FunctionTemplateDecl>(Template)? 1 :
3703 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3704 << Template;
3705 Diag(Template->getLocation(), diag::note_template_decl_here)
3706 << Params->getSourceRange();
3707 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003708 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003709 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003710
Richard Smith1fde8ec2012-09-07 02:06:42 +00003711 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00003712 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00003713 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003714 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003715 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00003716 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003717
Richard Smith96d71c32014-11-12 23:38:38 +00003718 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00003719 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00003720 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
3721 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00003722 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00003723 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00003724 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00003725 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00003726 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00003727 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00003728 Diag((*Param)->getLocation(), diag::note_template_param_here);
3729 return true;
3730 }
3731
Richard Smith1fde8ec2012-09-07 02:06:42 +00003732 // We're now done with this argument.
3733 ++ArgIdx;
3734
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003735 if ((*Param)->isTemplateParameterPack()) {
3736 // The template parameter was a template parameter pack, so take the
3737 // deduced argument and place it on the argument pack. Note that we
3738 // stay on the same template parameter so that we can deduce more
3739 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003740 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003741 } else {
3742 // Move to the next template parameter.
3743 ++Param;
3744 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003745
Richard Smith96d71c32014-11-12 23:38:38 +00003746 // If we just saw a pack expansion into a non-pack, then directly convert
3747 // the remaining arguments, because we don't know what parameters they'll
3748 // match up with.
3749 if (PackExpansionIntoNonPack) {
3750 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003751 // If we were part way through filling in an expanded parameter pack,
3752 // fall back to just producing individual arguments.
3753 Converted.insert(Converted.end(),
3754 ArgumentPack.begin(), ArgumentPack.end());
3755 ArgumentPack.clear();
3756 }
3757
3758 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00003759 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00003760 ++ArgIdx;
3761 }
3762
Richard Smith1fde8ec2012-09-07 02:06:42 +00003763 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00003764 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003765
Douglas Gregor84d49a22009-11-11 21:54:23 +00003766 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003767 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003768
Douglas Gregor2f157c92011-06-03 02:59:40 +00003769 // If we're checking a partial template argument list, we're done.
3770 if (PartialTemplateArgs) {
3771 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
3772 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3773 ArgumentPack.data(),
3774 ArgumentPack.size()));
3775
Richard Smith1fde8ec2012-09-07 02:06:42 +00003776 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00003777 }
3778
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003779 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003780 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00003781 if ((*Param)->isTemplateParameterPack()) {
3782 assert(!getExpandedPackSize(*Param) &&
3783 "Should have dealt with this already");
3784
3785 // A non-expanded parameter pack before the end of the parameter list
3786 // only occurs for an ill-formed template parameter list, unless we've
3787 // got a partial argument list for a function template, so just bail out.
3788 if (Param + 1 != ParamEnd)
3789 return true;
3790
Eli Friedmanb826a002012-09-26 02:36:12 +00003791 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3792 ArgumentPack.data(),
3793 ArgumentPack.size()));
3794 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00003795
3796 ++Param;
3797 continue;
3798 }
3799
Douglas Gregor8e072612012-02-03 07:34:46 +00003800 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00003801 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003802
Douglas Gregor84d49a22009-11-11 21:54:23 +00003803 // Retrieve the default template argument from the template
3804 // parameter. For each kind of template parameter, we substitute the
3805 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003806 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00003807 // the default argument.
3808 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Douglas Gregor8e072612012-02-03 07:34:46 +00003809 if (!TTP->hasDefaultArgument())
Richard Trieu15b66532015-01-24 02:48:32 +00003810 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003811
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003812 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003813 Template,
3814 TemplateLoc,
3815 RAngleLoc,
3816 TTP,
3817 Converted);
3818 if (!ArgType)
3819 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003820
Douglas Gregor84d49a22009-11-11 21:54:23 +00003821 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
3822 ArgType);
3823 } else if (NonTypeTemplateParmDecl *NTTP
3824 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Douglas Gregor8e072612012-02-03 07:34:46 +00003825 if (!NTTP->hasDefaultArgument())
Richard Trieu15b66532015-01-24 02:48:32 +00003826 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003827
John McCalldadc5752010-08-24 06:29:42 +00003828 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003829 TemplateLoc,
3830 RAngleLoc,
3831 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003832 Converted);
3833 if (E.isInvalid())
3834 return true;
3835
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003836 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00003837 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
3838 } else {
3839 TemplateTemplateParmDecl *TempParm
3840 = cast<TemplateTemplateParmDecl>(*Param);
3841
Douglas Gregor8e072612012-02-03 07:34:46 +00003842 if (!TempParm->hasDefaultArgument())
Richard Trieu15b66532015-01-24 02:48:32 +00003843 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003844
Douglas Gregordf846d12011-03-02 18:46:51 +00003845 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00003846 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003847 TemplateLoc,
3848 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003849 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003850 Converted,
3851 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003852 if (Name.isNull())
3853 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003854
Douglas Gregor9d802122011-03-02 17:09:35 +00003855 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
3856 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00003857 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003858
Douglas Gregor84d49a22009-11-11 21:54:23 +00003859 // Introduce an instantiation record that describes where we are using
3860 // the default template argument.
Alp Tokerd4a72d52013-10-08 08:09:04 +00003861 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
3862 SourceRange(TemplateLoc, RAngleLoc));
3863 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003864 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003865
Douglas Gregor84d49a22009-11-11 21:54:23 +00003866 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00003867 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003868 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003869 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003870
Richard Trieu15b66532015-01-24 02:48:32 +00003871 // Core issue 150 (assumed resolution): if this is a template template
3872 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00003873 // template definition.
3874 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00003875 NewArgs.addArgument(Arg);
3876
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003877 // Move to the next template parameter and argument.
3878 ++Param;
3879 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00003880 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003881
Richard Smith07f79912014-06-06 16:00:50 +00003882 // If we're performing a partial argument substitution, allow any trailing
3883 // pack expansions; they might be empty. This can happen even if
3884 // PartialTemplateArgs is false (the list of arguments is complete but
3885 // still dependent).
3886 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
3887 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00003888 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
3889 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00003890 }
3891
Douglas Gregor8e072612012-02-03 07:34:46 +00003892 // If we have any leftover arguments, then there were too many arguments.
3893 // Complain and fail.
3894 if (ArgIdx < NumArgs)
Richard Trieu15b66532015-01-24 02:48:32 +00003895 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
3896
3897 // No problems found with the new argument list, propagate changes back
3898 // to caller.
3899 TemplateArgs = NewArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003900
Richard Smith1fde8ec2012-09-07 02:06:42 +00003901 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00003902}
3903
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003904namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003905 class UnnamedLocalNoLinkageFinder
3906 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003907 {
3908 Sema &S;
3909 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003910
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003911 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003912
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003913 public:
3914 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
3915
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003916 bool Visit(QualType T) {
3917 return inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003918 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003919
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003920#define TYPE(Class, Parent) \
3921 bool Visit##Class##Type(const Class##Type *);
3922#define ABSTRACT_TYPE(Class, Parent) \
3923 bool Visit##Class##Type(const Class##Type *) { return false; }
3924#define NON_CANONICAL_TYPE(Class, Parent) \
3925 bool Visit##Class##Type(const Class##Type *) { return false; }
3926#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003927
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003928 bool VisitTagDecl(const TagDecl *Tag);
3929 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
3930 };
3931}
3932
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003933bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003934 return false;
3935}
3936
3937bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
3938 return Visit(T->getElementType());
3939}
3940
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003941bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003942 return Visit(T->getPointeeType());
3943}
3944
3945bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003946 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003947 return Visit(T->getPointeeType());
3948}
3949
3950bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003951 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003952 return Visit(T->getPointeeType());
3953}
3954
3955bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003956 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003957 return Visit(T->getPointeeType());
3958}
3959
3960bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003961 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003962 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
3963}
3964
3965bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003966 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003967 return Visit(T->getElementType());
3968}
3969
3970bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003971 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003972 return Visit(T->getElementType());
3973}
3974
3975bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003976 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003977 return Visit(T->getElementType());
3978}
3979
3980bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003981 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003982 return Visit(T->getElementType());
3983}
3984
3985bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003986 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003987 return Visit(T->getElementType());
3988}
3989
3990bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
3991 return Visit(T->getElementType());
3992}
3993
3994bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
3995 return Visit(T->getElementType());
3996}
3997
3998bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
3999 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004000 for (const auto &A : T->param_types()) {
4001 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004002 return true;
4003 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004004
Alp Toker314cc812014-01-25 16:55:45 +00004005 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004006}
4007
4008bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
4009 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00004010 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004011}
4012
4013bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
4014 const UnresolvedUsingType*) {
4015 return false;
4016}
4017
4018bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
4019 return false;
4020}
4021
4022bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4023 return Visit(T->getUnderlyingType());
4024}
4025
4026bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4027 return false;
4028}
4029
Alexis Hunte852b102011-05-24 22:41:36 +00004030bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4031 const UnaryTransformType*) {
4032 return false;
4033}
4034
Richard Smith30482bc2011-02-20 03:19:35 +00004035bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4036 return Visit(T->getDeducedType());
4037}
4038
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004039bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4040 return VisitTagDecl(T->getDecl());
4041}
4042
4043bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4044 return VisitTagDecl(T->getDecl());
4045}
4046
4047bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4048 const TemplateTypeParmType*) {
4049 return false;
4050}
4051
Douglas Gregorada4b792011-01-14 02:55:32 +00004052bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4053 const SubstTemplateTypeParmPackType *) {
4054 return false;
4055}
4056
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004057bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4058 const TemplateSpecializationType*) {
4059 return false;
4060}
4061
4062bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4063 const InjectedClassNameType* T) {
4064 return VisitTagDecl(T->getDecl());
4065}
4066
4067bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4068 const DependentNameType* T) {
4069 return VisitNestedNameSpecifier(T->getQualifier());
4070}
4071
4072bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4073 const DependentTemplateSpecializationType* T) {
4074 return VisitNestedNameSpecifier(T->getQualifier());
4075}
4076
Douglas Gregord2fa7662010-12-20 02:24:11 +00004077bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4078 const PackExpansionType* T) {
4079 return Visit(T->getPattern());
4080}
4081
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004082bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4083 return false;
4084}
4085
4086bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4087 const ObjCInterfaceType *) {
4088 return false;
4089}
4090
4091bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4092 const ObjCObjectPointerType *) {
4093 return false;
4094}
4095
Eli Friedman0dfb8892011-10-06 23:00:33 +00004096bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4097 return Visit(T->getValueType());
4098}
4099
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004100bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4101 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004102 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004103 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004104 diag::warn_cxx98_compat_template_arg_local_type :
4105 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004106 << S.Context.getTypeDeclType(Tag) << SR;
4107 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004108 }
4109
John McCall5ea95772013-03-09 00:54:27 +00004110 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004111 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004112 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004113 diag::warn_cxx98_compat_template_arg_unnamed_type :
4114 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004115 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4116 return true;
4117 }
4118
4119 return false;
4120}
4121
4122bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4123 NestedNameSpecifier *NNS) {
4124 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4125 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004126
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004127 switch (NNS->getKind()) {
4128 case NestedNameSpecifier::Identifier:
4129 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004130 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004131 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004132 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004133 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004134
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004135 case NestedNameSpecifier::TypeSpec:
4136 case NestedNameSpecifier::TypeSpecWithTemplate:
4137 return Visit(QualType(NNS->getAsType(), 0));
4138 }
David Blaikie8a40f702012-01-17 06:56:22 +00004139 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004140}
4141
4142
Douglas Gregord32e0282009-02-09 23:23:08 +00004143/// \brief Check a template argument against its corresponding
4144/// template type parameter.
4145///
4146/// This routine implements the semantics of C++ [temp.arg.type]. It
4147/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00004148bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00004149 TypeSourceInfo *ArgInfo) {
4150 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00004151 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00004152 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00004153
4154 if (Arg->isVariablyModifiedType()) {
4155 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004156 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004157 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00004158 }
4159
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004160 // C++03 [temp.arg.type]p2:
4161 // A local type, a type with no linkage, an unnamed type or a type
4162 // compounded from any of these types shall not be used as a
4163 // template-argument for a template type-parameter.
4164 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00004165 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004166 // a warning.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004167 bool NeedsCheck;
4168 if (LangOpts.CPlusPlus11)
4169 NeedsCheck =
4170 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_unnamed_type,
4171 SR.getBegin()) ||
4172 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_local_type,
4173 SR.getBegin());
4174 else
4175 NeedsCheck = Arg->hasUnnamedOrLocalType();
4176
4177 if (NeedsCheck) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004178 UnnamedLocalNoLinkageFinder Finder(*this, SR);
4179 (void)Finder.Visit(Context.getCanonicalType(Arg));
4180 }
4181
Douglas Gregord32e0282009-02-09 23:23:08 +00004182 return false;
4183}
4184
Douglas Gregor20fdef32012-04-10 17:08:25 +00004185enum NullPointerValueKind {
4186 NPV_NotNullPointer,
4187 NPV_NullPointer,
4188 NPV_Error
4189};
4190
4191/// \brief Determine whether the given template argument is a null pointer
4192/// value of the appropriate type.
4193static NullPointerValueKind
4194isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
4195 QualType ParamType, Expr *Arg) {
4196 if (Arg->isValueDependent() || Arg->isTypeDependent())
4197 return NPV_NotNullPointer;
4198
David Majnemer5c734ad2014-08-14 00:49:23 +00004199 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004200 return NPV_NotNullPointer;
4201
4202 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00004203 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
4204 if (ArgRV.isInvalid())
4205 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004206 Arg = ArgRV.get();
Douglas Gregor350880c2012-04-10 19:03:30 +00004207
Douglas Gregor20fdef32012-04-10 17:08:25 +00004208 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004209 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00004210 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00004211 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00004212 EvalResult.HasSideEffects) {
4213 SourceLocation DiagLoc = Arg->getExprLoc();
4214
4215 // If our only note is the usual "invalid subexpression" note, just point
4216 // the caret at its location rather than producing an essentially
4217 // redundant note.
4218 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4219 diag::note_invalid_subexpr_in_const_expr) {
4220 DiagLoc = Notes[0].first;
4221 Notes.clear();
4222 }
4223
4224 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4225 << Arg->getType() << Arg->getSourceRange();
4226 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4227 S.Diag(Notes[I].first, Notes[I].second);
4228
4229 S.Diag(Param->getLocation(), diag::note_template_param_here);
4230 return NPV_Error;
4231 }
Douglas Gregor20fdef32012-04-10 17:08:25 +00004232
4233 // C++11 [temp.arg.nontype]p1:
4234 // - an address constant expression of type std::nullptr_t
4235 if (Arg->getType()->isNullPtrType())
4236 return NPV_NullPointer;
4237
4238 // - a constant expression that evaluates to a null pointer value (4.10); or
4239 // - a constant expression that evaluates to a null member pointer value
4240 // (4.11); or
4241 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4242 (EvalResult.Val.isMemberPointer() &&
4243 !EvalResult.Val.getMemberPointerDecl())) {
4244 // If our expression has an appropriate type, we've succeeded.
4245 bool ObjCLifetimeConversion;
4246 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4247 S.IsQualificationConversion(Arg->getType(), ParamType, false,
4248 ObjCLifetimeConversion))
4249 return NPV_NullPointer;
4250
4251 // The types didn't match, but we know we got a null pointer; complain,
4252 // then recover as if the types were correct.
4253 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4254 << Arg->getType() << ParamType << Arg->getSourceRange();
4255 S.Diag(Param->getLocation(), diag::note_template_param_here);
4256 return NPV_NullPointer;
4257 }
4258
4259 // If we don't have a null pointer value, but we do have a NULL pointer
4260 // constant, suggest a cast to the appropriate type.
4261 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
4262 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4263 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004264 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4265 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
4266 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00004267 S.Diag(Param->getLocation(), diag::note_template_param_here);
4268 return NPV_NullPointer;
4269 }
4270
4271 // FIXME: If we ever want to support general, address-constant expressions
4272 // as non-type template arguments, we should return the ExprResult here to
4273 // be interpreted by the caller.
4274 return NPV_NotNullPointer;
4275}
4276
David Majnemer61c39a12013-08-23 05:39:39 +00004277/// \brief Checks whether the given template argument is compatible with its
4278/// template parameter.
4279static bool CheckTemplateArgumentIsCompatibleWithParameter(
4280 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4281 Expr *Arg, QualType ArgType) {
4282 bool ObjCLifetimeConversion;
4283 if (ParamType->isPointerType() &&
4284 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4285 S.IsQualificationConversion(ArgType, ParamType, false,
4286 ObjCLifetimeConversion)) {
4287 // For pointer-to-object types, qualification conversions are
4288 // permitted.
4289 } else {
4290 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4291 if (!ParamRef->getPointeeType()->isFunctionType()) {
4292 // C++ [temp.arg.nontype]p5b3:
4293 // For a non-type template-parameter of type reference to
4294 // object, no conversions apply. The type referred to by the
4295 // reference may be more cv-qualified than the (otherwise
4296 // identical) type of the template- argument. The
4297 // template-parameter is bound directly to the
4298 // template-argument, which shall be an lvalue.
4299
4300 // FIXME: Other qualifiers?
4301 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4302 unsigned ArgQuals = ArgType.getCVRQualifiers();
4303
4304 if ((ParamQuals | ArgQuals) != ParamQuals) {
4305 S.Diag(Arg->getLocStart(),
4306 diag::err_template_arg_ref_bind_ignores_quals)
4307 << ParamType << Arg->getType() << Arg->getSourceRange();
4308 S.Diag(Param->getLocation(), diag::note_template_param_here);
4309 return true;
4310 }
4311 }
4312 }
4313
4314 // At this point, the template argument refers to an object or
4315 // function with external linkage. We now need to check whether the
4316 // argument and parameter types are compatible.
4317 if (!S.Context.hasSameUnqualifiedType(ArgType,
4318 ParamType.getNonReferenceType())) {
4319 // We can't perform this conversion or binding.
4320 if (ParamType->isReferenceType())
4321 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4322 << ParamType << ArgIn->getType() << Arg->getSourceRange();
4323 else
4324 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4325 << ArgIn->getType() << ParamType << Arg->getSourceRange();
4326 S.Diag(Param->getLocation(), diag::note_template_param_here);
4327 return true;
4328 }
4329 }
4330
4331 return false;
4332}
4333
Douglas Gregorccb07762009-02-11 19:52:55 +00004334/// \brief Checks whether the given template argument is the address
4335/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004336static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00004337CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
4338 NonTypeTemplateParmDecl *Param,
4339 QualType ParamType,
4340 Expr *ArgIn,
4341 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004342 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004343 Expr *Arg = ArgIn;
4344 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00004345
Douglas Gregorb242683d2010-04-01 18:32:35 +00004346 bool AddressTaken = false;
4347 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00004348 if (S.getLangOpts().MicrosoftExt) {
4349 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4350 // dereference and address-of operators.
4351 Arg = Arg->IgnoreParenCasts();
4352
4353 bool ExtWarnMSTemplateArg = false;
4354 UnaryOperatorKind FirstOpKind;
4355 SourceLocation FirstOpLoc;
4356 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4357 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4358 if (UnOpKind == UO_Deref)
4359 ExtWarnMSTemplateArg = true;
4360 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4361 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4362 if (!AddrOpLoc.isValid()) {
4363 FirstOpKind = UnOpKind;
4364 FirstOpLoc = UnOp->getOperatorLoc();
4365 }
4366 } else
4367 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004368 }
David Majnemer61c39a12013-08-23 05:39:39 +00004369 if (FirstOpLoc.isValid()) {
4370 if (ExtWarnMSTemplateArg)
4371 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4372 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00004373
David Majnemer61c39a12013-08-23 05:39:39 +00004374 if (FirstOpKind == UO_AddrOf)
4375 AddressTaken = true;
4376 else if (Arg->getType()->isPointerType()) {
4377 // We cannot let pointers get dereferenced here, that is obviously not a
4378 // constant expression.
4379 assert(FirstOpKind == UO_Deref);
4380 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4381 << Arg->getSourceRange();
4382 }
4383 }
4384 } else {
4385 // See through any implicit casts we added to fix the type.
4386 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00004387
David Majnemer61c39a12013-08-23 05:39:39 +00004388 // C++ [temp.arg.nontype]p1:
4389 //
4390 // A template-argument for a non-type, non-template
4391 // template-parameter shall be one of: [...]
4392 //
4393 // -- the address of an object or function with external
4394 // linkage, including function templates and function
4395 // template-ids but excluding non-static class members,
4396 // expressed as & id-expression where the & is optional if
4397 // the name refers to a function or array, or if the
4398 // corresponding template-parameter is a reference; or
4399
4400 // In C++98/03 mode, give an extension warning on any extra parentheses.
4401 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4402 bool ExtraParens = false;
4403 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4404 if (!Invalid && !ExtraParens) {
4405 S.Diag(Arg->getLocStart(),
4406 S.getLangOpts().CPlusPlus11
4407 ? diag::warn_cxx98_compat_template_arg_extra_parens
4408 : diag::ext_template_arg_extra_parens)
4409 << Arg->getSourceRange();
4410 ExtraParens = true;
4411 }
4412
4413 Arg = Parens->getSubExpr();
4414 }
4415
4416 while (SubstNonTypeTemplateParmExpr *subst =
4417 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4418 Arg = subst->getReplacement()->IgnoreImpCasts();
4419
4420 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4421 if (UnOp->getOpcode() == UO_AddrOf) {
4422 Arg = UnOp->getSubExpr();
4423 AddressTaken = true;
4424 AddrOpLoc = UnOp->getOperatorLoc();
4425 }
4426 }
4427
4428 while (SubstNonTypeTemplateParmExpr *subst =
4429 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4430 Arg = subst->getReplacement()->IgnoreImpCasts();
4431 }
John McCall7c454bb2011-07-15 05:09:51 +00004432
David Majnemer07910d62014-06-26 07:48:46 +00004433 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4434 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
4435
4436 // If our parameter has pointer type, check for a null template value.
4437 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4438 NullPointerValueKind NPV;
4439 // dllimport'd entities aren't constant but are available inside of template
4440 // arguments.
4441 if (Entity && Entity->hasAttr<DLLImportAttr>())
4442 NPV = NPV_NotNullPointer;
4443 else
4444 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
4445 switch (NPV) {
4446 case NPV_NullPointer:
4447 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004448 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4449 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00004450 return false;
4451
4452 case NPV_Error:
4453 return true;
4454
4455 case NPV_NotNullPointer:
4456 break;
4457 }
4458 }
4459
Chandler Carruth724a8a12010-01-31 10:01:20 +00004460 // Stop checking the precise nature of the argument if it is value dependent,
4461 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00004462 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004463 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00004464 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004465 }
David Majnemer61c39a12013-08-23 05:39:39 +00004466
4467 if (isa<CXXUuidofExpr>(Arg)) {
4468 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4469 ArgIn, Arg, ArgType))
4470 return true;
4471
4472 Converted = TemplateArgument(ArgIn);
4473 return false;
4474 }
4475
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004476 if (!DRE) {
4477 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4478 << Arg->getSourceRange();
4479 S.Diag(Param->getLocation(), diag::note_template_param_here);
4480 return true;
4481 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00004482
Douglas Gregorccb07762009-02-11 19:52:55 +00004483 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00004484 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004485 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
David Majnemer6bedcfa2013-10-26 06:12:44 +00004486 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004487 S.Diag(Param->getLocation(), diag::note_template_param_here);
4488 return true;
4489 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004490
4491 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00004492 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004493 if (!Method->isStatic()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004494 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00004495 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004496 S.Diag(Param->getLocation(), diag::note_template_param_here);
4497 return true;
4498 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004499 }
Mike Stump11289f42009-09-09 15:08:12 +00004500
Richard Smith9380e0e2012-04-04 21:11:30 +00004501 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
4502 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00004503
Richard Smith9380e0e2012-04-04 21:11:30 +00004504 // A non-type template argument must refer to an object or function.
4505 if (!Func && !Var) {
4506 // We found something, but we don't know specifically what it is.
4507 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
4508 << Arg->getSourceRange();
4509 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4510 return true;
4511 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004512
Richard Smith9380e0e2012-04-04 21:11:30 +00004513 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00004514 if (Entity->getFormalLinkage() == InternalLinkage) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004515 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
Richard Smith9380e0e2012-04-04 21:11:30 +00004516 diag::warn_cxx98_compat_template_arg_object_internal :
4517 diag::ext_template_arg_object_internal)
4518 << !Func << Entity << Arg->getSourceRange();
4519 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4520 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00004521 } else if (!Entity->hasLinkage()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004522 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
4523 << !Func << Entity << Arg->getSourceRange();
4524 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4525 << !Func;
4526 return true;
4527 }
4528
4529 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004530 // If the template parameter has pointer type, the function decays.
4531 if (ParamType->isPointerType() && !AddressTaken)
4532 ArgType = S.Context.getPointerType(Func->getType());
4533 else if (AddressTaken && ParamType->isReferenceType()) {
4534 // If we originally had an address-of operator, but the
4535 // parameter has reference type, complain and (if things look
4536 // like they will work) drop the address-of operator.
4537 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
4538 ParamType.getNonReferenceType())) {
4539 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4540 << ParamType;
4541 S.Diag(Param->getLocation(), diag::note_template_param_here);
4542 return true;
4543 }
4544
4545 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4546 << ParamType
4547 << FixItHint::CreateRemoval(AddrOpLoc);
4548 S.Diag(Param->getLocation(), diag::note_template_param_here);
4549
4550 ArgType = Func->getType();
4551 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004552 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004553 // A value of reference type is not an object.
4554 if (Var->getType()->isReferenceType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004555 S.Diag(Arg->getLocStart(),
Douglas Gregorb242683d2010-04-01 18:32:35 +00004556 diag::err_template_arg_reference_var)
4557 << Var->getType() << Arg->getSourceRange();
4558 S.Diag(Param->getLocation(), diag::note_template_param_here);
4559 return true;
4560 }
4561
Richard Smith9380e0e2012-04-04 21:11:30 +00004562 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00004563 if (Var->getTLSKind()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004564 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
4565 << Arg->getSourceRange();
4566 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
4567 return true;
4568 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00004569
4570 // If the template parameter has pointer type, we must have taken
4571 // the address of this object.
4572 if (ParamType->isReferenceType()) {
4573 if (AddressTaken) {
4574 // If we originally had an address-of operator, but the
4575 // parameter has reference type, complain and (if things look
4576 // like they will work) drop the address-of operator.
4577 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
4578 ParamType.getNonReferenceType())) {
4579 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4580 << ParamType;
4581 S.Diag(Param->getLocation(), diag::note_template_param_here);
4582 return true;
4583 }
4584
4585 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4586 << ParamType
4587 << FixItHint::CreateRemoval(AddrOpLoc);
4588 S.Diag(Param->getLocation(), diag::note_template_param_here);
4589
4590 ArgType = Var->getType();
4591 }
4592 } else if (!AddressTaken && ParamType->isPointerType()) {
4593 if (Var->getType()->isArrayType()) {
4594 // Array-to-pointer decay.
4595 ArgType = S.Context.getArrayDecayedType(Var->getType());
4596 } else {
4597 // If the template parameter has pointer type but the address of
4598 // this object was not taken, complain and (possibly) recover by
4599 // taking the address of the entity.
4600 ArgType = S.Context.getPointerType(Var->getType());
4601 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
4602 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4603 << ParamType;
4604 S.Diag(Param->getLocation(), diag::note_template_param_here);
4605 return true;
4606 }
4607
4608 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4609 << ParamType
4610 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
4611
4612 S.Diag(Param->getLocation(), diag::note_template_param_here);
4613 }
4614 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004615 }
Mike Stump11289f42009-09-09 15:08:12 +00004616
David Majnemer61c39a12013-08-23 05:39:39 +00004617 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
4618 Arg, ArgType))
4619 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004620
4621 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00004622 Converted =
4623 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Nick Lewycky45b50522013-02-02 00:25:55 +00004624 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00004625 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004626}
4627
4628/// \brief Checks whether the given template argument is a pointer to
4629/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004630static bool CheckTemplateArgumentPointerToMember(Sema &S,
4631 NonTypeTemplateParmDecl *Param,
4632 QualType ParamType,
4633 Expr *&ResultArg,
4634 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004635 bool Invalid = false;
4636
Douglas Gregor20fdef32012-04-10 17:08:25 +00004637 // Check for a null pointer value.
4638 Expr *Arg = ResultArg;
4639 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4640 case NPV_Error:
4641 return true;
4642 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00004643 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004644 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4645 /*isNullPtr*/true);
David Majnemer763584d2014-02-06 10:59:19 +00004646 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft())
4647 S.RequireCompleteType(Arg->getExprLoc(), ParamType, 0);
Douglas Gregor20fdef32012-04-10 17:08:25 +00004648 return false;
4649 case NPV_NotNullPointer:
4650 break;
4651 }
4652
4653 bool ObjCLifetimeConversion;
4654 if (S.IsQualificationConversion(Arg->getType(),
4655 ParamType.getNonReferenceType(),
4656 false, ObjCLifetimeConversion)) {
4657 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004658 Arg->getValueKind()).get();
Douglas Gregor20fdef32012-04-10 17:08:25 +00004659 ResultArg = Arg;
4660 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
4661 ParamType.getNonReferenceType())) {
4662 // We can't perform this conversion.
4663 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4664 << Arg->getType() << ParamType << Arg->getSourceRange();
4665 S.Diag(Param->getLocation(), diag::note_template_param_here);
4666 return true;
4667 }
4668
Douglas Gregorccb07762009-02-11 19:52:55 +00004669 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00004670 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00004671 Arg = Cast->getSubExpr();
4672
4673 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004674 //
Douglas Gregorccb07762009-02-11 19:52:55 +00004675 // A template-argument for a non-type, non-template
4676 // template-parameter shall be one of: [...]
4677 //
4678 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00004679 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00004680
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004681 // In C++98/03 mode, give an extension warning on any extra parentheses.
4682 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4683 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004684 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004685 if (!Invalid && !ExtraParens) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00004686 S.Diag(Arg->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004687 S.getLangOpts().CPlusPlus11 ?
Douglas Gregor20fdef32012-04-10 17:08:25 +00004688 diag::warn_cxx98_compat_template_arg_extra_parens :
4689 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00004690 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004691 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00004692 }
4693
4694 Arg = Parens->getSubExpr();
4695 }
4696
John McCall7c454bb2011-07-15 05:09:51 +00004697 while (SubstNonTypeTemplateParmExpr *subst =
4698 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4699 Arg = subst->getReplacement()->IgnoreImpCasts();
4700
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004701 // A pointer-to-member constant written &Class::member.
4702 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00004703 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004704 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
4705 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00004706 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004707 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004708 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004709 // A constant of pointer-to-member type.
4710 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
4711 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
4712 if (VD->getType()->isMemberPointerType()) {
David Majnemercd053cd2013-12-10 00:40:58 +00004713 if (isa<NonTypeTemplateParmDecl>(VD)) {
Eli Friedmanb826a002012-09-26 02:36:12 +00004714 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004715 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004716 } else {
4717 VD = cast<ValueDecl>(VD->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00004718 Converted = TemplateArgument(VD, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00004719 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004720 return Invalid;
4721 }
4722 }
4723 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004724
Craig Topperc3ec1492014-05-26 06:22:03 +00004725 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004726 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004727
Douglas Gregorccb07762009-02-11 19:52:55 +00004728 if (!DRE)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004729 return S.Diag(Arg->getLocStart(),
4730 diag::err_template_arg_not_pointer_to_member_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00004731 << Arg->getSourceRange();
4732
David Majnemer3ac84e62013-10-22 21:56:38 +00004733 if (isa<FieldDecl>(DRE->getDecl()) ||
4734 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4735 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004736 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00004737 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00004738 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
4739 "Only non-static member pointers can make it here");
4740
4741 // Okay: this is the address of a non-static member, and therefore
4742 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00004743 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004744 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004745 } else {
4746 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00004747 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00004748 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004749 return Invalid;
4750 }
4751
4752 // We found something else, but we don't know specifically what it is.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004753 S.Diag(Arg->getLocStart(),
4754 diag::err_template_arg_not_pointer_to_member_form)
4755 << Arg->getSourceRange();
4756 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00004757 return true;
4758}
4759
Douglas Gregord32e0282009-02-09 23:23:08 +00004760/// \brief Check a template argument against its corresponding
4761/// non-type template parameter.
4762///
Douglas Gregor463421d2009-03-03 04:44:36 +00004763/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00004764/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00004765/// returns the converted template argument. \p ParamType is the
4766/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00004767ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00004768 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00004769 TemplateArgument &Converted,
4770 CheckTemplateArgumentKind CTAK) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004771 SourceLocation StartLoc = Arg->getLocStart();
Douglas Gregorc40290e2009-03-09 23:48:35 +00004772
Douglas Gregor86560402009-02-10 23:36:10 +00004773 // If either the parameter has a dependent type or the argument is
4774 // type-dependent, there's nothing we can check now.
Richard Smithd663fdd2014-12-17 20:42:37 +00004775 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00004776 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00004777 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004778 return Arg;
Douglas Gregorc40290e2009-03-09 23:48:35 +00004779 }
Douglas Gregor86560402009-02-10 23:36:10 +00004780
Richard Smithd663fdd2014-12-17 20:42:37 +00004781 // We should have already dropped all cv-qualifiers by now.
4782 assert(!ParamType.hasQualifiers() &&
4783 "non-type template parameter type cannot be qualified");
4784
4785 if (CTAK == CTAK_Deduced &&
4786 !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
4787 // C++ [temp.deduct.type]p17:
4788 // If, in the declaration of a function template with a non-type
4789 // template-parameter, the non-type template-parameter is used
4790 // in an expression in the function parameter-list and, if the
4791 // corresponding template-argument is deduced, the
4792 // template-argument type shall match the type of the
4793 // template-parameter exactly, except that a template-argument
4794 // deduced from an array bound may be of any integral type.
4795 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
4796 << Arg->getType().getUnqualifiedType()
4797 << ParamType.getUnqualifiedType();
4798 Diag(Param->getLocation(), diag::note_template_param_here);
4799 return ExprError();
4800 }
4801
Richard Smith410cc892014-11-26 03:26:53 +00004802 if (getLangOpts().CPlusPlus1z) {
4803 // FIXME: We can do some limited checking for a value-dependent but not
4804 // type-dependent argument.
4805 if (Arg->isValueDependent()) {
4806 Converted = TemplateArgument(Arg);
4807 return Arg;
4808 }
4809
4810 // C++1z [temp.arg.nontype]p1:
4811 // A template-argument for a non-type template parameter shall be
4812 // a converted constant expression of the type of the template-parameter.
4813 APValue Value;
4814 ExprResult ArgResult = CheckConvertedConstantExpression(
4815 Arg, ParamType, Value, CCEK_TemplateArg);
4816 if (ArgResult.isInvalid())
4817 return ExprError();
4818
Richard Smithd663fdd2014-12-17 20:42:37 +00004819 QualType CanonParamType = Context.getCanonicalType(ParamType);
4820
Richard Smith410cc892014-11-26 03:26:53 +00004821 // Convert the APValue to a TemplateArgument.
4822 switch (Value.getKind()) {
4823 case APValue::Uninitialized:
4824 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00004825 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00004826 break;
4827 case APValue::Int:
4828 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00004829 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00004830 break;
4831 case APValue::MemberPointer: {
4832 assert(ParamType->isMemberPointerType());
4833
4834 // FIXME: We need TemplateArgument representation and mangling for these.
4835 if (!Value.getMemberPointerPath().empty()) {
4836 Diag(Arg->getLocStart(),
4837 diag::err_template_arg_member_ptr_base_derived_not_supported)
4838 << Value.getMemberPointerDecl() << ParamType
4839 << Arg->getSourceRange();
4840 return ExprError();
4841 }
4842
4843 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00004844 Converted = VD ? TemplateArgument(VD, CanonParamType)
4845 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00004846 break;
4847 }
4848 case APValue::LValue: {
4849 // For a non-type template-parameter of pointer or reference type,
4850 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00004851 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
4852 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00004853 // -- a temporary object
4854 // -- a string literal
4855 // -- the result of a typeid expression, or
4856 // -- a predefind __func__ variable
4857 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
4858 if (isa<CXXUuidofExpr>(E)) {
4859 Converted = TemplateArgument(const_cast<Expr*>(E));
4860 break;
4861 }
4862 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4863 << Arg->getSourceRange();
4864 return ExprError();
4865 }
4866 auto *VD = const_cast<ValueDecl *>(
4867 Value.getLValueBase().dyn_cast<const ValueDecl *>());
4868 // -- a subobject
4869 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
4870 VD && VD->getType()->isArrayType() &&
4871 Value.getLValuePath()[0].ArrayIndex == 0 &&
4872 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
4873 // Per defect report (no number yet):
4874 // ... other than a pointer to the first element of a complete array
4875 // object.
4876 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
4877 Value.isLValueOnePastTheEnd()) {
4878 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
4879 << Value.getAsString(Context, ParamType);
4880 return ExprError();
4881 }
Richard Smithd663fdd2014-12-17 20:42:37 +00004882 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00004883 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00004884 assert((!VD || !ParamType->isNullPtrType()) &&
4885 "non-null value of type nullptr_t?");
4886 Converted = VD ? TemplateArgument(VD, CanonParamType)
4887 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00004888 break;
4889 }
4890 case APValue::AddrLabelDiff:
4891 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
4892 case APValue::Float:
4893 case APValue::ComplexInt:
4894 case APValue::ComplexFloat:
4895 case APValue::Vector:
4896 case APValue::Array:
4897 case APValue::Struct:
4898 case APValue::Union:
4899 llvm_unreachable("invalid kind for template argument");
4900 }
4901
4902 return ArgResult.get();
4903 }
4904
Douglas Gregor86560402009-02-10 23:36:10 +00004905 // C++ [temp.arg.nontype]p5:
4906 // The following conversions are performed on each expression used
4907 // as a non-type template-argument. If a non-type
4908 // template-argument cannot be converted to the type of the
4909 // corresponding template-parameter then the program is
4910 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00004911 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00004912 // C++11:
4913 // -- for a non-type template-parameter of integral or
4914 // enumeration type, conversions permitted in a converted
4915 // constant expression are applied.
4916 //
4917 // C++98:
4918 // -- for a non-type template-parameter of integral or
4919 // enumeration type, integral promotions (4.5) and integral
4920 // conversions (4.7) are applied.
4921
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004922 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00004923 // We can't check arbitrary value-dependent arguments.
4924 // FIXME: If there's no viable conversion to the template parameter type,
4925 // we should be able to diagnose that prior to instantiation.
4926 if (Arg->isValueDependent()) {
4927 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004928 return Arg;
Richard Smithf8379a02012-01-18 23:55:52 +00004929 }
4930
4931 // C++ [temp.arg.nontype]p1:
4932 // A template-argument for a non-type, non-template template-parameter
4933 // shall be one of:
4934 //
4935 // -- for a non-type template-parameter of integral or enumeration
4936 // type, a converted constant expression of the type of the
4937 // template-parameter; or
4938 llvm::APSInt Value;
4939 ExprResult ArgResult =
4940 CheckConvertedConstantExpression(Arg, ParamType, Value,
4941 CCEK_TemplateArg);
4942 if (ArgResult.isInvalid())
4943 return ExprError();
4944
4945 // Widen the argument value to sizeof(parameter type). This is almost
4946 // always a no-op, except when the parameter type is bool. In
4947 // that case, this may extend the argument from 1 bit to 8 bits.
4948 QualType IntegerType = ParamType;
4949 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
4950 IntegerType = Enum->getDecl()->getIntegerType();
4951 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
4952
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004953 Converted = TemplateArgument(Context, Value,
4954 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00004955 return ArgResult;
4956 }
4957
Richard Smith08b12f12011-10-27 22:11:44 +00004958 ExprResult ArgResult = DefaultLvalueConversion(Arg);
4959 if (ArgResult.isInvalid())
4960 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004961 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00004962
4963 QualType ArgType = Arg->getType();
4964
Douglas Gregor86560402009-02-10 23:36:10 +00004965 // C++ [temp.arg.nontype]p1:
4966 // A template-argument for a non-type, non-template
4967 // template-parameter shall be one of:
4968 //
4969 // -- an integral constant-expression of integral or enumeration
4970 // type; or
4971 // -- the name of a non-type template-parameter; or
4972 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00004973 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00004974 if (!ArgType->isIntegralOrEnumerationType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004975 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00004976 diag::err_template_arg_not_integral_or_enumeral)
4977 << ArgType << Arg->getSourceRange();
4978 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00004979 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00004980 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00004981 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
4982 QualType T;
4983
4984 public:
4985 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00004986
4987 void diagnoseNotICE(Sema &S, SourceLocation Loc,
4988 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00004989 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
4990 }
4991 } Diagnoser(ArgType);
4992
4993 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004994 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00004995 if (!Arg)
4996 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00004997 }
4998
Richard Smithd663fdd2014-12-17 20:42:37 +00004999 // From here on out, all we care about is the unqualified form
5000 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005001 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00005002
5003 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00005004 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00005005 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00005006 } else if (ParamType->isBooleanType()) {
5007 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005008 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005009 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
5010 !ParamType->isEnumeralType()) {
5011 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005012 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005013 } else {
5014 // We can't perform this conversion.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005015 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005016 diag::err_template_arg_not_convertible)
Richard Smithd663fdd2014-12-17 20:42:37 +00005017 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00005018 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005019 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005020 }
5021
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005022 // Add the value of this argument to the list of converted
5023 // arguments. We use the bitwidth and signedness of the template
5024 // parameter.
5025 if (Arg->isValueDependent()) {
5026 // The argument is value-dependent. Create a new
5027 // TemplateArgument with the converted expression.
5028 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005029 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005030 }
5031
Douglas Gregor52aba872009-03-14 00:20:21 +00005032 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00005033 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00005034 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00005035
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005036 if (ParamType->isBooleanType()) {
5037 // Value must be zero or one.
5038 Value = Value != 0;
5039 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5040 if (Value.getBitWidth() != AllowedBits)
5041 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005042 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005043 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005044 llvm::APSInt OldValue = Value;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005045
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005046 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005047 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005048 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005049 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005050 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005051 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005052
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005053 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005054 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005055 && (OldValue.isSigned() && OldValue.isNegative())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005056 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005057 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5058 << Arg->getSourceRange();
5059 Diag(Param->getLocation(), diag::note_template_param_here);
5060 }
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005061
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005062 // Complain if we overflowed the template parameter's type.
5063 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005064 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005065 RequiredBits = OldValue.getActiveBits();
5066 else if (OldValue.isUnsigned())
5067 RequiredBits = OldValue.getActiveBits() + 1;
5068 else
5069 RequiredBits = OldValue.getMinSignedBits();
5070 if (RequiredBits > AllowedBits) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005071 Diag(Arg->getLocStart(),
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005072 diag::warn_template_arg_too_large)
5073 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5074 << Arg->getSourceRange();
5075 Diag(Param->getLocation(), diag::note_template_param_here);
5076 }
Douglas Gregor52aba872009-03-14 00:20:21 +00005077 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005078
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005079 Converted = TemplateArgument(Context, Value,
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00005080 ParamType->isEnumeralType()
5081 ? Context.getCanonicalType(ParamType)
5082 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005083 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00005084 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005085
Richard Smith08b12f12011-10-27 22:11:44 +00005086 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00005087 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
5088
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005089 // Handle pointer-to-function, reference-to-function, and
5090 // pointer-to-member-function all in (roughly) the same way.
5091 if (// -- For a non-type template-parameter of type pointer to
5092 // function, only the function-to-pointer conversion (4.3) is
5093 // applied. If the template-argument represents a set of
5094 // overloaded functions (or a pointer to such), the matching
5095 // function is selected from the set (13.4).
5096 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005097 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005098 // -- For a non-type template-parameter of type reference to
5099 // function, no conversions apply. If the template-argument
5100 // represents a set of overloaded functions, the matching
5101 // function is selected from the set (13.4).
5102 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005103 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005104 // -- For a non-type template-parameter of type pointer to
5105 // member function, no conversions apply. If the
5106 // template-argument represents a set of overloaded member
5107 // functions, the matching member function is selected from
5108 // the set (13.4).
5109 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005110 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005111 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005112
Douglas Gregor064fdb22010-04-14 23:11:21 +00005113 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005114 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00005115 true,
5116 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005117 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005118 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005119
5120 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5121 ArgType = Arg->getType();
5122 } else
John Wiegley01296292011-04-08 18:41:53 +00005123 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005124 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005125
John Wiegley01296292011-04-08 18:41:53 +00005126 if (!ParamType->isMemberPointerType()) {
5127 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5128 ParamType,
5129 Arg, Converted))
5130 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005131 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00005132 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00005133
Douglas Gregor20fdef32012-04-10 17:08:25 +00005134 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5135 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005136 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005137 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005138 }
5139
Chris Lattner696197c2009-02-20 21:37:53 +00005140 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005141 // -- for a non-type template-parameter of type pointer to
5142 // object, qualification conversions (4.4) and the
5143 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00005144 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00005145 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005146 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005147
John Wiegley01296292011-04-08 18:41:53 +00005148 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5149 ParamType,
5150 Arg, Converted))
5151 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005152 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00005153 }
Mike Stump11289f42009-09-09 15:08:12 +00005154
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005155 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005156 // -- For a non-type template-parameter of type reference to
5157 // object, no conversions apply. The type referred to by the
5158 // reference may be more cv-qualified than the (otherwise
5159 // identical) type of the template-argument. The
5160 // template-parameter is bound directly to the
5161 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00005162 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005163 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005164
Douglas Gregor064fdb22010-04-14 23:11:21 +00005165 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005166 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
5167 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00005168 true,
5169 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005170 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005171 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005172
5173 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5174 ArgType = Arg->getType();
5175 } else
John Wiegley01296292011-04-08 18:41:53 +00005176 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005177 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005178
John Wiegley01296292011-04-08 18:41:53 +00005179 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5180 ParamType,
5181 Arg, Converted))
5182 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005183 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005184 }
Douglas Gregor0e558532009-02-11 16:16:59 +00005185
Douglas Gregor20fdef32012-04-10 17:08:25 +00005186 // Deal with parameters of type std::nullptr_t.
5187 if (ParamType->isNullPtrType()) {
5188 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5189 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005190 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005191 }
5192
5193 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
5194 case NPV_NotNullPointer:
5195 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
5196 << Arg->getType() << ParamType;
5197 Diag(Param->getLocation(), diag::note_template_param_here);
5198 return ExprError();
5199
5200 case NPV_Error:
5201 return ExprError();
5202
5203 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00005204 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005205 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
5206 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005207 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005208 }
5209 }
5210
Douglas Gregor0e558532009-02-11 16:16:59 +00005211 // -- For a non-type template-parameter of type pointer to data
5212 // member, qualification conversions (4.4) are applied.
5213 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
5214
Douglas Gregor20fdef32012-04-10 17:08:25 +00005215 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5216 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005217 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005218 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00005219}
5220
5221/// \brief Check a template argument against its corresponding
5222/// template template parameter.
5223///
5224/// This routine implements the semantics of C++ [temp.arg.template].
5225/// It returns true if an error occurred, and false otherwise.
5226bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00005227 TemplateArgumentLoc &Arg,
Richard Smith1fde8ec2012-09-07 02:06:42 +00005228 unsigned ArgumentPackIndex) {
Eli Friedmanb826a002012-09-26 02:36:12 +00005229 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005230 TemplateDecl *Template = Name.getAsTemplateDecl();
5231 if (!Template) {
5232 // Any dependent template name is fine.
5233 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5234 return false;
5235 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00005236
Richard Smith3f1b5d02011-05-05 21:57:07 +00005237 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00005238 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00005239 // the name of a class template or an alias template, expressed as an
5240 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00005241 // primary class templates are considered when matching the
5242 // template template argument with the corresponding parameter;
5243 // partial specializations are not considered even if their
5244 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00005245 //
5246 // Note that we also allow template template parameters here, which
5247 // will happen when we are dealing with, e.g., class template
5248 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00005249 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00005250 !isa<TemplateTemplateParmDecl>(Template) &&
5251 !isa<TypeAliasTemplateDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00005252 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00005253 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005254 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005255 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00005256 << Template;
5257 }
5258
Richard Smith1fde8ec2012-09-07 02:06:42 +00005259 TemplateParameterList *Params = Param->getTemplateParameters();
5260 if (Param->isExpandedParameterPack())
5261 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5262
Douglas Gregor85e0f662009-02-10 00:24:35 +00005263 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00005264 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005265 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005266 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005267 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00005268}
5269
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005270/// \brief Given a non-type template argument that refers to a
5271/// declaration and the type of its corresponding non-type template
5272/// parameter, produce an expression that properly refers to that
5273/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005274ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005275Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5276 QualType ParamType,
5277 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00005278 // C++ [temp.param]p8:
5279 //
5280 // A non-type template-parameter of type "array of T" or
5281 // "function returning T" is adjusted to be of type "pointer to
5282 // T" or "pointer to function returning T", respectively.
5283 if (ParamType->isArrayType())
5284 ParamType = Context.getArrayDecayedType(ParamType);
5285 else if (ParamType->isFunctionType())
5286 ParamType = Context.getPointerType(ParamType);
5287
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005288 // For a NULL non-type template argument, return nullptr casted to the
5289 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00005290 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005291 return ImpCastExprToType(
5292 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
5293 ParamType,
5294 ParamType->getAs<MemberPointerType>()
5295 ? CK_NullToMemberPointer
5296 : CK_NullToPointer);
5297 }
Eli Friedmanb826a002012-09-26 02:36:12 +00005298 assert(Arg.getKind() == TemplateArgument::Declaration &&
5299 "Only declaration template arguments permitted here");
5300
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005301 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5302
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005303 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00005304 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5305 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005306 // If the value is a class member, we might have a pointer-to-member.
5307 // Determine whether the non-type template template parameter is of
5308 // pointer-to-member type. If so, we need to build an appropriate
5309 // expression for a pointer-to-member, since a "normal" DeclRefExpr
5310 // would refer to the member itself.
5311 if (ParamType->isMemberPointerType()) {
5312 QualType ClassType
5313 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5314 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00005315 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00005316 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005317 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00005318 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00005319
5320 // The actual value-ness of this is unimportant, but for
5321 // internal consistency's sake, references to instance methods
5322 // are r-values.
5323 ExprValueKind VK = VK_LValue;
5324 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5325 VK = VK_RValue;
5326
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005327 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00005328 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00005329 VK,
John McCall7decc9e2010-11-18 06:31:45 +00005330 Loc,
5331 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005332 if (RefExpr.isInvalid())
5333 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005334
John McCalle3027922010-08-25 11:45:40 +00005335 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005336
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005337 // We might need to perform a trailing qualification conversion, since
5338 // the element type on the parameter could be more qualified than the
5339 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00005340 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005341 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00005342 ParamType.getUnqualifiedType(), false,
5343 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005344 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005345
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005346 assert(!RefExpr.isInvalid() &&
5347 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005348 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005349 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005350 }
5351 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005352
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005353 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005354
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005355 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005356 // When the non-type template parameter is a pointer, take the
5357 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00005358 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005359 if (RefExpr.isInvalid())
5360 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005361
5362 if (T->isFunctionType() || T->isArrayType()) {
5363 // Decay functions and arrays.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005364 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00005365 if (RefExpr.isInvalid())
5366 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005367
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005368 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005369 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005370
Douglas Gregorb242683d2010-04-01 18:32:35 +00005371 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00005372 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005373 }
5374
John McCall7decc9e2010-11-18 06:31:45 +00005375 ExprValueKind VK = VK_RValue;
5376
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005377 // If the non-type template parameter has reference type, qualify the
5378 // resulting declaration reference with the extra qualifiers on the
5379 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00005380 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5381 VK = VK_LValue;
5382 T = Context.getQualifiedType(T,
5383 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005384 } else if (isa<FunctionDecl>(VD)) {
5385 // References to functions are always lvalues.
5386 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00005387 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005388
John McCall7decc9e2010-11-18 06:31:45 +00005389 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005390}
5391
5392/// \brief Construct a new expression that refers to the given
5393/// integral template argument with the given source-location
5394/// information.
5395///
5396/// This routine takes care of the mapping from an integral template
5397/// argument (which may have any integral type) to the appropriate
5398/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005399ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005400Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5401 SourceLocation Loc) {
5402 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00005403 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005404 QualType OrigT = Arg.getIntegralType();
5405
5406 // If this is an enum type that we're instantiating, we need to use an integer
5407 // type the same size as the enumerator. We don't want to build an
5408 // IntegerLiteral with enum type. The integer type of an enum type can be of
5409 // any integral type with C++11 enum classes, make sure we create the right
5410 // type of literal for it.
5411 QualType T = OrigT;
5412 if (const EnumType *ET = OrigT->getAs<EnumType>())
5413 T = ET->getDecl()->getIntegerType();
5414
5415 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00005416 if (T->isAnyCharacterType()) {
5417 CharacterLiteral::CharacterKind Kind;
5418 if (T->isWideCharType())
5419 Kind = CharacterLiteral::Wide;
5420 else if (T->isChar16Type())
5421 Kind = CharacterLiteral::UTF16;
5422 else if (T->isChar32Type())
5423 Kind = CharacterLiteral::UTF32;
5424 else
5425 Kind = CharacterLiteral::Ascii;
5426
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005427 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
5428 Kind, T, Loc);
5429 } else if (T->isBooleanType()) {
5430 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
5431 T, Loc);
5432 } else if (T->isNullPtrType()) {
5433 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
5434 } else {
5435 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00005436 }
5437
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005438 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00005439 // FIXME: This is a hack. We need a better way to handle substituted
5440 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00005441 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
5442 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005443 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00005444 Loc, Loc);
5445 }
5446
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005447 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005448}
5449
Douglas Gregor641040a2011-01-12 23:45:44 +00005450/// \brief Match two template parameters within template parameter lists.
5451static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
5452 bool Complain,
5453 Sema::TemplateParameterListEqualKind Kind,
5454 SourceLocation TemplateArgLoc) {
5455 // Check the actual kind (type, non-type, template).
5456 if (Old->getKind() != New->getKind()) {
5457 if (Complain) {
5458 unsigned NextDiag = diag::err_template_param_different_kind;
5459 if (TemplateArgLoc.isValid()) {
5460 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5461 NextDiag = diag::note_template_param_different_kind;
5462 }
5463 S.Diag(New->getLocation(), NextDiag)
5464 << (Kind != Sema::TPL_TemplateMatch);
5465 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
5466 << (Kind != Sema::TPL_TemplateMatch);
5467 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005468
Douglas Gregor641040a2011-01-12 23:45:44 +00005469 return false;
5470 }
5471
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005472 // Check that both are parameter packs are neither are parameter packs.
5473 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005474 // template template parameter, the template template parameter can have
5475 // a parameter pack where the template template argument does not.
5476 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
5477 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5478 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00005479 if (Complain) {
5480 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
5481 if (TemplateArgLoc.isValid()) {
5482 S.Diag(TemplateArgLoc,
5483 diag::err_template_arg_template_params_mismatch);
5484 NextDiag = diag::note_template_parameter_pack_non_pack;
5485 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005486
Douglas Gregor641040a2011-01-12 23:45:44 +00005487 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
5488 : isa<NonTypeTemplateParmDecl>(New)? 1
5489 : 2;
5490 S.Diag(New->getLocation(), NextDiag)
5491 << ParamKind << New->isParameterPack();
5492 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
5493 << ParamKind << Old->isParameterPack();
5494 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005495
Douglas Gregor641040a2011-01-12 23:45:44 +00005496 return false;
5497 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005498
Douglas Gregor641040a2011-01-12 23:45:44 +00005499 // For non-type template parameters, check the type of the parameter.
5500 if (NonTypeTemplateParmDecl *OldNTTP
5501 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
5502 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005503
Douglas Gregor641040a2011-01-12 23:45:44 +00005504 // If we are matching a template template argument to a template
5505 // template parameter and one of the non-type template parameter types
5506 // is dependent, then we must wait until template instantiation time
5507 // to actually compare the arguments.
5508 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5509 (OldNTTP->getType()->isDependentType() ||
5510 NewNTTP->getType()->isDependentType()))
5511 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005512
Douglas Gregor641040a2011-01-12 23:45:44 +00005513 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
5514 if (Complain) {
5515 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
5516 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005517 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00005518 diag::err_template_arg_template_params_mismatch);
5519 NextDiag = diag::note_template_nontype_parm_different_type;
5520 }
5521 S.Diag(NewNTTP->getLocation(), NextDiag)
5522 << NewNTTP->getType()
5523 << (Kind != Sema::TPL_TemplateMatch);
5524 S.Diag(OldNTTP->getLocation(),
5525 diag::note_template_nontype_parm_prev_declaration)
5526 << OldNTTP->getType();
5527 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005528
Douglas Gregor641040a2011-01-12 23:45:44 +00005529 return false;
5530 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005531
Douglas Gregor641040a2011-01-12 23:45:44 +00005532 return true;
5533 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005534
Douglas Gregor641040a2011-01-12 23:45:44 +00005535 // For template template parameters, check the template parameter types.
5536 // The template parameter lists of template template
5537 // parameters must agree.
5538 if (TemplateTemplateParmDecl *OldTTP
5539 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005540 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00005541 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
5542 OldTTP->getTemplateParameters(),
5543 Complain,
5544 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005545 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00005546 : Kind),
5547 TemplateArgLoc);
5548 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005549
Douglas Gregor641040a2011-01-12 23:45:44 +00005550 return true;
5551}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005552
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005553/// \brief Diagnose a known arity mismatch when comparing template argument
5554/// lists.
5555static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005556void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005557 TemplateParameterList *New,
5558 TemplateParameterList *Old,
5559 Sema::TemplateParameterListEqualKind Kind,
5560 SourceLocation TemplateArgLoc) {
5561 unsigned NextDiag = diag::err_template_param_list_different_arity;
5562 if (TemplateArgLoc.isValid()) {
5563 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5564 NextDiag = diag::note_template_param_list_different_arity;
5565 }
5566 S.Diag(New->getTemplateLoc(), NextDiag)
5567 << (New->size() > Old->size())
5568 << (Kind != Sema::TPL_TemplateMatch)
5569 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
5570 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
5571 << (Kind != Sema::TPL_TemplateMatch)
5572 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
5573}
5574
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005575/// \brief Determine whether the given template parameter lists are
5576/// equivalent.
5577///
Mike Stump11289f42009-09-09 15:08:12 +00005578/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005579/// source code as part of a new template declaration.
5580///
5581/// \param Old The old template parameter list, typically found via
5582/// name lookup of the template declared with this template parameter
5583/// list.
5584///
5585/// \param Complain If true, this routine will produce a diagnostic if
5586/// the template parameter lists are not equivalent.
5587///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005588/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00005589///
5590/// \param TemplateArgLoc If this source location is valid, then we
5591/// are actually checking the template parameter list of a template
5592/// argument (New) against the template parameter list of its
5593/// corresponding template template parameter (Old). We produce
5594/// slightly different diagnostics in this scenario.
5595///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005596/// \returns True if the template parameter lists are equal, false
5597/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005598bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005599Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
5600 TemplateParameterList *Old,
5601 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005602 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00005603 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005604 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
5605 if (Complain)
5606 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5607 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005608
5609 return false;
5610 }
5611
Douglas Gregor641040a2011-01-12 23:45:44 +00005612 // C++0x [temp.arg.template]p3:
5613 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005614 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00005615 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005616 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005617 // template-parameter-list of P. [...]
5618 TemplateParameterList::iterator NewParm = New->begin();
5619 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005620 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005621 OldParmEnd = Old->end();
5622 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00005623 if (Kind != TPL_TemplateTemplateArgumentMatch ||
5624 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005625 if (NewParm == NewParmEnd) {
5626 if (Complain)
5627 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5628 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005629
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005630 return false;
5631 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005632
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005633 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5634 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005635 return false;
5636
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005637 ++NewParm;
5638 continue;
5639 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005640
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005641 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005642 // [...] When P's template- parameter-list contains a template parameter
5643 // pack (14.5.3), the template parameter pack will match zero or more
5644 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005645 // template-parameter-list of A with the same type and form as the
5646 // template parameter pack in P (ignoring whether those template
5647 // parameters are template parameter packs).
5648 for (; NewParm != NewParmEnd; ++NewParm) {
5649 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5650 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005651 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005652 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005653 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005654
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005655 // Make sure we exhausted all of the arguments.
5656 if (NewParm != NewParmEnd) {
5657 if (Complain)
5658 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5659 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005660
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005661 return false;
5662 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005663
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005664 return true;
5665}
5666
5667/// \brief Check whether a template can be declared within this scope.
5668///
5669/// If the template declaration is valid in this scope, returns
5670/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00005671bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005672Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00005673 if (!S)
5674 return false;
5675
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005676 // Find the nearest enclosing declaration scope.
5677 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5678 (S->getFlags() & Scope::TemplateParamScope) != 0)
5679 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00005680
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005681 // C++ [temp]p4:
5682 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00005683 DeclContext *Ctx = S->getEntity();
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005684 if (Ctx && Ctx->isExternCContext())
Mike Stump11289f42009-09-09 15:08:12 +00005685 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005686 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005687
Eli Friedmandfbd0c42009-07-31 01:43:05 +00005688 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005689 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005690
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005691 // C++ [temp]p2:
5692 // A template-declaration can appear only as a namespace scope or
5693 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00005694 if (Ctx) {
5695 if (Ctx->isFileContext())
5696 return false;
5697 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
5698 // C++ [temp.mem]p2:
5699 // A local class shall not have member templates.
5700 if (RD->isLocalClass())
5701 return Diag(TemplateParams->getTemplateLoc(),
5702 diag::err_template_inside_local_class)
5703 << TemplateParams->getSourceRange();
5704 else
5705 return false;
5706 }
5707 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005708
Mike Stump11289f42009-09-09 15:08:12 +00005709 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005710 diag::err_template_outside_namespace_or_class_scope)
5711 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005712}
Douglas Gregor67a65642009-02-17 23:15:12 +00005713
Douglas Gregor54888652009-10-07 00:13:32 +00005714/// \brief Determine what kind of template specialization the given declaration
5715/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00005716static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00005717 if (!D)
5718 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005719
Douglas Gregorbbe8f462009-10-08 15:14:33 +00005720 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
5721 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00005722 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
5723 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00005724 if (VarDecl *Var = dyn_cast<VarDecl>(D))
5725 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005726
Douglas Gregor54888652009-10-07 00:13:32 +00005727 return TSK_Undeclared;
5728}
5729
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005730/// \brief Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005731/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00005732///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005733/// This routine determines whether a template specialization can be declared
5734/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00005735///
5736/// \param S the semantic analysis object for which this check is being
5737/// performed.
5738///
5739/// \param Specialized the entity being specialized or instantiated, which
5740/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005741/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00005742/// member class).
5743///
5744/// \param PrevDecl the previous declaration of this entity, if any.
5745///
5746/// \param Loc the location of the explicit specialization or instantiation of
5747/// this entity.
5748///
5749/// \param IsPartialSpecialization whether this is a partial specialization of
5750/// a class template.
5751///
Douglas Gregor54888652009-10-07 00:13:32 +00005752/// \returns true if there was an error that we cannot recover from, false
5753/// otherwise.
5754static bool CheckTemplateSpecializationScope(Sema &S,
5755 NamedDecl *Specialized,
5756 NamedDecl *PrevDecl,
5757 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005758 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00005759 // Keep these "kind" numbers in sync with the %select statements in the
5760 // various diagnostics emitted by this routine.
5761 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00005762 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005763 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005764 else if (isa<VarTemplateDecl>(Specialized))
5765 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00005766 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005767 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005768 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005769 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005770 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00005771 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005772 else if (isa<RecordDecl>(Specialized))
5773 EntityKind = 7;
5774 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
5775 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00005776 else {
Richard Smith7d137e32012-03-23 03:33:32 +00005777 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005778 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005779 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00005780 return true;
5781 }
5782
Douglas Gregorf47b9112009-02-25 22:02:03 +00005783 // C++ [temp.expl.spec]p2:
5784 // An explicit specialization shall be declared in the namespace
5785 // of which the template is a member, or, for member templates, in
5786 // the namespace of which the enclosing class or enclosing class
5787 // template is a member. An explicit specialization of a member
5788 // function, member class or static data member of a class
5789 // template shall be declared in the namespace of which the class
5790 // template is a member. Such a declaration may also be a
5791 // definition. If the declaration is not a definition, the
5792 // specialization may be defined later in the name- space in which
5793 // the explicit specialization was declared, or in a namespace
5794 // that encloses the one in which the explicit specialization was
5795 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00005796 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00005797 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005798 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00005799 return true;
5800 }
Douglas Gregore4b05162009-10-07 17:21:34 +00005801
Douglas Gregor40fb7442009-10-07 17:30:37 +00005802 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005803 if (S.getLangOpts().MicrosoftExt) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00005804 // Do not warn for class scope explicit specialization during
5805 // instantiation, warning was already emitted during pattern
5806 // semantic analysis.
5807 if (!S.ActiveTemplateInstantiations.size())
5808 S.Diag(Loc, diag::ext_function_specialization_in_class)
5809 << Specialized;
5810 } else {
5811 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5812 << Specialized;
5813 return true;
5814 }
Douglas Gregor40fb7442009-10-07 17:30:37 +00005815 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005816
Douglas Gregor44e5a0a2011-10-20 16:41:18 +00005817 if (S.CurContext->isRecord() &&
5818 !S.CurContext->Equals(Specialized->getDeclContext())) {
5819 // Make sure that we're specializing in the right record context.
5820 // Otherwise, things can go horribly wrong.
5821 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5822 << Specialized;
5823 return true;
5824 }
5825
Douglas Gregore4b05162009-10-07 17:21:34 +00005826 // C++ [temp.class.spec]p6:
5827 // A class template partial specialization may be declared or redeclared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005828 // in any namespace scope in which its definition may be defined (14.5.1
5829 // and 14.5.2).
Richard Smitha98f8fc2013-12-07 05:09:50 +00005830 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00005831 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00005832 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00005833
5834 // Make sure that this redeclaration (or definition) occurs in an enclosing
5835 // namespace.
5836 // Note that HandleDeclarator() performs this check for explicit
5837 // specializations of function templates, static data members, and member
5838 // functions, so we skip the check here for those kinds of entities.
5839 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
5840 // Should we refactor that check, so that it occurs later?
5841 if (!DC->Encloses(SpecializedContext) &&
5842 !(isa<FunctionTemplateDecl>(Specialized) ||
5843 isa<FunctionDecl>(Specialized) ||
5844 isa<VarTemplateDecl>(Specialized) ||
5845 isa<VarDecl>(Specialized))) {
5846 if (isa<TranslationUnitDecl>(SpecializedContext))
5847 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
5848 << EntityKind << Specialized;
Alexey Bataev0068cb22015-03-20 07:21:46 +00005849 else if (isa<NamespaceDecl>(SpecializedContext)) {
5850 int Diag = diag::err_template_spec_redecl_out_of_scope;
5851 if (S.getLangOpts().MicrosoftExt)
5852 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
5853 S.Diag(Loc, Diag) << EntityKind << Specialized
5854 << cast<NamedDecl>(SpecializedContext);
5855 } else
Richard Smitha98f8fc2013-12-07 05:09:50 +00005856 llvm_unreachable("unexpected namespace context for specialization");
5857
5858 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5859 } else if ((!PrevDecl ||
5860 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
5861 getTemplateSpecializationKind(PrevDecl) ==
5862 TSK_ImplicitInstantiation)) {
Douglas Gregorb1aab432010-09-12 05:08:28 +00005863 // C++ [temp.exp.spec]p2:
5864 // An explicit specialization shall be declared in the namespace of which
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005865 // the template is a member, or, for member templates, in the namespace
Douglas Gregorb1aab432010-09-12 05:08:28 +00005866 // of which the enclosing class or enclosing class template is a member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005867 // An explicit specialization of a member function, member class or
5868 // static data member of a class template shall be declared in the
Douglas Gregorb1aab432010-09-12 05:08:28 +00005869 // namespace of which the class template is a member.
5870 //
Richard Smitha98f8fc2013-12-07 05:09:50 +00005871 // C++11 [temp.expl.spec]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005872 // An explicit specialization shall be declared in a namespace enclosing
Douglas Gregorb1aab432010-09-12 05:08:28 +00005873 // the specialized template.
Richard Smitha98f8fc2013-12-07 05:09:50 +00005874 // C++11 [temp.explicit]p3:
5875 // An explicit instantiation shall appear in an enclosing namespace of its
5876 // template.
Richard Smith0bf8a4922011-10-18 20:49:44 +00005877 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005878 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
Richard Smith0bf8a4922011-10-18 20:49:44 +00005879 if (isa<TranslationUnitDecl>(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005880 assert(!IsCPlusPlus11Extension &&
Richard Smith0bf8a4922011-10-18 20:49:44 +00005881 "DC encloses TU but isn't in enclosing namespace set");
5882 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor8ce63152010-09-12 05:24:55 +00005883 << EntityKind << Specialized;
Richard Smith0bf8a4922011-10-18 20:49:44 +00005884 } else if (isa<NamespaceDecl>(SpecializedContext)) {
5885 int Diag;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005886 if (!IsCPlusPlus11Extension)
Richard Smith0bf8a4922011-10-18 20:49:44 +00005887 Diag = diag::err_template_spec_decl_out_of_scope;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005888 else if (!S.getLangOpts().CPlusPlus11)
Richard Smith0bf8a4922011-10-18 20:49:44 +00005889 Diag = diag::ext_template_spec_decl_out_of_scope;
5890 else
5891 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
5892 S.Diag(Loc, Diag)
5893 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
5894 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005895
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005896 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00005897 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00005898 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005899
Douglas Gregorf47b9112009-02-25 22:02:03 +00005900 return false;
5901}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005902
Richard Smith6056d5e2014-02-09 00:54:43 +00005903static SourceRange findTemplateParameter(unsigned Depth, Expr *E) {
5904 if (!E->isInstantiationDependent())
5905 return SourceLocation();
5906 DependencyChecker Checker(Depth);
5907 Checker.TraverseStmt(E);
5908 if (Checker.Match && Checker.MatchLoc.isInvalid())
5909 return E->getSourceRange();
5910 return Checker.MatchLoc;
5911}
5912
5913static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
5914 if (!TL.getType()->isDependentType())
5915 return SourceLocation();
5916 DependencyChecker Checker(Depth);
5917 Checker.TraverseTypeLoc(TL);
5918 if (Checker.Match && Checker.MatchLoc.isInvalid())
5919 return TL.getSourceRange();
5920 return Checker.MatchLoc;
5921}
5922
Larisse Voufo39a1e502013-08-06 01:03:05 +00005923/// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005924/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00005925static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00005926 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
5927 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005928 for (unsigned I = 0; I != NumArgs; ++I) {
5929 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005930 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00005931 S, TemplateNameLoc, Param, Args[I].pack_begin(),
5932 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005933 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005934
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005935 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005936 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005937
Eli Friedmanb826a002012-09-26 02:36:12 +00005938 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005939 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00005940
5941 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005942
Douglas Gregor98318c22011-01-03 21:37:45 +00005943 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005944 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
5945 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00005946
5947 // Strip off any implicit casts we added as part of type checking.
5948 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
5949 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005950
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005951 // C++ [temp.class.spec]p8:
5952 // A non-type argument is non-specialized if it is the name of a
5953 // non-type parameter. All other non-type arguments are
5954 // specialized.
5955 //
5956 // Below, we check the two conditions that only apply to
5957 // specialized non-type arguments, so skip any non-specialized
5958 // arguments.
5959 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00005960 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005961 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005962
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005963 // C++ [temp.class.spec]p9:
5964 // Within the argument list of a class template partial
5965 // specialization, the following restrictions apply:
5966 // -- A partially specialized non-type argument expression
5967 // shall not involve a template parameter of the partial
5968 // specialization except when the argument expression is a
5969 // simple identifier.
Richard Smith6056d5e2014-02-09 00:54:43 +00005970 SourceRange ParamUseRange =
5971 findTemplateParameter(Param->getDepth(), ArgExpr);
5972 if (ParamUseRange.isValid()) {
5973 if (IsDefaultArgument) {
5974 S.Diag(TemplateNameLoc,
5975 diag::err_dependent_non_type_arg_in_partial_spec);
5976 S.Diag(ParamUseRange.getBegin(),
5977 diag::note_dependent_non_type_default_arg_in_partial_spec)
5978 << ParamUseRange;
5979 } else {
5980 S.Diag(ParamUseRange.getBegin(),
5981 diag::err_dependent_non_type_arg_in_partial_spec)
5982 << ParamUseRange;
5983 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005984 return true;
5985 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005986
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005987 // -- The type of a template parameter corresponding to a
5988 // specialized non-type argument shall not be dependent on a
5989 // parameter of the specialization.
Richard Smith6056d5e2014-02-09 00:54:43 +00005990 //
5991 // FIXME: We need to delay this check until instantiation in some cases:
5992 //
5993 // template<template<typename> class X> struct A {
5994 // template<typename T, X<T> N> struct B;
5995 // template<typename T> struct B<T, 0>;
5996 // };
5997 // template<typename> using X = int;
5998 // A<X>::B<int, 0> b;
5999 ParamUseRange = findTemplateParameter(
6000 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
6001 if (ParamUseRange.isValid()) {
6002 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
6003 diag::err_dependent_typed_non_type_arg_in_partial_spec)
6004 << Param->getType() << ParamUseRange;
6005 S.Diag(Param->getLocation(), diag::note_template_param_here)
6006 << (IsDefaultArgument ? ParamUseRange : SourceRange());
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006007 return true;
6008 }
6009 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006010
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006011 return false;
6012}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006013
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006014/// \brief Check the non-type template arguments of a class template
6015/// partial specialization according to C++ [temp.class.spec]p9.
6016///
Richard Smith6056d5e2014-02-09 00:54:43 +00006017/// \param TemplateNameLoc the location of the template name.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006018/// \param TemplateParams the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00006019/// template.
6020/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00006021/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00006022/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006023///
Richard Smith6056d5e2014-02-09 00:54:43 +00006024/// \returns \c true if there was an error, \c false otherwise.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006025static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006026 Sema &S, SourceLocation TemplateNameLoc,
6027 TemplateParameterList *TemplateParams, unsigned NumExplicit,
Larisse Voufo39a1e502013-08-06 01:03:05 +00006028 SmallVectorImpl<TemplateArgument> &TemplateArgs) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006029 const TemplateArgument *ArgList = TemplateArgs.data();
6030
6031 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6032 NonTypeTemplateParmDecl *Param
6033 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
6034 if (!Param)
6035 continue;
6036
Richard Smith6056d5e2014-02-09 00:54:43 +00006037 if (CheckNonTypeTemplatePartialSpecializationArgs(
6038 S, TemplateNameLoc, Param, &ArgList[I], 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006039 return true;
6040 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006041
6042 return false;
6043}
6044
John McCall48871652010-08-21 09:40:31 +00006045DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00006046Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
6047 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00006048 SourceLocation KWLoc,
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006049 SourceLocation ModulePrivateLoc,
Richard Smith4b55a9c2014-04-17 03:29:33 +00006050 TemplateIdAnnotation &TemplateId,
Douglas Gregor67a65642009-02-17 23:15:12 +00006051 AttributeList *Attr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00006052 MultiTemplateParamsArg
6053 TemplateParameterLists,
6054 SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006055 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00006056
Richard Smith4b55a9c2014-04-17 03:29:33 +00006057 CXXScopeSpec &SS = TemplateId.SS;
6058
Abramo Bagnara60804e12011-03-18 15:16:37 +00006059 // NOTE: KWLoc is the location of the tag keyword. This will instead
6060 // store the location of the outermost template keyword in the declaration.
6061 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00006062 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
6063 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
6064 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
6065 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00006066
Douglas Gregor67a65642009-02-17 23:15:12 +00006067 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00006068 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00006069 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00006070 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
6071
6072 if (!ClassTemplate) {
6073 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006074 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00006075 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
6076 return true;
6077 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006078
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006079 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00006080 bool isPartialSpecialization = false;
6081
Douglas Gregorf47b9112009-02-25 22:02:03 +00006082 // Check the validity of the template headers that introduce this
6083 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00006084 // FIXME: We probably shouldn't complain about these headers for
6085 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006086 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00006087 TemplateParameterList *TemplateParams =
6088 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00006089 KWLoc, TemplateNameLoc, SS, &TemplateId,
6090 TemplateParameterLists, TUK == TUK_Friend, isExplicitSpecialization,
6091 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006092 if (Invalid)
6093 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006094
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006095 if (TemplateParams && TemplateParams->size() > 0) {
6096 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00006097
Douglas Gregorec9518b2010-12-21 08:14:57 +00006098 if (TUK == TUK_Friend) {
6099 Diag(KWLoc, diag::err_partial_specialization_friend)
6100 << SourceRange(LAngleLoc, RAngleLoc);
6101 return true;
6102 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006103
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006104 // C++ [temp.class.spec]p10:
6105 // The template parameter list of a specialization shall not
6106 // contain default template argument values.
6107 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6108 Decl *Param = TemplateParams->getParam(I);
6109 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6110 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006111 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006112 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00006113 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006114 }
6115 } else if (NonTypeTemplateParmDecl *NTTP
6116 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6117 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006118 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006119 diag::err_default_arg_in_partial_spec)
6120 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006121 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006122 }
6123 } else {
6124 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006125 if (TTP->hasDefaultArgument()) {
6126 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006127 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006128 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006129 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00006130 }
6131 }
6132 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006133 } else if (TemplateParams) {
6134 if (TUK == TUK_Friend)
6135 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00006136 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006137 SourceRange(TemplateParams->getTemplateLoc(),
6138 TemplateParams->getRAngleLoc()))
6139 << SourceRange(LAngleLoc, RAngleLoc);
6140 else
6141 isExplicitSpecialization = true;
Richard Smith4b55a9c2014-04-17 03:29:33 +00006142 } else {
6143 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006144 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006145
Douglas Gregor67a65642009-02-17 23:15:12 +00006146 // Check that the specialization uses the same tag kind as the
6147 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00006148 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6149 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00006150 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00006151 Kind, TUK == TUK_Definition, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00006152 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00006153 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00006154 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00006155 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00006156 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00006157 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006158 diag::note_previous_use);
6159 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6160 }
6161
Douglas Gregorc40290e2009-03-09 23:48:35 +00006162 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00006163 TemplateArgumentListInfo TemplateArgs =
6164 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00006165
Douglas Gregor14406932011-01-03 20:35:03 +00006166 // Check for unexpanded parameter packs in any of the template arguments.
6167 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006168 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00006169 UPPC_PartialSpecialization))
6170 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006171
Douglas Gregor67a65642009-02-17 23:15:12 +00006172 // Check that the template argument list is well-formed for this
6173 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006174 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00006175 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6176 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006177 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006178
Douglas Gregor2373c592009-05-31 09:31:02 +00006179 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00006180 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00006181 if (isPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006182 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006183 *this, TemplateNameLoc, ClassTemplate->getTemplateParameters(),
6184 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006185 return true;
6186
Douglas Gregor678d76c2011-07-01 01:22:09 +00006187 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006188 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00006189 !TemplateSpecializationType::anyDependentTemplateArguments(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006190 TemplateArgs.getArgumentArray(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00006191 TemplateArgs.size(),
6192 InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00006193 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
6194 << ClassTemplate->getDeclName();
6195 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00006196 }
6197 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006198
Craig Topperc3ec1492014-05-26 06:22:03 +00006199 void *InsertPos = nullptr;
6200 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00006201
6202 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006203 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00006204 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006205 else
Craig Topper7e0daca2014-06-26 04:58:53 +00006206 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00006207
Craig Topperc3ec1492014-05-26 06:22:03 +00006208 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00006209
Douglas Gregorf47b9112009-02-25 22:02:03 +00006210 // Check whether we can declare a class template specialization in
6211 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00006212 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006213 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
6214 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006215 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006216 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006217
Douglas Gregor15301382009-07-30 17:40:51 +00006218 // The canonical type
6219 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00006220 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00006221 // Build the canonical type that describes the converted template
6222 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00006223 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6224 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006225 Converted.data(),
6226 Converted.size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006227
6228 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006229 ClassTemplate->getInjectedClassNameSpecialization())) {
6230 // C++ [temp.class.spec]p9b3:
6231 //
6232 // -- The argument list of the specialization shall not be identical
6233 // to the implicit argument list of the primary template.
6234 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00006235 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00006236 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006237 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
6238 ClassTemplate->getIdentifier(),
6239 TemplateNameLoc,
6240 Attr,
6241 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00006242 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00006243 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00006244 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006245 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006246 }
Douglas Gregor15301382009-07-30 17:40:51 +00006247
Douglas Gregor2373c592009-05-31 09:31:02 +00006248 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00006249 ClassTemplatePartialSpecializationDecl *PrevPartial
6250 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006251 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00006252 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00006253 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006254 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00006255 TemplateParams,
6256 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006257 Converted.data(),
6258 Converted.size(),
John McCall6b51f282009-11-23 01:53:49 +00006259 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00006260 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00006261 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00006262 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006263 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00006264 Partial->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +00006265 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006266 TemplateParameterLists.data());
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006267 }
Douglas Gregor2373c592009-05-31 09:31:02 +00006268
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006269 if (!PrevPartial)
6270 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006271 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00006272
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006273 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00006274 // template specialization, make a note of that.
6275 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6276 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006277
Douglas Gregor91772d12009-06-13 00:26:55 +00006278 // Check that all of the template parameters of the class template
6279 // partial specialization are deducible from the template
6280 // arguments. If not, this class template partial specialization
6281 // will never be used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006282 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006283 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00006284 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00006285 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00006286
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006287 if (!DeducibleParams.all()) {
6288 unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
Douglas Gregor91772d12009-06-13 00:26:55 +00006289 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00006290 << /*class template*/0 << (NumNonDeducible > 1)
Douglas Gregor91772d12009-06-13 00:26:55 +00006291 << SourceRange(TemplateNameLoc, RAngleLoc);
6292 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
6293 if (!DeducibleParams[I]) {
6294 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
6295 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00006296 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006297 diag::note_partial_spec_unused_parameter)
6298 << Param->getDeclName();
6299 else
Mike Stump11289f42009-09-09 15:08:12 +00006300 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006301 diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00006302 << "(anonymous)";
Douglas Gregor91772d12009-06-13 00:26:55 +00006303 }
6304 }
6305 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006306 } else {
6307 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00006308 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00006309 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00006310 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00006311 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006312 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006313 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006314 Converted.data(),
6315 Converted.size(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006316 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00006317 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006318 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00006319 Specialization->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +00006320 TemplateParameterLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006321 TemplateParameterLists.data());
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006322 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006323
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006324 if (!PrevDecl)
6325 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00006326
6327 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00006328 }
6329
Douglas Gregor06db9f52009-10-12 20:18:28 +00006330 // C++ [temp.expl.spec]p6:
6331 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006332 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006333 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006334 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006335 // use occurs; no diagnostic is required.
6336 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006337 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006338 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006339 // Is there any previous explicit specialization declaration?
6340 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6341 Okay = true;
6342 break;
6343 }
6344 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006345
Douglas Gregorc854c662010-02-26 06:03:23 +00006346 if (!Okay) {
6347 SourceRange Range(TemplateNameLoc, RAngleLoc);
6348 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6349 << Context.getTypeDeclType(Specialization) << Range;
6350
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006351 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00006352 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006353 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00006354 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00006355 return true;
6356 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006357 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006358
Douglas Gregor2208a292009-09-26 20:57:03 +00006359 // If this is not a friend, note that this is an explicit specialization.
6360 if (TUK != TUK_Friend)
6361 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00006362
6363 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006364 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00006365 RecordDecl *Def = Specialization->getDefinition();
6366 NamedDecl *Hidden = nullptr;
6367 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
6368 SkipBody->ShouldSkip = true;
6369 makeMergedDefinitionVisible(Hidden, KWLoc);
6370 // From here on out, treat this as just a redeclaration.
6371 TUK = TUK_Declaration;
6372 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00006373 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006374 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00006375 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00006376 Diag(Def->getLocation(), diag::note_previous_definition);
6377 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00006378 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006379 }
6380 }
6381
John McCall659a3372010-12-18 03:30:47 +00006382 if (Attr)
6383 ProcessDeclAttributeList(S, Specialization, Attr);
6384
Richard Smith034b94a2012-08-17 03:20:55 +00006385 // Add alignment attributes if necessary; these attributes are checked when
6386 // the ASTContext lays out the structure.
6387 if (TUK == TUK_Definition) {
6388 AddAlignmentAttributesForRecord(Specialization);
6389 AddMsStructLayoutForRecord(Specialization);
6390 }
6391
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006392 if (ModulePrivateLoc.isValid())
6393 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6394 << (isPartialSpecialization? 1 : 0)
6395 << FixItHint::CreateRemoval(ModulePrivateLoc);
6396
Douglas Gregord56a91e2009-02-26 22:19:44 +00006397 // Build the fully-sugared type for this class template
6398 // specialization as the user wrote in the specialization
6399 // itself. This means that we'll pretty-print the type retrieved
6400 // from the specialization's declaration the way that the user
6401 // actually wrote the specialization, rather than formatting the
6402 // name based on the "canonical" representation used to store the
6403 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00006404 TypeSourceInfo *WrittenTy
6405 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6406 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006407 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006408 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006409 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006410 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006411
Douglas Gregor1e249f82009-02-25 22:18:32 +00006412 // C++ [temp.expl.spec]p9:
6413 // A template explicit specialization is in the scope of the
6414 // namespace in which the template was defined.
6415 //
6416 // We actually implement this paragraph where we set the semantic
6417 // context (in the creation of the ClassTemplateSpecializationDecl),
6418 // but we also maintain the lexical context where the actual
6419 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00006420 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00006421
Douglas Gregor67a65642009-02-17 23:15:12 +00006422 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006423 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00006424 Specialization->startDefinition();
6425
Douglas Gregor2208a292009-09-26 20:57:03 +00006426 if (TUK == TUK_Friend) {
6427 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6428 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00006429 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00006430 /*FIXME:*/KWLoc);
6431 Friend->setAccess(AS_public);
6432 CurContext->addDecl(Friend);
6433 } else {
6434 // Add the specialization into its lexical context, so that it can
6435 // be seen when iterating through the list of declarations in that
6436 // context. However, specializations are not found by name lookup.
6437 CurContext->addDecl(Specialization);
6438 }
John McCall48871652010-08-21 09:40:31 +00006439 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00006440}
Douglas Gregor333489b2009-03-27 23:10:48 +00006441
John McCall48871652010-08-21 09:40:31 +00006442Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006443 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00006444 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006445 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00006446 ActOnDocumentableDecl(NewDecl);
6447 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006448}
6449
John McCall48871652010-08-21 09:40:31 +00006450Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00006451 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00006452 Declarator &D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006453 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006454 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Mike Stump11289f42009-09-09 15:08:12 +00006455
Douglas Gregor17a7c122009-06-24 00:54:41 +00006456 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00006457 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00006458 }
Mike Stump11289f42009-09-09 15:08:12 +00006459
Douglas Gregor17a7c122009-06-24 00:54:41 +00006460 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00006461
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006462 D.setFunctionDefinitionKind(FDK_Definition);
John McCall48871652010-08-21 09:40:31 +00006463 Decl *DP = HandleDeclarator(ParentScope, D,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006464 TemplateParameterLists);
Argyrios Kyrtzidis6fada2d2012-12-14 06:53:58 +00006465 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Douglas Gregor17a7c122009-06-24 00:54:41 +00006466}
6467
John McCall4f7ced62010-02-11 01:33:53 +00006468/// \brief Strips various properties off an implicit instantiation
6469/// that has just been explicitly specialized.
6470static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00006471 D->dropAttr<DLLImportAttr>();
6472 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00006473
Nico Webere4974382014-12-19 23:52:45 +00006474 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00006475 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00006476}
6477
Nico Webera8f80b32012-01-09 19:52:25 +00006478/// \brief Compute the diagnostic location for an explicit instantiation
6479// declaration or definition.
6480static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006481 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00006482 // Explicit instantiations following a specialization have no effect and
6483 // hence no PointOfInstantiation. In that case, walk decl backwards
6484 // until a valid name loc is found.
6485 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006486 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
6487 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00006488 PrevDiagLoc = Prev->getLocation();
6489 }
6490 assert(PrevDiagLoc.isValid() &&
6491 "Explicit instantiation without point of instantiation?");
6492 return PrevDiagLoc;
6493}
6494
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006495/// \brief Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006496/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006497/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006498/// new specialization/instantiation will have any effect.
6499///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006500/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006501/// instantiation.
6502///
6503/// \param NewTSK the kind of the new explicit specialization or instantiation.
6504///
6505/// \param PrevDecl the previous declaration of the entity.
6506///
6507/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
6508///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006509/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006510/// declaration was instantiated (either implicitly or explicitly).
6511///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006512/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006513/// specialization or instantiation has no effect and should be ignored.
6514///
6515/// \returns true if there was an error that should prevent the introduction of
6516/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00006517bool
6518Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6519 TemplateSpecializationKind NewTSK,
6520 NamedDecl *PrevDecl,
6521 TemplateSpecializationKind PrevTSK,
6522 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00006523 bool &HasNoEffect) {
6524 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006525
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006526 switch (NewTSK) {
6527 case TSK_Undeclared:
6528 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00006529 assert(
6530 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
6531 "previous declaration must be implicit!");
6532 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006533
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006534 case TSK_ExplicitSpecialization:
6535 switch (PrevTSK) {
6536 case TSK_Undeclared:
6537 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006538 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006539 // explicitly specialized or has merely been mentioned without any
6540 // instantiation.
6541 return false;
6542
6543 case TSK_ImplicitInstantiation:
6544 if (PrevPointOfInstantiation.isInvalid()) {
6545 // The declaration itself has not actually been instantiated, so it is
6546 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00006547 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006548 return false;
6549 }
6550 // Fall through
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006551
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006552 case TSK_ExplicitInstantiationDeclaration:
6553 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006554 assert((PrevTSK == TSK_ImplicitInstantiation ||
6555 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006556 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006557
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006558 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006559 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006560 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006561 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006562 // implicit instantiation to take place, in every translation unit in
6563 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006564 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006565 // Is there any previous explicit specialization declaration?
6566 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
6567 return false;
6568 }
6569
Douglas Gregor1d957a32009-10-27 18:42:08 +00006570 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006571 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00006572 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006573 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006574
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006575 return true;
6576 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006577
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006578 case TSK_ExplicitInstantiationDeclaration:
6579 switch (PrevTSK) {
6580 case TSK_ExplicitInstantiationDeclaration:
6581 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00006582 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006583 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006584
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006585 case TSK_Undeclared:
6586 case TSK_ImplicitInstantiation:
6587 // We're explicitly instantiating something that may have already been
6588 // implicitly instantiated; that's fine.
6589 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006590
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006591 case TSK_ExplicitSpecialization:
6592 // C++0x [temp.explicit]p4:
6593 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006594 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006595 // specialization for that template, the explicit instantiation has no
6596 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00006597 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006598 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006599
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006600 case TSK_ExplicitInstantiationDefinition:
6601 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006602 // If an entity is the subject of both an explicit instantiation
6603 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006604 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006605 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00006606 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00006607
6608 // Explicit instantiations following a specialization have no effect and
6609 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
6610 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00006611 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6612 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006613 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006614 return false;
6615 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006616
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006617 case TSK_ExplicitInstantiationDefinition:
6618 switch (PrevTSK) {
6619 case TSK_Undeclared:
6620 case TSK_ImplicitInstantiation:
6621 // We're explicitly instantiating something that may have already been
6622 // implicitly instantiated; that's fine.
6623 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006624
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006625 case TSK_ExplicitSpecialization:
6626 // C++ DR 259, C++0x [temp.explicit]p4:
6627 // For a given set of template parameters, if an explicit
6628 // instantiation of a template appears after a declaration of
6629 // an explicit specialization for that template, the explicit
6630 // instantiation has no effect.
6631 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006632 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00006633 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006634 // has been explicitly specialized.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006635 Diag(NewLoc, getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006636 diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
6637 diag::ext_explicit_instantiation_after_specialization)
6638 << PrevDecl;
6639 Diag(PrevDecl->getLocation(),
6640 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006641 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006642 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006643
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006644 case TSK_ExplicitInstantiationDeclaration:
6645 // We're explicity instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006646 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00006647
6648 // C++0x [temp.explicit]p4:
6649 // For a given set of template parameters, if an explicit instantiation
6650 // of a template appears after a declaration of an explicit
6651 // specialization for that template, the explicit instantiation has no
6652 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006653 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00006654 // Is there any previous explicit specialization declaration?
6655 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6656 HasNoEffect = true;
6657 break;
6658 }
6659 }
6660
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006661 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006662
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006663 case TSK_ExplicitInstantiationDefinition:
6664 // C++0x [temp.spec]p5:
6665 // For a given template and a given set of template-arguments,
6666 // - an explicit instantiation definition shall appear at most once
6667 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006668
6669 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
6670 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00006671 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006672 : diag::err_explicit_instantiation_duplicate)
6673 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00006674 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00006675 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006676 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006677 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006678 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006679 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006680
David Blaikie83d382b2011-09-23 05:06:16 +00006681 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006682}
6683
John McCallb9c78482010-04-08 09:05:18 +00006684/// \brief Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00006685/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00006686///
James Dennettf14a6e52012-06-15 22:23:43 +00006687/// The only possible way to get a dependent function template specialization
6688/// is with a friend declaration, like so:
6689///
6690/// \code
6691/// template \<class T> void foo(T);
6692/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00006693/// friend void foo<>(T);
6694/// };
James Dennettf14a6e52012-06-15 22:23:43 +00006695/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00006696///
6697/// There really isn't any useful analysis we can do here, so we
6698/// just store the information.
6699bool
6700Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6701 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6702 LookupResult &Previous) {
6703 // Remove anything from Previous that isn't a function template in
6704 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00006705 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00006706 LookupResult::Filter F = Previous.makeFilter();
6707 while (F.hasNext()) {
6708 NamedDecl *D = F.next()->getUnderlyingDecl();
6709 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00006710 !FDLookupContext->InEnclosingNamespaceSetOf(
6711 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00006712 F.erase();
6713 }
6714 F.done();
6715
6716 // Should this be diagnosed here?
6717 if (Previous.empty()) return true;
6718
6719 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
6720 ExplicitTemplateArgs);
6721 return false;
6722}
6723
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006724/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006725/// specialization.
6726///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006727/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006728/// explicit function template specialization. On successful completion,
6729/// the function declaration \p FD will become a function template
6730/// specialization.
6731///
6732/// \param FD the function declaration, which will be updated to become a
6733/// function template specialization.
6734///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006735/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
6736/// if any. Note that this may be valid info even when 0 arguments are
6737/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
6738/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006739///
Francois Pichet3a44e432011-07-08 06:21:47 +00006740/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006741/// this function specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006742bool Sema::CheckFunctionTemplateSpecialization(
6743 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
6744 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006745 // The set of function template specializations that could match this
6746 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00006747 UnresolvedSet<8> Candidates;
Larisse Voufo98b20f12013-07-19 23:00:19 +00006748 TemplateSpecCandidateSet FailedCandidates(FD->getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006749
Sebastian Redl50c68252010-08-31 00:36:30 +00006750 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00006751 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6752 I != E; ++I) {
6753 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
6754 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006755 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006756 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00006757 if (!FDLookupContext->InEnclosingNamespaceSetOf(
6758 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006759 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006760
Richard Smith574f4f62013-01-14 05:37:29 +00006761 // When matching a constexpr member function template specialization
6762 // against the primary template, we don't yet know whether the
6763 // specialization has an implicit 'const' (because we don't know whether
6764 // it will be a static member function until we know which template it
6765 // specializes), so adjust it now assuming it specializes this template.
6766 QualType FT = FD->getType();
6767 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00006768 CXXMethodDecl *OldMD =
6769 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00006770 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00006771 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00006772 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6773 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00006774 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00006775 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00006776 }
6777 }
6778
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006779 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006780 // A trailing template-argument can be left unspecified in the
6781 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006782 // provided it can be deduced from the function argument type.
6783 // Perform template argument deduction to determine whether we may be
6784 // specializing this template.
6785 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00006786 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006787 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00006788 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
6789 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
6790 ExplicitTemplateArgs, FT, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00006791 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006792 // that we can provide nifty diagnostics.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006793 FailedCandidates.addCandidate()
6794 .set(FunTmpl->getTemplatedDecl(),
6795 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006796 (void)TDK;
6797 continue;
6798 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006799
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006800 // Record this candidate.
John McCall58cc69d2010-01-27 01:50:18 +00006801 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006802 }
6803 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006804
Douglas Gregor5de279c2009-09-26 03:41:46 +00006805 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006806 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00006807 Candidates.begin(), Candidates.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00006808 FD->getLocation(),
6809 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
6810 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00006811 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00006812 PDiag(diag::note_function_template_spec_matched));
6813
John McCall58cc69d2010-01-27 01:50:18 +00006814 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006815 return true;
John McCall58cc69d2010-01-27 01:50:18 +00006816
6817 // Ignore access information; it doesn't figure into redeclaration checking.
6818 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00006819
6820 FunctionTemplateSpecializationInfo *SpecInfo
6821 = Specialization->getTemplateSpecializationInfo();
6822 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00006823
6824 // Note: do not overwrite location info if previous template
6825 // specialization kind was explicit.
6826 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00006827 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00006828 Specialization->setLocation(FD->getLocation());
Richard Smith5b8b3db2012-02-20 23:28:05 +00006829 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
6830 // function can differ from the template declaration with respect to
6831 // the constexpr specifier.
6832 Specialization->setConstexpr(FD->isConstexpr());
6833 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006834
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006835 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00006836 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00006837
6838 // If this is a friend declaration, then we're not really declaring
6839 // an explicit specialization.
6840 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006841
Douglas Gregor54888652009-10-07 00:13:32 +00006842 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00006843 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006844 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00006845 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006846 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006847 false))
Douglas Gregor54888652009-10-07 00:13:32 +00006848 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00006849
6850 // C++ [temp.expl.spec]p6:
6851 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006852 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006853 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006854 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006855 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00006856 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00006857 if (!isFriend &&
6858 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00006859 TSK_ExplicitSpecialization,
6860 Specialization,
6861 SpecInfo->getTemplateSpecializationKind(),
6862 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00006863 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00006864 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00006865
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006866 // Mark the prior declaration as an explicit specialization, so that later
6867 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006868 if (!isFriend) {
John McCall816d75b2010-03-24 07:46:06 +00006869 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006870 MarkUnusedFileScopedDecl(Specialization);
6871 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006872
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006873 // Turn the given function declaration into a function template
6874 // specialization, with the template arguments from the previous
6875 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006876 // Take copies of (semantic and syntactic) template argument lists.
6877 const TemplateArgumentList* TemplArgs = new (Context)
6878 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Douglas Gregord5058122010-02-11 01:19:42 +00006879 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006880 TemplArgs, /*InsertPos=*/nullptr,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006881 SpecInfo->getTemplateSpecializationKind(),
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00006882 ExplicitTemplateArgs);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006883
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006884 // The "previous declaration" for this function template specialization is
6885 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00006886 Previous.clear();
6887 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006888 return false;
6889}
6890
Douglas Gregor86d142a2009-10-08 07:24:58 +00006891/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006892/// specialization.
6893///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006894/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006895/// explicit member function specialization. On successful completion,
6896/// the function declaration \p FD will become a member function
6897/// specialization.
6898///
Douglas Gregor86d142a2009-10-08 07:24:58 +00006899/// \param Member the member declaration, which will be updated to become a
6900/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006901///
John McCall1f82f242009-11-18 22:49:29 +00006902/// \param Previous the set of declarations, one of which may be specialized
6903/// by this function specialization; the set will be modified to contain the
6904/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006905bool
John McCall1f82f242009-11-18 22:49:29 +00006906Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00006907 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00006908
Douglas Gregor86d142a2009-10-08 07:24:58 +00006909 // Try to find the member we are instantiating.
Craig Topperc3ec1492014-05-26 06:22:03 +00006910 NamedDecl *Instantiation = nullptr;
6911 NamedDecl *InstantiatedFrom = nullptr;
6912 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00006913
John McCall1f82f242009-11-18 22:49:29 +00006914 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00006915 // Nowhere to look anyway.
6916 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00006917 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6918 I != E; ++I) {
6919 NamedDecl *D = (*I)->getUnderlyingDecl();
6920 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00006921 QualType Adjusted = Function->getType();
6922 if (!hasExplicitCallingConv(Adjusted))
6923 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
6924 if (Context.hasSameType(Adjusted, Method->getType())) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00006925 Instantiation = Method;
6926 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00006927 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00006928 break;
6929 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006930 }
6931 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00006932 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00006933 VarDecl *PrevVar;
6934 if (Previous.isSingleResult() &&
6935 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00006936 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00006937 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00006938 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00006939 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00006940 }
6941 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00006942 CXXRecordDecl *PrevRecord;
6943 if (Previous.isSingleResult() &&
6944 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
6945 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00006946 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00006947 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00006948 }
Richard Smith7d137e32012-03-23 03:33:32 +00006949 } else if (isa<EnumDecl>(Member)) {
6950 EnumDecl *PrevEnum;
6951 if (Previous.isSingleResult() &&
6952 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
6953 Instantiation = PrevEnum;
6954 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
6955 MSInfo = PrevEnum->getMemberSpecializationInfo();
6956 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006957 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006958
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006959 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00006960 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006961 // specializations are always out-of-line, the caller will complain about
6962 // this mismatch later.
6963 return false;
6964 }
John McCalle820e5e2010-04-13 20:37:33 +00006965
6966 // If this is a friend, just bail out here before we start turning
6967 // things into explicit specializations.
6968 if (Member->getFriendObjectKind() != Decl::FOK_None) {
6969 // Preserve instantiation information.
6970 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
6971 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
6972 cast<CXXMethodDecl>(InstantiatedFrom),
6973 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
6974 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
6975 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
6976 cast<CXXRecordDecl>(InstantiatedFrom),
6977 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
6978 }
6979
6980 Previous.clear();
6981 Previous.addDecl(Instantiation);
6982 return false;
6983 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006984
Douglas Gregor86d142a2009-10-08 07:24:58 +00006985 // Make sure that this is a specialization of a member.
6986 if (!InstantiatedFrom) {
6987 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
6988 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006989 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
6990 return true;
6991 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006992
Douglas Gregor06db9f52009-10-12 20:18:28 +00006993 // C++ [temp.expl.spec]p6:
6994 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00006995 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006996 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006997 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006998 // use occurs; no diagnostic is required.
6999 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00007000
Abramo Bagnara8075c852010-06-12 07:44:57 +00007001 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00007002 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
7003 TSK_ExplicitSpecialization,
7004 Instantiation,
7005 MSInfo->getTemplateSpecializationKind(),
7006 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007007 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007008 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007009
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007010 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007011 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00007012 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007013 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007014 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007015 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00007016
Douglas Gregor86d142a2009-10-08 07:24:58 +00007017 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007018 // the original declaration to note that it is an explicit specialization
7019 // (if it was previously an implicit instantiation). This latter step
7020 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00007021 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007022 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
7023 if (InstantiationFunction->getTemplateSpecializationKind() ==
7024 TSK_ImplicitInstantiation) {
7025 InstantiationFunction->setTemplateSpecializationKind(
7026 TSK_ExplicitSpecialization);
7027 InstantiationFunction->setLocation(Member->getLocation());
7028 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007029
Douglas Gregor86d142a2009-10-08 07:24:58 +00007030 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
7031 cast<CXXMethodDecl>(InstantiatedFrom),
7032 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007033 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007034 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007035 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
7036 if (InstantiationVar->getTemplateSpecializationKind() ==
7037 TSK_ImplicitInstantiation) {
7038 InstantiationVar->setTemplateSpecializationKind(
7039 TSK_ExplicitSpecialization);
7040 InstantiationVar->setLocation(Member->getLocation());
7041 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007042
Larisse Voufo39a1e502013-08-06 01:03:05 +00007043 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
7044 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007045 MarkUnusedFileScopedDecl(InstantiationVar);
Richard Smith7d137e32012-03-23 03:33:32 +00007046 } else if (isa<CXXRecordDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007047 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
7048 if (InstantiationClass->getTemplateSpecializationKind() ==
7049 TSK_ImplicitInstantiation) {
7050 InstantiationClass->setTemplateSpecializationKind(
7051 TSK_ExplicitSpecialization);
7052 InstantiationClass->setLocation(Member->getLocation());
7053 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007054
Douglas Gregor86d142a2009-10-08 07:24:58 +00007055 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007056 cast<CXXRecordDecl>(InstantiatedFrom),
7057 TSK_ExplicitSpecialization);
Richard Smith7d137e32012-03-23 03:33:32 +00007058 } else {
7059 assert(isa<EnumDecl>(Member) && "Only member enums remain");
7060 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
7061 if (InstantiationEnum->getTemplateSpecializationKind() ==
7062 TSK_ImplicitInstantiation) {
7063 InstantiationEnum->setTemplateSpecializationKind(
7064 TSK_ExplicitSpecialization);
7065 InstantiationEnum->setLocation(Member->getLocation());
7066 }
7067
7068 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
7069 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007070 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007071
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007072 // Save the caller the trouble of having to figure out which declaration
7073 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00007074 Previous.clear();
7075 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007076 return false;
7077}
7078
Douglas Gregore47f5a72009-10-14 23:41:34 +00007079/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007080///
7081/// \returns true if a serious error occurs, false otherwise.
7082static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00007083 SourceLocation InstLoc,
7084 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00007085 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
7086 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007087
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007088 if (CurContext->isRecord()) {
7089 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
7090 << D;
7091 return true;
7092 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007093
Richard Smith050d2612011-10-18 02:28:33 +00007094 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007095 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00007096 // template. If the name declared in the explicit instantiation is an
7097 // unqualified name, the explicit instantiation shall appear in the
7098 // namespace where its template is declared or, if that namespace is inline
7099 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007100 //
7101 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00007102 if (WasQualifiedName) {
7103 if (CurContext->Encloses(OrigContext))
7104 return false;
7105 } else {
7106 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
7107 return false;
7108 }
7109
7110 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
7111 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007112 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007113 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007114 diag::err_explicit_instantiation_out_of_scope :
7115 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007116 << D << NS;
7117 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007118 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007119 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007120 diag::err_explicit_instantiation_unqualified_wrong_namespace :
7121 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
7122 << D << NS;
7123 } else
7124 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007125 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007126 diag::err_explicit_instantiation_must_be_global :
7127 diag::warn_explicit_instantiation_must_be_global_0x)
7128 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007129 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007130 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007131}
7132
7133/// \brief Determine whether the given scope specifier has a template-id in it.
7134static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
7135 if (!SS.isSet())
7136 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007137
Richard Smith050d2612011-10-18 02:28:33 +00007138 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007139 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007140 // or a static data member of a class template specialization, the name of
7141 // the class template specialization in the qualified-id for the member
7142 // name shall be a simple-template-id.
7143 //
7144 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00007145 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
7146 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00007147 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00007148 if (isa<TemplateSpecializationType>(T))
7149 return true;
7150
7151 return false;
7152}
7153
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007154// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00007155DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007156Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007157 SourceLocation ExternLoc,
7158 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007159 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00007160 SourceLocation KWLoc,
7161 const CXXScopeSpec &SS,
7162 TemplateTy TemplateD,
7163 SourceLocation TemplateNameLoc,
7164 SourceLocation LAngleLoc,
7165 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00007166 SourceLocation RAngleLoc,
7167 AttributeList *Attr) {
7168 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00007169 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00007170 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00007171 // Check that the specialization uses the same tag kind as the
7172 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007173 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7174 assert(Kind != TTK_Enum &&
7175 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00007176
7177 if (isa<TypeAliasTemplateDecl>(TD)) {
7178 Diag(KWLoc, diag::err_tag_reference_non_tag) << Kind;
7179 Diag(TD->getTemplatedDecl()->getLocation(),
7180 diag::note_previous_use);
7181 return true;
7182 }
7183
7184 ClassTemplateDecl *ClassTemplate = cast<ClassTemplateDecl>(TD);
7185
Douglas Gregord9034f02009-05-14 16:41:31 +00007186 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007187 Kind, /*isDefinition*/false, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00007188 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007189 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00007190 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007191 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007192 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007193 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00007194 diag::note_previous_use);
7195 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7196 }
7197
Douglas Gregore47f5a72009-10-14 23:41:34 +00007198 // C++0x [temp.explicit]p2:
7199 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007200 // definition and an explicit instantiation declaration. An explicit
7201 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00007202 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
7203 ? TSK_ExplicitInstantiationDefinition
7204 : TSK_ExplicitInstantiationDeclaration;
7205
7206 if (TSK == TSK_ExplicitInstantiationDeclaration) {
7207 // Check for dllexport class template instantiation declarations.
7208 for (AttributeList *A = Attr; A; A = A->getNext()) {
7209 if (A->getKind() == AttributeList::AT_DLLExport) {
7210 Diag(ExternLoc,
7211 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7212 Diag(A->getLoc(), diag::note_attribute);
7213 break;
7214 }
7215 }
7216
7217 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
7218 Diag(ExternLoc,
7219 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7220 Diag(A->getLocation(), diag::note_attribute);
7221 }
7222 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007223
Douglas Gregora1f49972009-05-13 00:25:59 +00007224 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00007225 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00007226 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00007227
7228 // Check that the template argument list is well-formed for this
7229 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007230 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007231 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7232 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00007233 return true;
7234
Douglas Gregora1f49972009-05-13 00:25:59 +00007235 // Find the class template specialization declaration that
7236 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00007237 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007238 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00007239 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00007240
Abramo Bagnara8075c852010-06-12 07:44:57 +00007241 TemplateSpecializationKind PrevDecl_TSK
7242 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
7243
Douglas Gregor54888652009-10-07 00:13:32 +00007244 // C++0x [temp.explicit]p2:
7245 // [...] An explicit instantiation shall appear in an enclosing
7246 // namespace of its template. [...]
7247 //
7248 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007249 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
7250 SS.isSet()))
7251 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007252
Craig Topperc3ec1492014-05-26 06:22:03 +00007253 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007254
Abramo Bagnara8075c852010-06-12 07:44:57 +00007255 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00007256 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00007257 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007258 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00007259 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007260 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00007261 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00007262
Abramo Bagnara8075c852010-06-12 07:44:57 +00007263 // Even though HasNoEffect == true means that this explicit instantiation
7264 // has no effect on semantics, we go on to put its syntax in the AST.
7265
7266 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
7267 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007268 // Since the only prior class template specialization with these
7269 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00007270 // declaration node as our own, updating the source location
7271 // for the template name to reflect our new declaration.
7272 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007273 Specialization = PrevDecl;
7274 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007275 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007276 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00007277 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00007278
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007279 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00007280 // Create a new class template specialization declaration node for
7281 // this explicit specialization.
7282 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007283 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00007284 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007285 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007286 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00007287 Converted.data(),
7288 Converted.size(),
7289 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00007290 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00007291
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007292 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007293 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007294 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007295 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007296 }
7297
7298 // Build the fully-sugared type for this explicit instantiation as
7299 // the user wrote in the explicit instantiation itself. This means
7300 // that we'll pretty-print the type retrieved from the
7301 // specialization's declaration the way that the user actually wrote
7302 // the explicit instantiation, rather than formatting the name based
7303 // on the "canonical" representation used to store the template
7304 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007305 TypeSourceInfo *WrittenTy
7306 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7307 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00007308 Context.getTypeDeclType(Specialization));
7309 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00007310
Abramo Bagnara8075c852010-06-12 07:44:57 +00007311 // Set source locations for keywords.
7312 Specialization->setExternLoc(ExternLoc);
7313 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidis40bcfd72013-04-22 23:23:42 +00007314 Specialization->setRBraceLoc(SourceLocation());
Abramo Bagnara8075c852010-06-12 07:44:57 +00007315
Rafael Espindola0b062072012-01-03 06:04:21 +00007316 if (Attr)
7317 ProcessDeclAttributeList(S, Specialization, Attr);
7318
Abramo Bagnara8075c852010-06-12 07:44:57 +00007319 // Add the explicit instantiation into its lexical context. However,
7320 // since explicit instantiations are never found by name lookup, we
7321 // just put it into the declaration context directly.
7322 Specialization->setLexicalDeclContext(CurContext);
7323 CurContext->addDecl(Specialization);
7324
7325 // Syntax is now OK, so return if it has no other effect on semantics.
7326 if (HasNoEffect) {
7327 // Set the template specialization kind.
7328 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00007329 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00007330 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007331
7332 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00007333 // A definition of a class template or class member template
7334 // shall be in scope at the point of the explicit instantiation of
7335 // the class template or class member template.
7336 //
7337 // This check comes when we actually try to perform the
7338 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00007339 ClassTemplateSpecializationDecl *Def
7340 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007341 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007342 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00007343 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007344 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007345 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007346 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
7347 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007348
Douglas Gregor1d957a32009-10-27 18:42:08 +00007349 // Instantiate the members of this class template specialization.
7350 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007351 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00007352 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007353 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
7354
7355 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
7356 // TSK_ExplicitInstantiationDefinition
7357 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborg17f9b442015-05-27 00:06:45 +00007358 TSK == TSK_ExplicitInstantiationDefinition) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00007359 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007360 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007361
Hans Wennborgc0875502015-06-09 00:39:05 +00007362 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
7363 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7364 // In the MS ABI, an explicit instantiation definition can add a dll
7365 // attribute to a template with a previous instantiation declaration.
7366 // MinGW doesn't allow this.
Hans Wennborg17f9b442015-05-27 00:06:45 +00007367 auto *A = cast<InheritableAttr>(
7368 getDLLAttr(Specialization)->clone(getASTContext()));
7369 A->setInherited(true);
7370 Def->addAttr(A);
7371 checkClassLevelDLLAttribute(Def);
Hans Wennborgfce87ca2015-06-09 00:39:09 +00007372
7373 // Propagate attribute to base class templates.
7374 for (auto &B : Def->bases()) {
7375 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
7376 B.getType()->getAsCXXRecordDecl()))
7377 propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
7378 }
Hans Wennborg17f9b442015-05-27 00:06:45 +00007379 }
7380 }
7381
Douglas Gregor12e49d32009-10-15 22:53:21 +00007382 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007383 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007384
Abramo Bagnara8075c852010-06-12 07:44:57 +00007385 // Set the template specialization kind.
7386 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00007387 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00007388}
7389
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007390// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00007391DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007392Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007393 SourceLocation ExternLoc,
7394 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007395 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007396 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007397 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007398 IdentifierInfo *Name,
7399 SourceLocation NameLoc,
7400 AttributeList *Attr) {
7401
Douglas Gregord6ab8742009-05-28 23:31:59 +00007402 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00007403 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00007404 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00007405 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00007406 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007407 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00007408 SourceLocation(), false, TypeResult(),
7409 /*IsTypeSpecifier*/false);
John McCall7f41d982009-09-11 04:59:25 +00007410 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
7411
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007412 if (!TagD)
7413 return true;
7414
John McCall48871652010-08-21 09:40:31 +00007415 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00007416 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007417
Douglas Gregorb8006faf2009-05-27 17:30:49 +00007418 if (Tag->isInvalidDecl())
7419 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007420
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007421 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
7422 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
7423 if (!Pattern) {
7424 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
7425 << Context.getTypeDeclType(Record);
7426 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
7427 return true;
7428 }
7429
Douglas Gregore47f5a72009-10-14 23:41:34 +00007430 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007431 // If the explicit instantiation is for a class or member class, the
7432 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00007433 // simple-template-id.
7434 //
7435 // C++98 has the same restriction, just worded differently.
7436 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00007437 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007438 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007439
Douglas Gregore47f5a72009-10-14 23:41:34 +00007440 // C++0x [temp.explicit]p2:
7441 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007442 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00007443 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00007444 TemplateSpecializationKind TSK
7445 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7446 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007447
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007448 // C++0x [temp.explicit]p2:
7449 // [...] An explicit instantiation shall appear in an enclosing
7450 // namespace of its template. [...]
7451 //
7452 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007453 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007454
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007455 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007456 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00007457 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007458 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00007459 PrevDecl = Record;
7460 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007461 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007462 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007463 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007464 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007465 PrevDecl,
7466 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007467 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007468 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007469 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00007470 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007471 return TagD;
7472 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007473
Douglas Gregor12e49d32009-10-15 22:53:21 +00007474 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007475 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007476 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00007477 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007478 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00007479 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007480 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007481 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00007482 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00007483 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
7484 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00007485 Diag(Pattern->getLocation(), diag::note_forward_declaration)
7486 << Pattern;
7487 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007488 } else {
7489 if (InstantiateClass(NameLoc, Record, Def,
7490 getTemplateInstantiationArgs(Record),
7491 TSK))
7492 return true;
7493
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007494 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00007495 if (!RecordDef)
7496 return true;
7497 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007498 }
7499
Douglas Gregor1d957a32009-10-27 18:42:08 +00007500 // Instantiate all of the members of the class.
7501 InstantiateClassMembers(NameLoc, RecordDef,
7502 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007503
Douglas Gregor88d292c2010-05-13 16:44:06 +00007504 if (TSK == TSK_ExplicitInstantiationDefinition)
7505 MarkVTableUsed(NameLoc, RecordDef, true);
7506
Mike Stump87c57ac2009-05-16 07:39:55 +00007507 // FIXME: We don't have any representation for explicit instantiations of
7508 // member classes. Such a representation is not needed for compilation, but it
7509 // should be available for clients that want to see all of the declarations in
7510 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007511 return TagD;
7512}
7513
John McCallfaf5fb42010-08-26 23:41:50 +00007514DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
7515 SourceLocation ExternLoc,
7516 SourceLocation TemplateLoc,
7517 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007518 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007519 // TODO: check if/when DNInfo should replace Name.
7520 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7521 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00007522 if (!Name) {
7523 if (!D.isInvalidType())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007524 Diag(D.getDeclSpec().getLocStart(),
Douglas Gregor450f00842009-09-25 18:43:00 +00007525 diag::err_explicit_instantiation_requires_name)
7526 << D.getDeclSpec().getSourceRange()
7527 << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007528
Douglas Gregor450f00842009-09-25 18:43:00 +00007529 return true;
7530 }
7531
7532 // The scope passed in may not be a decl scope. Zip up the scope tree until
7533 // we find one that is.
7534 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7535 (S->getFlags() & Scope::TemplateParamScope) != 0)
7536 S = S->getParent();
7537
7538 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00007539 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
7540 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00007541 if (R.isNull())
7542 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007543
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007544 // C++ [dcl.stc]p1:
7545 // A storage-class-specifier shall not be specified in [...] an explicit
7546 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00007547 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007548 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
7549 << Name;
7550 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007551 } else if (D.getDeclSpec().getStorageClassSpec()
7552 != DeclSpec::SCS_unspecified) {
7553 // Complain about then remove the storage class specifier.
7554 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
7555 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7556
7557 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00007558 }
7559
Douglas Gregor3c74d412009-10-14 20:14:33 +00007560 // C++0x [temp.explicit]p1:
7561 // [...] An explicit instantiation of a function template shall not use the
7562 // inline or constexpr specifiers.
7563 // Presumably, this also applies to member functions of class templates as
7564 // well.
Richard Smith83c19292011-10-18 03:44:03 +00007565 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007566 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007567 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00007568 diag::err_explicit_instantiation_inline :
7569 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00007570 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00007571 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00007572 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
7573 // not already specified.
7574 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7575 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007576
Douglas Gregore47f5a72009-10-14 23:41:34 +00007577 // C++0x [temp.explicit]p2:
7578 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007579 // definition and an explicit instantiation declaration. An explicit
7580 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00007581 TemplateSpecializationKind TSK
7582 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7583 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007584
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007585 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00007586 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00007587
7588 if (!R->isFunctionType()) {
7589 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007590 // A [...] static data member of a class template can be explicitly
7591 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00007592 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007593 // C++1y [temp.explicit]p1:
7594 // A [...] variable [...] template specialization can be explicitly
7595 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00007596 if (Previous.isAmbiguous())
7597 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007598
John McCall67c00872009-12-02 08:25:40 +00007599 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00007600 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007601
Larisse Voufo39a1e502013-08-06 01:03:05 +00007602 if (!PrevTemplate) {
7603 if (!Prev || !Prev->isStaticDataMember()) {
7604 // We expect to see a data data member here.
7605 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
7606 << Name;
7607 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7608 P != PEnd; ++P)
7609 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
7610 return true;
7611 }
7612
7613 if (!Prev->getInstantiatedFromStaticDataMember()) {
7614 // FIXME: Check for explicit specialization?
7615 Diag(D.getIdentifierLoc(),
7616 diag::err_explicit_instantiation_data_member_not_instantiated)
7617 << Prev;
7618 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
7619 // FIXME: Can we provide a note showing where this was declared?
7620 return true;
7621 }
7622 } else {
7623 // Explicitly instantiate a variable template.
7624
7625 // C++1y [dcl.spec.auto]p6:
7626 // ... A program that uses auto or decltype(auto) in a context not
7627 // explicitly allowed in this section is ill-formed.
7628 //
7629 // This includes auto-typed variable template instantiations.
7630 if (R->isUndeducedType()) {
7631 Diag(T->getTypeLoc().getLocStart(),
7632 diag::err_auto_not_allowed_var_inst);
7633 return true;
7634 }
7635
Richard Smithef985ac2013-09-18 02:10:12 +00007636 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7637 // C++1y [temp.explicit]p3:
7638 // If the explicit instantiation is for a variable, the unqualified-id
7639 // in the declaration shall be a template-id.
7640 Diag(D.getIdentifierLoc(),
7641 diag::err_explicit_instantiation_without_template_id)
7642 << PrevTemplate;
7643 Diag(PrevTemplate->getLocation(),
7644 diag::note_explicit_instantiation_here);
7645 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007646 }
7647
Richard Smithef985ac2013-09-18 02:10:12 +00007648 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00007649 TemplateArgumentListInfo TemplateArgs =
7650 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00007651
Larisse Voufo39a1e502013-08-06 01:03:05 +00007652 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
7653 D.getIdentifierLoc(), TemplateArgs);
7654 if (Res.isInvalid())
7655 return true;
7656
7657 // Ignore access control bits, we don't need them for redeclaration
7658 // checking.
7659 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00007660 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007661
Douglas Gregore47f5a72009-10-14 23:41:34 +00007662 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007663 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007664 // or a static data member of a class template specialization, the name of
7665 // the class template specialization in the qualified-id for the member
7666 // name shall be a simple-template-id.
7667 //
7668 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007669 //
Richard Smith5977d872013-09-18 21:55:14 +00007670 // This does not apply to variable template specializations, where the
7671 // template-id is in the unqualified-id instead.
7672 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007673 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00007674 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007675 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007676
Douglas Gregore47f5a72009-10-14 23:41:34 +00007677 // Check the scope of this explicit instantiation.
7678 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007679
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007680 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00007681 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
7682 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007683 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007684 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00007685 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007686 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007687
Larisse Voufo39a1e502013-08-06 01:03:05 +00007688 if (!HasNoEffect) {
7689 // Instantiate static data member or variable template.
7690
7691 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7692 if (PrevTemplate) {
7693 // Merge attributes.
7694 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
7695 ProcessDeclAttributeList(S, Prev, Attr);
7696 }
7697 if (TSK == TSK_ExplicitInstantiationDefinition)
7698 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
7699 }
7700
7701 // Check the new variable specialization against the parsed input.
7702 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
7703 Diag(T->getTypeLoc().getLocStart(),
7704 diag::err_invalid_var_template_spec_type)
7705 << 0 << PrevTemplate << R << Prev->getType();
7706 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
7707 << 2 << PrevTemplate->getDeclName();
7708 return true;
7709 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007710
Douglas Gregor450f00842009-09-25 18:43:00 +00007711 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00007712 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007713 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007714
7715 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00007716 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00007717 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00007718 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00007719 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00007720 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00007721 HasExplicitTemplateArgs = true;
7722 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007723
Douglas Gregor450f00842009-09-25 18:43:00 +00007724 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007725 // A [...] function [...] can be explicitly instantiated from its template.
7726 // A member function [...] of a class template can be explicitly
7727 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00007728 // template.
John McCall58cc69d2010-01-27 01:50:18 +00007729 UnresolvedSet<8> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00007730 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00007731 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7732 P != PEnd; ++P) {
7733 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00007734 if (!HasExplicitTemplateArgs) {
7735 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00007736 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType());
7737 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
Douglas Gregord90fd522009-09-25 21:45:23 +00007738 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00007739
John McCall58cc69d2010-01-27 01:50:18 +00007740 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00007741 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
7742 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00007743 }
Douglas Gregor450f00842009-09-25 18:43:00 +00007744 }
7745 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007746
Douglas Gregor450f00842009-09-25 18:43:00 +00007747 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
7748 if (!FunTmpl)
7749 continue;
7750
Larisse Voufo98b20f12013-07-19 23:00:19 +00007751 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00007752 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007753 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007754 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00007755 (HasExplicitTemplateArgs ? &TemplateArgs
7756 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00007757 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00007758 // Keep track of almost-matches.
7759 FailedCandidates.addCandidate()
7760 .set(FunTmpl->getTemplatedDecl(),
7761 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00007762 (void)TDK;
7763 continue;
7764 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007765
John McCall58cc69d2010-01-27 01:50:18 +00007766 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00007767 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007768
Douglas Gregor450f00842009-09-25 18:43:00 +00007769 // Find the most specialized function template specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007770 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00007771 Matches.begin(), Matches.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00007772 D.getIdentifierLoc(),
7773 PDiag(diag::err_explicit_instantiation_not_known) << Name,
7774 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
7775 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00007776
John McCall58cc69d2010-01-27 01:50:18 +00007777 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00007778 return true;
John McCall58cc69d2010-01-27 01:50:18 +00007779
7780 // Ignore access control bits, we don't need them for redeclaration checking.
7781 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007782
Alexey Bataev73983912014-11-06 10:10:50 +00007783 // C++11 [except.spec]p4
7784 // In an explicit instantiation an exception-specification may be specified,
7785 // but is not required.
7786 // If an exception-specification is specified in an explicit instantiation
7787 // directive, it shall be compatible with the exception-specifications of
7788 // other declarations of that function.
7789 if (auto *FPT = R->getAs<FunctionProtoType>())
7790 if (FPT->hasExceptionSpec()) {
7791 unsigned DiagID =
7792 diag::err_mismatched_exception_spec_explicit_instantiation;
7793 if (getLangOpts().MicrosoftExt)
7794 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
7795 bool Result = CheckEquivalentExceptionSpec(
7796 PDiag(DiagID) << Specialization->getType(),
7797 PDiag(diag::note_explicit_instantiation_here),
7798 Specialization->getType()->getAs<FunctionProtoType>(),
7799 Specialization->getLocation(), FPT, D.getLocStart());
7800 // In Microsoft mode, mismatching exception specifications just cause a
7801 // warning.
7802 if (!getLangOpts().MicrosoftExt && Result)
7803 return true;
7804 }
7805
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007806 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007807 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00007808 diag::err_explicit_instantiation_member_function_not_instantiated)
7809 << Specialization
7810 << (Specialization->getTemplateSpecializationKind() ==
7811 TSK_ExplicitSpecialization);
7812 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
7813 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007814 }
7815
Douglas Gregorec9fd132012-01-14 16:38:05 +00007816 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00007817 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
7818 PrevDecl = Specialization;
7819
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007820 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007821 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007822 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007823 PrevDecl,
7824 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007825 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007826 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007827 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007828
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007829 // FIXME: We may still want to build some representation of this
7830 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007831 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00007832 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007833 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00007834
7835 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Rafael Espindola2aa7acf2012-01-04 05:40:59 +00007836 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
7837 if (Attr)
7838 ProcessDeclAttributeList(S, Specialization, Attr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007839
Richard Smitheb36ddf2014-04-24 22:45:46 +00007840 if (Specialization->isDefined()) {
7841 // Let the ASTConsumer know that this function has been explicitly
7842 // instantiated now, and its linkage might have changed.
7843 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
7844 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00007845 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007846
Douglas Gregore47f5a72009-10-14 23:41:34 +00007847 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007848 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007849 // or a static data member of a class template specialization, the name of
7850 // the class template specialization in the qualified-id for the member
7851 // name shall be a simple-template-id.
7852 //
7853 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007854 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00007855 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007856 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00007857 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007858 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00007859 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007860 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007861
Douglas Gregore47f5a72009-10-14 23:41:34 +00007862 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007863 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregore47f5a72009-10-14 23:41:34 +00007864 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007865 D.getIdentifierLoc(),
Douglas Gregore47f5a72009-10-14 23:41:34 +00007866 D.getCXXScopeSpec().isSet());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007867
Douglas Gregor450f00842009-09-25 18:43:00 +00007868 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00007869 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007870}
7871
John McCallfaf5fb42010-08-26 23:41:50 +00007872TypeResult
John McCall7f41d982009-09-11 04:59:25 +00007873Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
7874 const CXXScopeSpec &SS, IdentifierInfo *Name,
7875 SourceLocation TagLoc, SourceLocation NameLoc) {
7876 // This has to hold, because SS is expected to be defined.
7877 assert(Name && "Expected a name in a dependent tag");
7878
Aaron Ballman4a979672014-01-03 13:56:08 +00007879 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00007880 if (!NNS)
7881 return true;
7882
Abramo Bagnara6150c882010-05-11 21:36:43 +00007883 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00007884
Douglas Gregorba41d012010-04-24 16:38:41 +00007885 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
7886 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00007887 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00007888 return true;
7889 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00007890
Douglas Gregore7c20652011-03-02 00:47:37 +00007891 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007892 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00007893 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
7894
7895 // Create type-source location information for this type.
7896 TypeLocBuilder TLB;
7897 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00007898 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00007899 TL.setQualifierLoc(SS.getWithLocInContext(Context));
7900 TL.setNameLoc(NameLoc);
7901 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00007902}
7903
John McCallfaf5fb42010-08-26 23:41:50 +00007904TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007905Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7906 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00007907 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007908 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00007909 return true;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007910
Richard Smith0bf8a4922011-10-18 20:49:44 +00007911 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
7912 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007913 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00007914 diag::warn_cxx98_compat_typename_outside_of_template :
7915 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007916 << FixItHint::CreateRemoval(TypenameLoc);
7917
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00007918 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00007919 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
7920 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00007921 if (T.isNull())
7922 return true;
John McCall99b2fe52010-04-29 23:50:39 +00007923
7924 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7925 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00007926 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00007927 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00007928 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00007929 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00007930 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00007931 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00007932 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00007933 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00007934 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00007935 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007936
John McCallba7bf592010-08-24 05:47:05 +00007937 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00007938}
7939
John McCallfaf5fb42010-08-26 23:41:50 +00007940TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007941Sema::ActOnTypenameType(Scope *S,
7942 SourceLocation TypenameLoc,
7943 const CXXScopeSpec &SS,
7944 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00007945 TemplateTy TemplateIn,
7946 SourceLocation TemplateNameLoc,
7947 SourceLocation LAngleLoc,
7948 ASTTemplateArgsPtr TemplateArgsIn,
7949 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00007950 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
7951 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007952 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00007953 diag::warn_cxx98_compat_typename_outside_of_template :
7954 diag::ext_typename_outside_of_template)
7955 << FixItHint::CreateRemoval(TypenameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007956
7957 // Translate the parser's template argument list in our AST format.
7958 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
7959 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
7960
7961 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007962 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
7963 // Construct a dependent template specialization type.
7964 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00007965 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007966 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
7967 DTN->getQualifier(),
7968 DTN->getIdentifier(),
7969 TemplateArgs);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007970
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007971 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00007972 TypeLocBuilder Builder;
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007973 DependentTemplateSpecializationTypeLoc SpecTL
7974 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007975 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
7976 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00007977 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007978 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007979 SpecTL.setLAngleLoc(LAngleLoc);
7980 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007981 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7982 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007983 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00007984 }
Douglas Gregorb09518c2011-02-27 22:46:49 +00007985
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007986 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
7987 if (T.isNull())
7988 return true;
Douglas Gregorb09518c2011-02-27 22:46:49 +00007989
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007990 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00007991 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007992 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007993 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007994 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
7995 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007996 SpecTL.setLAngleLoc(LAngleLoc);
7997 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007998 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7999 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
8000
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008001 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
8002 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008003 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008004 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8005
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008006 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
8007 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00008008}
8009
Douglas Gregorb09518c2011-02-27 22:46:49 +00008010
Richard Smith6f8d2c62012-05-09 05:17:00 +00008011/// Determine whether this failed name lookup should be treated as being
8012/// disabled by a usage of std::enable_if.
8013static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
8014 SourceRange &CondRange) {
8015 // We must be looking for a ::type...
8016 if (!II.isStr("type"))
8017 return false;
8018
8019 // ... within an explicitly-written template specialization...
8020 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
8021 return false;
8022 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00008023 TemplateSpecializationTypeLoc EnableIfTSTLoc =
8024 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
8025 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00008026 return false;
8027 const TemplateSpecializationType *EnableIfTST =
David Blaikie6adc78e2013-02-18 22:06:02 +00008028 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
Richard Smith6f8d2c62012-05-09 05:17:00 +00008029
8030 // ... which names a complete class template declaration...
8031 const TemplateDecl *EnableIfDecl =
8032 EnableIfTST->getTemplateName().getAsTemplateDecl();
8033 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
8034 return false;
8035
8036 // ... called "enable_if".
8037 const IdentifierInfo *EnableIfII =
8038 EnableIfDecl->getDeclName().getAsIdentifierInfo();
8039 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
8040 return false;
8041
8042 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00008043 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Richard Smith6f8d2c62012-05-09 05:17:00 +00008044 return true;
8045}
8046
Douglas Gregor333489b2009-03-27 23:10:48 +00008047/// \brief Build the type that describes a C++ typename specifier,
8048/// e.g., "typename T::type".
8049QualType
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008050Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
8051 SourceLocation KeywordLoc,
8052 NestedNameSpecifierLoc QualifierLoc,
8053 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00008054 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00008055 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008056 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00008057
John McCall0b66eb32010-05-01 00:40:08 +00008058 DeclContext *Ctx = computeDeclContext(SS);
8059 if (!Ctx) {
8060 // If the nested-name-specifier is dependent and couldn't be
8061 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008062 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
8063 return Context.getDependentNameType(Keyword,
8064 QualifierLoc.getNestedNameSpecifier(),
8065 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008066 }
Douglas Gregor333489b2009-03-27 23:10:48 +00008067
John McCall0b66eb32010-05-01 00:40:08 +00008068 // If the nested-name-specifier refers to the current instantiation,
8069 // the "typename" keyword itself is superfluous. In C++03, the
8070 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
8071 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00008072 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008073
John McCall0b66eb32010-05-01 00:40:08 +00008074 if (RequireCompleteDeclContext(SS, Ctx))
8075 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00008076
8077 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00008078 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00008079 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00008080 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00008081 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00008082 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00008083 case LookupResult::NotFound: {
8084 // If we're looking up 'type' within a template named 'enable_if', produce
8085 // a more specific diagnostic.
8086 SourceRange CondRange;
8087 if (isEnableIf(QualifierLoc, II, CondRange)) {
8088 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
8089 << Ctx << CondRange;
8090 return QualType();
8091 }
8092
Douglas Gregore40876a2009-10-13 21:16:44 +00008093 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00008094 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008095 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008096
8097 case LookupResult::FoundUnresolvedValue: {
8098 // We found a using declaration that is a value. Most likely, the using
8099 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008100 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008101 IILoc);
8102 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
8103 << Name << Ctx << FullRange;
8104 if (UnresolvedUsingValueDecl *Using
8105 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008106 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008107 Diag(Loc, diag::note_using_value_decl_missing_typename)
8108 << FixItHint::CreateInsertion(Loc, "typename ");
8109 }
8110 }
8111 // Fall through to create a dependent typename type, from which we can recover
8112 // better.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008113
Douglas Gregord0d2ee02010-01-15 01:44:47 +00008114 case LookupResult::NotFoundInCurrentInstantiation:
8115 // Okay, it's a member of an unknown instantiation.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008116 return Context.getDependentNameType(Keyword,
8117 QualifierLoc.getNestedNameSpecifier(),
8118 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00008119
8120 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008121 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00008122 // We found a type. Build an ElaboratedType, since the
8123 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00008124 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008125 return Context.getElaboratedType(ETK_Typename,
8126 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00008127 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00008128 }
8129
8130 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00008131 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00008132 break;
8133
8134 case LookupResult::FoundOverloaded:
8135 DiagID = diag::err_typename_nested_not_type;
8136 Referenced = *Result.begin();
8137 break;
8138
John McCall6538c932009-10-10 05:48:19 +00008139 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00008140 return QualType();
8141 }
8142
8143 // If we get here, it's because name lookup did not find a
8144 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008145 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00008146 IILoc);
8147 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00008148 if (Referenced)
8149 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
8150 << Name;
8151 return QualType();
8152}
Douglas Gregor15acfb92009-08-06 16:20:37 +00008153
8154namespace {
8155 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00008156 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00008157 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00008158 SourceLocation Loc;
8159 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00008160
Douglas Gregor15acfb92009-08-06 16:20:37 +00008161 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00008162 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008163
Mike Stump11289f42009-09-09 15:08:12 +00008164 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008165 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00008166 DeclarationName Entity)
8167 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00008168 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00008169
8170 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00008171 /// transformed.
8172 ///
8173 /// For the purposes of type reconstruction, a type has already been
8174 /// transformed if it is NULL or if it is not dependent.
8175 bool AlreadyTransformed(QualType T) {
8176 return T.isNull() || !T->isDependentType();
8177 }
Mike Stump11289f42009-09-09 15:08:12 +00008178
8179 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00008180 /// rebuilt.
8181 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00008182
Douglas Gregor15acfb92009-08-06 16:20:37 +00008183 /// \brief Returns the name of the entity whose type is being rebuilt.
8184 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00008185
Douglas Gregoref6ab412009-10-27 06:26:26 +00008186 /// \brief Sets the "base" location and entity when that
8187 /// information is known based on another transformation.
8188 void setBase(SourceLocation Loc, DeclarationName Entity) {
8189 this->Loc = Loc;
8190 this->Entity = Entity;
8191 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00008192
8193 ExprResult TransformLambdaExpr(LambdaExpr *E) {
8194 // Lambdas never need to be transformed.
8195 return E;
8196 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00008197 };
8198}
8199
Douglas Gregor15acfb92009-08-06 16:20:37 +00008200/// \brief Rebuilds a type within the context of the current instantiation.
8201///
Mike Stump11289f42009-09-09 15:08:12 +00008202/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00008203/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00008204/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00008205/// partial specialization thereof). This routine will rebuild that type now
8206/// that we have entered the declarator's scope, which may produce different
8207/// canonical types, e.g.,
8208///
8209/// \code
8210/// template<typename T>
8211/// struct X {
8212/// typedef T* pointer;
8213/// pointer data();
8214/// };
8215///
8216/// template<typename T>
8217/// typename X<T>::pointer X<T>::data() { ... }
8218/// \endcode
8219///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00008220/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008221/// since we do not know that we can look into X<T> when we parsed the type.
8222/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00008223/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00008224/// as the canonical type of T*, allowing the return types of the out-of-line
8225/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00008226TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8227 SourceLocation Loc,
8228 DeclarationName Name) {
8229 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00008230 return T;
Mike Stump11289f42009-09-09 15:08:12 +00008231
Douglas Gregor15acfb92009-08-06 16:20:37 +00008232 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
8233 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00008234}
Douglas Gregorbe999392009-09-15 16:23:51 +00008235
John McCalldadc5752010-08-24 06:29:42 +00008236ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00008237 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
8238 DeclarationName());
8239 return Rebuilder.TransformExpr(E);
8240}
8241
John McCall99b2fe52010-04-29 23:50:39 +00008242bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Douglas Gregor10176412011-02-25 16:07:42 +00008243 if (SS.isInvalid())
8244 return true;
John McCall2408e322010-04-27 00:57:59 +00008245
Douglas Gregor10176412011-02-25 16:07:42 +00008246 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00008247 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
8248 DeclarationName());
Douglas Gregor10176412011-02-25 16:07:42 +00008249 NestedNameSpecifierLoc Rebuilt
8250 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
8251 if (!Rebuilt)
8252 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008253
Douglas Gregor10176412011-02-25 16:07:42 +00008254 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00008255 return false;
John McCall2408e322010-04-27 00:57:59 +00008256}
8257
Douglas Gregor041b0842011-10-14 15:31:12 +00008258/// \brief Rebuild the template parameters now that we know we're in a current
8259/// instantiation.
8260bool Sema::RebuildTemplateParamsInCurrentInstantiation(
8261 TemplateParameterList *Params) {
8262 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8263 Decl *Param = Params->getParam(I);
8264
8265 // There is nothing to rebuild in a type parameter.
8266 if (isa<TemplateTypeParmDecl>(Param))
8267 continue;
8268
8269 // Rebuild the template parameter list of a template template parameter.
8270 if (TemplateTemplateParmDecl *TTP
8271 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
8272 if (RebuildTemplateParamsInCurrentInstantiation(
8273 TTP->getTemplateParameters()))
8274 return true;
8275
8276 continue;
8277 }
8278
8279 // Rebuild the type of a non-type template parameter.
8280 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
8281 TypeSourceInfo *NewTSI
8282 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
8283 NTTP->getLocation(),
8284 NTTP->getDeclName());
8285 if (!NewTSI)
8286 return true;
8287
8288 if (NewTSI != NTTP->getTypeSourceInfo()) {
8289 NTTP->setTypeSourceInfo(NewTSI);
8290 NTTP->setType(NewTSI->getType());
8291 }
8292 }
8293
8294 return false;
8295}
8296
Douglas Gregorbe999392009-09-15 16:23:51 +00008297/// \brief Produces a formatted string that describes the binding of
8298/// template parameters to template arguments.
8299std::string
8300Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8301 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008302 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00008303}
8304
8305std::string
8306Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8307 const TemplateArgument *Args,
8308 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008309 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +00008310 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +00008311
Douglas Gregore62e6a02009-11-11 19:13:48 +00008312 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008313 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008314
Douglas Gregorbe999392009-09-15 16:23:51 +00008315 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00008316 if (I >= NumArgs)
8317 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008318
Douglas Gregorbe999392009-09-15 16:23:51 +00008319 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008320 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +00008321 else
Douglas Gregor0192c232010-12-20 16:52:59 +00008322 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008323
Douglas Gregorbe999392009-09-15 16:23:51 +00008324 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +00008325 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +00008326 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +00008327 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +00008328 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008329
Douglas Gregor0192c232010-12-20 16:52:59 +00008330 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +00008331 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +00008332 }
Douglas Gregor0192c232010-12-20 16:52:59 +00008333
8334 Out << ']';
8335 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +00008336}
Francois Pichet1c229c02011-04-22 22:18:13 +00008337
Richard Smithe40f2ba2013-08-07 21:41:30 +00008338void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
8339 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +00008340 if (!FD)
8341 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +00008342
8343 LateParsedTemplate *LPT = new LateParsedTemplate;
8344
8345 // Take tokens to avoid allocations
8346 LPT->Toks.swap(Toks);
8347 LPT->D = FnD;
Chandler Carruth52cee4d2015-03-26 09:08:15 +00008348 LateParsedTemplateMap.insert(std::make_pair(FD, LPT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008349
8350 FD->setLateTemplateParsed(true);
8351}
8352
8353void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
8354 if (!FD)
8355 return;
8356 FD->setLateTemplateParsed(false);
8357}
Francois Pichet1c229c02011-04-22 22:18:13 +00008358
8359bool Sema::IsInsideALocalClassWithinATemplateFunction() {
8360 DeclContext *DC = CurContext;
8361
8362 while (DC) {
8363 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
8364 const FunctionDecl *FD = RD->isLocalClass();
8365 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
8366 } else if (DC->isTranslationUnit() || DC->isNamespace())
8367 return false;
8368
8369 DC = DC->getParent();
8370 }
8371 return false;
8372}