blob: 8bfcde609201e773437c9ac0cfe42dda795a3b39 [file] [log] [blame]
Douglas Gregor72c3f312008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor72c3f312008-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 Gregor99ebf652009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregor99ebf652009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +000011
John McCall2d887082010-08-25 22:03:47 +000012#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000013#include "clang/Sema/Lookup.h"
John McCall5f1e0942010-08-24 08:50:51 +000014#include "clang/Sema/Scope.h"
John McCall7cd088e2010-08-24 07:21:54 +000015#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000016#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor4a959d82009-08-06 16:20:37 +000017#include "TreeTransform.h"
Douglas Gregorddc29e12009-02-06 22:42:48 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor898574e2008-12-05 23:32:09 +000019#include "clang/AST/Expr.h"
Douglas Gregorcc45cb32009-02-11 19:52:55 +000020#include "clang/AST/ExprCXX.h"
John McCall92b7f702010-03-11 07:50:04 +000021#include "clang/AST/DeclFriend.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000022#include "clang/AST/DeclTemplate.h"
John McCall4e2cbb22010-10-20 05:44:58 +000023#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor5f3aeb62010-10-13 00:27:52 +000024#include "clang/AST/TypeVisitor.h"
John McCall19510852010-08-20 18:27:03 +000025#include "clang/Sema/DeclSpec.h"
26#include "clang/Sema/ParsedTemplate.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000027#include "clang/Basic/LangOptions.h"
Douglas Gregord5a423b2009-09-25 18:43:00 +000028#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbf4ea562009-09-15 16:23:51 +000029#include "llvm/ADT/StringExtras.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000030using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000031using namespace sema;
Douglas Gregor72c3f312008-12-05 18:15:24 +000032
John McCall78b81052010-11-10 02:40:36 +000033// Exported for use by Parser.
34SourceRange
35clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
36 unsigned N) {
37 if (!N) return SourceRange();
38 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
39}
40
Douglas Gregor2dd078a2009-09-02 22:59:36 +000041/// \brief Determine whether the declaration found is acceptable as the name
42/// of a template and, if so, return that template declaration. Otherwise,
43/// returns NULL.
John McCallad00b772010-06-16 08:42:20 +000044static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
45 NamedDecl *Orig) {
46 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000047
Douglas Gregor2dd078a2009-09-02 22:59:36 +000048 if (isa<TemplateDecl>(D))
John McCallad00b772010-06-16 08:42:20 +000049 return Orig;
Mike Stump1eb44332009-09-09 15:08:12 +000050
Douglas Gregor2dd078a2009-09-02 22:59:36 +000051 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
52 // C++ [temp.local]p1:
53 // Like normal (non-template) classes, class templates have an
54 // injected-class-name (Clause 9). The injected-class-name
55 // can be used with or without a template-argument-list. When
56 // it is used without a template-argument-list, it is
57 // equivalent to the injected-class-name followed by the
58 // template-parameters of the class template enclosed in
59 // <>. When it is used with a template-argument-list, it
60 // refers to the specified class template specialization,
61 // which could be the current specialization or another
62 // specialization.
63 if (Record->isInjectedClassName()) {
Douglas Gregor542b5482009-10-14 17:30:58 +000064 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregor2dd078a2009-09-02 22:59:36 +000065 if (Record->getDescribedClassTemplate())
66 return Record->getDescribedClassTemplate();
67
68 if (ClassTemplateSpecializationDecl *Spec
69 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
70 return Spec->getSpecializedTemplate();
71 }
Mike Stump1eb44332009-09-09 15:08:12 +000072
Douglas Gregor2dd078a2009-09-02 22:59:36 +000073 return 0;
74 }
Mike Stump1eb44332009-09-09 15:08:12 +000075
Douglas Gregor2dd078a2009-09-02 22:59:36 +000076 return 0;
77}
78
Douglas Gregor312eadb2011-04-24 05:37:28 +000079void Sema::FilterAcceptableTemplateNames(LookupResult &R) {
Douglas Gregor01e56ae2010-04-12 20:54:26 +000080 // The set of class templates we've already seen.
81 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCallf7a1a742009-11-24 19:00:30 +000082 LookupResult::Filter filter = R.makeFilter();
83 while (filter.hasNext()) {
84 NamedDecl *Orig = filter.next();
Douglas Gregor312eadb2011-04-24 05:37:28 +000085 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig);
John McCallf7a1a742009-11-24 19:00:30 +000086 if (!Repl)
87 filter.erase();
Douglas Gregor01e56ae2010-04-12 20:54:26 +000088 else if (Repl != Orig) {
89
90 // C++ [temp.local]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000091 // A lookup that finds an injected-class-name (10.2) can result in an
Douglas Gregor01e56ae2010-04-12 20:54:26 +000092 // ambiguity in certain cases (for example, if it is found in more than
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000093 // one base class). If all of the injected-class-names that are found
94 // refer to specializations of the same class template, and if the name
Richard Smith3e4c6c42011-05-05 21:57:07 +000095 // is used as a template-name, the reference refers to the class
96 // template itself and not a specialization thereof, and is not
Douglas Gregor01e56ae2010-04-12 20:54:26 +000097 // ambiguous.
Douglas Gregor01e56ae2010-04-12 20:54:26 +000098 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
99 if (!ClassTemplates.insert(ClassTmpl)) {
100 filter.erase();
101 continue;
102 }
John McCall8ba66912010-08-13 07:02:08 +0000103
104 // FIXME: we promote access to public here as a workaround to
105 // the fact that LookupResult doesn't let us remember that we
106 // found this template through a particular injected class name,
107 // which means we end up doing nasty things to the invariants.
108 // Pretending that access is public is *much* safer.
109 filter.replace(Repl, AS_public);
Douglas Gregor01e56ae2010-04-12 20:54:26 +0000110 }
John McCallf7a1a742009-11-24 19:00:30 +0000111 }
112 filter.done();
113}
114
Douglas Gregor312eadb2011-04-24 05:37:28 +0000115bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R) {
116 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
117 if (isAcceptableTemplateName(Context, *I))
118 return true;
119
Douglas Gregor3b887352011-04-27 04:48:22 +0000120 return false;
Douglas Gregor312eadb2011-04-24 05:37:28 +0000121}
122
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000123TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000124 CXXScopeSpec &SS,
Abramo Bagnara7c153532010-08-06 12:11:11 +0000125 bool hasTemplateKeyword,
Douglas Gregor014e88d2009-11-03 23:16:33 +0000126 UnqualifiedId &Name,
John McCallb3d87482010-08-24 05:47:05 +0000127 ParsedType ObjectTypePtr,
Douglas Gregor495c35d2009-08-25 22:51:20 +0000128 bool EnteringContext,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000129 TemplateTy &TemplateResult,
130 bool &MemberOfUnknownSpecialization) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000131 assert(getLangOptions().CPlusPlus && "No template names in C!");
132
Douglas Gregor014e88d2009-11-03 23:16:33 +0000133 DeclarationName TName;
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000134 MemberOfUnknownSpecialization = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000135
Douglas Gregor014e88d2009-11-03 23:16:33 +0000136 switch (Name.getKind()) {
137 case UnqualifiedId::IK_Identifier:
138 TName = DeclarationName(Name.Identifier);
139 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000140
Douglas Gregor014e88d2009-11-03 23:16:33 +0000141 case UnqualifiedId::IK_OperatorFunctionId:
142 TName = Context.DeclarationNames.getCXXOperatorName(
143 Name.OperatorFunctionId.Operator);
144 break;
145
Sean Hunte6252d12009-11-28 08:58:14 +0000146 case UnqualifiedId::IK_LiteralOperatorId:
Sean Hunt3e518bd2009-11-29 07:34:05 +0000147 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
148 break;
Sean Hunte6252d12009-11-28 08:58:14 +0000149
Douglas Gregor014e88d2009-11-03 23:16:33 +0000150 default:
151 return TNK_Non_template;
152 }
Mike Stump1eb44332009-09-09 15:08:12 +0000153
John McCallb3d87482010-08-24 05:47:05 +0000154 QualType ObjectType = ObjectTypePtr.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000155
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000156 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
Douglas Gregorbfea2392009-12-31 08:11:17 +0000157 LookupOrdinaryName);
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000158 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
159 MemberOfUnknownSpecialization);
John McCall67d22fb2010-08-28 20:17:00 +0000160 if (R.empty()) return TNK_Non_template;
161 if (R.isAmbiguous()) {
162 // Suppress diagnostics; we'll redo this lookup later.
John McCallb8592062010-08-13 02:23:42 +0000163 R.suppressDiagnostics();
John McCall67d22fb2010-08-28 20:17:00 +0000164
165 // FIXME: we might have ambiguous templates, in which case we
166 // should at least parse them properly!
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000167 return TNK_Non_template;
John McCallb8592062010-08-13 02:23:42 +0000168 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000169
John McCall0bd6feb2009-12-02 08:04:21 +0000170 TemplateName Template;
171 TemplateNameKind TemplateKind;
Mike Stump1eb44332009-09-09 15:08:12 +0000172
John McCall0bd6feb2009-12-02 08:04:21 +0000173 unsigned ResultCount = R.end() - R.begin();
174 if (ResultCount > 1) {
175 // We assume that we'll preserve the qualifier from a function
176 // template name in other ways.
177 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
178 TemplateKind = TNK_Function_template;
John McCallb8592062010-08-13 02:23:42 +0000179
180 // We'll do this lookup again later.
181 R.suppressDiagnostics();
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000182 } else {
John McCall0bd6feb2009-12-02 08:04:21 +0000183 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
184
185 if (SS.isSet() && !SS.isInvalid()) {
186 NestedNameSpecifier *Qualifier
187 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Abramo Bagnara7c153532010-08-06 12:11:11 +0000188 Template = Context.getQualifiedTemplateName(Qualifier,
189 hasTemplateKeyword, TD);
John McCall0bd6feb2009-12-02 08:04:21 +0000190 } else {
191 Template = TemplateName(TD);
192 }
193
John McCallb8592062010-08-13 02:23:42 +0000194 if (isa<FunctionTemplateDecl>(TD)) {
John McCall0bd6feb2009-12-02 08:04:21 +0000195 TemplateKind = TNK_Function_template;
John McCallb8592062010-08-13 02:23:42 +0000196
197 // We'll do this lookup again later.
198 R.suppressDiagnostics();
199 } else {
Richard Smith3e4c6c42011-05-05 21:57:07 +0000200 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
201 isa<TypeAliasTemplateDecl>(TD));
John McCall0bd6feb2009-12-02 08:04:21 +0000202 TemplateKind = TNK_Type_template;
203 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000204 }
Mike Stump1eb44332009-09-09 15:08:12 +0000205
John McCall0bd6feb2009-12-02 08:04:21 +0000206 TemplateResult = TemplateTy::make(Template);
207 return TemplateKind;
John McCallf7a1a742009-11-24 19:00:30 +0000208}
209
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000210bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
Douglas Gregor84d0a192010-01-12 21:28:44 +0000211 SourceLocation IILoc,
212 Scope *S,
213 const CXXScopeSpec *SS,
214 TemplateTy &SuggestedTemplate,
215 TemplateNameKind &SuggestedKind) {
216 // We can't recover unless there's a dependent scope specifier preceding the
217 // template name.
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000218 // FIXME: Typo correction?
Douglas Gregor84d0a192010-01-12 21:28:44 +0000219 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
220 computeDeclContext(*SS))
221 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000222
Douglas Gregor84d0a192010-01-12 21:28:44 +0000223 // The code is missing a 'template' keyword prior to the dependent template
224 // name.
225 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
226 Diag(IILoc, diag::err_template_kw_missing)
227 << Qualifier << II.getName()
Douglas Gregor849b2432010-03-31 17:46:05 +0000228 << FixItHint::CreateInsertion(IILoc, "template ");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000229 SuggestedTemplate
Douglas Gregor84d0a192010-01-12 21:28:44 +0000230 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
231 SuggestedKind = TNK_Dependent_template_name;
232 return true;
233}
234
John McCallf7a1a742009-11-24 19:00:30 +0000235void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000236 Scope *S, CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +0000237 QualType ObjectType,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000238 bool EnteringContext,
239 bool &MemberOfUnknownSpecialization) {
John McCallf7a1a742009-11-24 19:00:30 +0000240 // Determine where to perform name lookup
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000241 MemberOfUnknownSpecialization = false;
John McCallf7a1a742009-11-24 19:00:30 +0000242 DeclContext *LookupCtx = 0;
243 bool isDependent = false;
244 if (!ObjectType.isNull()) {
245 // This nested-name-specifier occurs in a member access expression, e.g.,
246 // x->B::f, and we are looking into the type of the object.
247 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
248 LookupCtx = computeDeclContext(ObjectType);
249 isDependent = ObjectType->isDependentType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000250 assert((isDependent || !ObjectType->isIncompleteType()) &&
John McCallf7a1a742009-11-24 19:00:30 +0000251 "Caller should have completed object type");
252 } else if (SS.isSet()) {
253 // This nested-name-specifier occurs after another nested-name-specifier,
254 // so long into the context associated with the prior nested-name-specifier.
255 LookupCtx = computeDeclContext(SS, EnteringContext);
256 isDependent = isDependentScopeSpecifier(SS);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000257
John McCallf7a1a742009-11-24 19:00:30 +0000258 // The declaration context must be complete.
John McCall77bb1aa2010-05-01 00:40:08 +0000259 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCallf7a1a742009-11-24 19:00:30 +0000260 return;
261 }
262
263 bool ObjectTypeSearchedInScope = false;
264 if (LookupCtx) {
265 // Perform "qualified" name lookup into the declaration context we
266 // computed, which is either the type of the base of a member access
267 // expression or the declaration context associated with a prior
268 // nested-name-specifier.
269 LookupQualifiedName(Found, LookupCtx);
270
271 if (!ObjectType.isNull() && Found.empty()) {
272 // C++ [basic.lookup.classref]p1:
273 // In a class member access expression (5.2.5), if the . or -> token is
274 // immediately followed by an identifier followed by a <, the
275 // identifier must be looked up to determine whether the < is the
276 // beginning of a template argument list (14.2) or a less-than operator.
277 // The identifier is first looked up in the class of the object
278 // expression. If the identifier is not found, it is then looked up in
279 // the context of the entire postfix-expression and shall name a class
280 // or function template.
John McCallf7a1a742009-11-24 19:00:30 +0000281 if (S) LookupName(Found, S);
282 ObjectTypeSearchedInScope = true;
283 }
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000284 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregor2e933882010-01-12 17:06:20 +0000285 // We cannot look into a dependent object type or nested nme
286 // specifier.
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000287 MemberOfUnknownSpecialization = true;
John McCallf7a1a742009-11-24 19:00:30 +0000288 return;
289 } else {
290 // Perform unqualified name lookup in the current scope.
291 LookupName(Found, S);
292 }
293
Douglas Gregor2e933882010-01-12 17:06:20 +0000294 if (Found.empty() && !isDependent) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000295 // If we did not find any names, attempt to correct any typos.
296 DeclarationName Name = Found.getLookupName();
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000297 Found.clear();
298 if (TypoCorrection Corrected = CorrectTypo(Found.getLookupNameInfo(),
299 Found.getLookupKind(), S, &SS,
300 LookupCtx, false,
301 CTC_CXXCasts)) {
302 Found.setLookupName(Corrected.getCorrection());
303 if (Corrected.getCorrectionDecl())
304 Found.addDecl(Corrected.getCorrectionDecl());
Douglas Gregor312eadb2011-04-24 05:37:28 +0000305 FilterAcceptableTemplateNames(Found);
John McCallad00b772010-06-16 08:42:20 +0000306 if (!Found.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000307 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
308 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
Douglas Gregorbfea2392009-12-31 08:11:17 +0000309 if (LookupCtx)
310 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000311 << Name << LookupCtx << CorrectedQuotedStr << SS.getRange()
312 << FixItHint::CreateReplacement(Found.getNameLoc(), CorrectedStr);
Douglas Gregorbfea2392009-12-31 08:11:17 +0000313 else
314 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000315 << Name << CorrectedQuotedStr
316 << FixItHint::CreateReplacement(Found.getNameLoc(), CorrectedStr);
Douglas Gregor67dd1d42010-01-07 00:17:44 +0000317 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
318 Diag(Template->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000319 << CorrectedQuotedStr;
John McCallad00b772010-06-16 08:42:20 +0000320 }
Douglas Gregorbfea2392009-12-31 08:11:17 +0000321 } else {
Douglas Gregor12eb5d62010-06-29 19:27:42 +0000322 Found.setLookupName(Name);
Douglas Gregorbfea2392009-12-31 08:11:17 +0000323 }
324 }
325
Douglas Gregor312eadb2011-04-24 05:37:28 +0000326 FilterAcceptableTemplateNames(Found);
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000327 if (Found.empty()) {
328 if (isDependent)
329 MemberOfUnknownSpecialization = true;
John McCallf7a1a742009-11-24 19:00:30 +0000330 return;
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000331 }
John McCallf7a1a742009-11-24 19:00:30 +0000332
333 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
334 // C++ [basic.lookup.classref]p1:
335 // [...] If the lookup in the class of the object expression finds a
336 // template, the name is also looked up in the context of the entire
337 // postfix-expression and [...]
338 //
339 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
340 LookupOrdinaryName);
341 LookupName(FoundOuter, S);
Douglas Gregor312eadb2011-04-24 05:37:28 +0000342 FilterAcceptableTemplateNames(FoundOuter);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000343
John McCallf7a1a742009-11-24 19:00:30 +0000344 if (FoundOuter.empty()) {
345 // - if the name is not found, the name found in the class of the
346 // object expression is used, otherwise
Douglas Gregora6d1e762011-08-10 21:59:45 +0000347 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
348 FoundOuter.isAmbiguous()) {
John McCallf7a1a742009-11-24 19:00:30 +0000349 // - if the name is found in the context of the entire
350 // postfix-expression and does not name a class template, the name
351 // found in the class of the object expression is used, otherwise
Douglas Gregora6d1e762011-08-10 21:59:45 +0000352 FoundOuter.clear();
John McCallad00b772010-06-16 08:42:20 +0000353 } else if (!Found.isSuppressingDiagnostics()) {
John McCallf7a1a742009-11-24 19:00:30 +0000354 // - if the name found is a class template, it must refer to the same
355 // entity as the one found in the class of the object expression,
356 // otherwise the program is ill-formed.
357 if (!Found.isSingleResult() ||
358 Found.getFoundDecl()->getCanonicalDecl()
359 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000360 Diag(Found.getNameLoc(),
Jeffrey Yasskin21d07e42010-06-05 01:39:57 +0000361 diag::ext_nested_name_member_ref_lookup_ambiguous)
362 << Found.getLookupName()
363 << ObjectType;
John McCallf7a1a742009-11-24 19:00:30 +0000364 Diag(Found.getRepresentativeDecl()->getLocation(),
365 diag::note_ambig_member_ref_object_type)
366 << ObjectType;
367 Diag(FoundOuter.getFoundDecl()->getLocation(),
368 diag::note_ambig_member_ref_scope);
369
370 // Recover by taking the template that we found in the object
371 // expression's type.
372 }
373 }
374 }
375}
376
John McCall2f841ba2009-12-02 03:53:29 +0000377/// ActOnDependentIdExpression - Handle a dependent id-expression that
378/// was just parsed. This is only possible with an explicit scope
379/// specifier naming a dependent type.
John McCall60d7b3a2010-08-24 06:29:42 +0000380ExprResult
John McCallf7a1a742009-11-24 19:00:30 +0000381Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +0000382 const DeclarationNameInfo &NameInfo,
John McCall2f841ba2009-12-02 03:53:29 +0000383 bool isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +0000384 const TemplateArgumentListInfo *TemplateArgs) {
John McCallea1471e2010-05-20 01:18:31 +0000385 DeclContext *DC = getFunctionLevelDeclContext();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000386
John McCall2f841ba2009-12-02 03:53:29 +0000387 if (!isAddressOfOperand &&
John McCallea1471e2010-05-20 01:18:31 +0000388 isa<CXXMethodDecl>(DC) &&
389 cast<CXXMethodDecl>(DC)->isInstance()) {
390 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000391
John McCallf7a1a742009-11-24 19:00:30 +0000392 // Since the 'this' expression is synthesized, we don't need to
393 // perform the double-lookup check.
394 NamedDecl *FirstQualifierInScope = 0;
395
John McCallaa81e162009-12-01 22:10:20 +0000396 return Owned(CXXDependentScopeMemberExpr::Create(Context,
397 /*This*/ 0, ThisType,
398 /*IsArrow*/ true,
John McCallf7a1a742009-11-24 19:00:30 +0000399 /*Op*/ SourceLocation(),
Douglas Gregor7c3179c2011-02-28 18:50:33 +0000400 SS.getWithLocInContext(Context),
John McCallf7a1a742009-11-24 19:00:30 +0000401 FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +0000402 NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000403 TemplateArgs));
404 }
405
Abramo Bagnara25777432010-08-11 22:01:17 +0000406 return BuildDependentDeclRefExpr(SS, NameInfo, TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +0000407}
408
John McCall60d7b3a2010-08-24 06:29:42 +0000409ExprResult
John McCallf7a1a742009-11-24 19:00:30 +0000410Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +0000411 const DeclarationNameInfo &NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000412 const TemplateArgumentListInfo *TemplateArgs) {
413 return Owned(DependentScopeDeclRefExpr::Create(Context,
Douglas Gregor00cf3cc2011-02-25 20:49:16 +0000414 SS.getWithLocInContext(Context),
Abramo Bagnara25777432010-08-11 22:01:17 +0000415 NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000416 TemplateArgs));
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000417}
418
Douglas Gregor72c3f312008-12-05 18:15:24 +0000419/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
420/// that the template parameter 'PrevDecl' is being shadowed by a new
421/// declaration at location Loc. Returns true to indicate that this is
422/// an error, and false otherwise.
423bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +0000424 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000425
426 // Microsoft Visual C++ permits template parameters to be shadowed.
Francois Pichet62ec1f22011-09-17 17:15:52 +0000427 if (getLangOptions().MicrosoftExt)
Douglas Gregor72c3f312008-12-05 18:15:24 +0000428 return false;
429
430 // C++ [temp.local]p4:
431 // A template-parameter shall not be redeclared within its
432 // scope (including nested scopes).
Mike Stump1eb44332009-09-09 15:08:12 +0000433 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor72c3f312008-12-05 18:15:24 +0000434 << cast<NamedDecl>(PrevDecl)->getDeclName();
435 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
436 return true;
437}
438
Douglas Gregor2943aed2009-03-03 04:44:36 +0000439/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000440/// the parameter D to reference the templated declaration and return a pointer
441/// to the template declaration. Otherwise, do nothing to D and return null.
John McCalld226f652010-08-21 09:40:31 +0000442TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
443 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
444 D = Temp->getTemplatedDecl();
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000445 return Temp;
446 }
447 return 0;
448}
449
Douglas Gregorba68eca2011-01-05 17:40:24 +0000450ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
451 SourceLocation EllipsisLoc) const {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000452 assert(Kind == Template &&
Douglas Gregorba68eca2011-01-05 17:40:24 +0000453 "Only template template arguments can be pack expansions here");
454 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
455 "Template template argument pack expansion without packs");
456 ParsedTemplateArgument Result(*this);
457 Result.EllipsisLoc = EllipsisLoc;
458 return Result;
459}
460
Douglas Gregor788cd062009-11-11 01:00:40 +0000461static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
462 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000463
Douglas Gregor788cd062009-11-11 01:00:40 +0000464 switch (Arg.getKind()) {
465 case ParsedTemplateArgument::Type: {
John McCalla93c9342009-12-07 02:54:59 +0000466 TypeSourceInfo *DI;
Douglas Gregor788cd062009-11-11 01:00:40 +0000467 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000468 if (!DI)
John McCalla93c9342009-12-07 02:54:59 +0000469 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor788cd062009-11-11 01:00:40 +0000470 return TemplateArgumentLoc(TemplateArgument(T), DI);
471 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000472
Douglas Gregor788cd062009-11-11 01:00:40 +0000473 case ParsedTemplateArgument::NonType: {
474 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
475 return TemplateArgumentLoc(TemplateArgument(E), E);
476 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000477
Douglas Gregor788cd062009-11-11 01:00:40 +0000478 case ParsedTemplateArgument::Template: {
John McCall2b5289b2010-08-23 07:28:44 +0000479 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregor2be29f42011-01-14 23:41:42 +0000480 TemplateArgument TArg;
481 if (Arg.getEllipsisLoc().isValid())
482 TArg = TemplateArgument(Template, llvm::Optional<unsigned int>());
483 else
484 TArg = Template;
485 return TemplateArgumentLoc(TArg,
Douglas Gregorb6744ef2011-03-02 17:09:35 +0000486 Arg.getScopeSpec().getWithLocInContext(
487 SemaRef.Context),
Douglas Gregorba68eca2011-01-05 17:40:24 +0000488 Arg.getLocation(),
489 Arg.getEllipsisLoc());
Douglas Gregor788cd062009-11-11 01:00:40 +0000490 }
491 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000492
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +0000493 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +0000494 return TemplateArgumentLoc();
495}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000496
Douglas Gregor788cd062009-11-11 01:00:40 +0000497/// \brief Translates template arguments as provided by the parser
498/// into template arguments used by semantic analysis.
John McCalld5532b62009-11-23 01:53:49 +0000499void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
500 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor788cd062009-11-11 01:00:40 +0000501 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCalld5532b62009-11-23 01:53:49 +0000502 TemplateArgs.addArgument(translateTemplateArgument(*this,
503 TemplateArgsIn[I]));
Douglas Gregor788cd062009-11-11 01:00:40 +0000504}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000505
Douglas Gregor72c3f312008-12-05 18:15:24 +0000506/// ActOnTypeParameter - Called when a C++ template type parameter
507/// (e.g., "typename T") has been parsed. Typename specifies whether
508/// the keyword "typename" was used to declare the type parameter
509/// (otherwise, "class" was used), and KeyLoc is the location of the
510/// "class" or "typename" keyword. ParamName is the name of the
511/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth4fb86f82011-05-01 00:51:33 +0000512/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor72c3f312008-12-05 18:15:24 +0000513/// If the type parameter has a default argument, it will be added
514/// later via ActOnTypeParameterDefault.
John McCalld226f652010-08-21 09:40:31 +0000515Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
516 SourceLocation EllipsisLoc,
517 SourceLocation KeyLoc,
518 IdentifierInfo *ParamName,
519 SourceLocation ParamNameLoc,
520 unsigned Depth, unsigned Position,
521 SourceLocation EqualLoc,
John McCallb3d87482010-08-24 05:47:05 +0000522 ParsedType DefaultArg) {
Mike Stump1eb44332009-09-09 15:08:12 +0000523 assert(S->isTemplateParamScope() &&
524 "Template type parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000525 bool Invalid = false;
526
527 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000528 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
Douglas Gregorc0b39642010-04-15 23:40:53 +0000529 LookupOrdinaryName,
530 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000531 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000532 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000533 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000534 }
535
Douglas Gregorddc29e12009-02-06 22:42:48 +0000536 SourceLocation Loc = ParamNameLoc;
537 if (!ParamName)
538 Loc = KeyLoc;
539
Douglas Gregor72c3f312008-12-05 18:15:24 +0000540 TemplateTypeParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000541 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000542 KeyLoc, Loc, Depth, Position, ParamName,
543 Typename, Ellipsis);
Douglas Gregor9a299e02011-03-04 17:52:15 +0000544 Param->setAccess(AS_public);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000545 if (Invalid)
546 Param->setInvalidDecl();
547
548 if (ParamName) {
549 // Add the template parameter into the current scope.
John McCalld226f652010-08-21 09:40:31 +0000550 S->AddDecl(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000551 IdResolver.AddDecl(Param);
552 }
553
Douglas Gregor61c4d282011-01-05 15:48:55 +0000554 // C++0x [temp.param]p9:
555 // A default template-argument may be specified for any kind of
556 // template-parameter that is not a template parameter pack.
557 if (DefaultArg && Ellipsis) {
558 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
559 DefaultArg = ParsedType();
560 }
561
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000562 // Handle the default argument, if provided.
563 if (DefaultArg) {
564 TypeSourceInfo *DefaultTInfo;
565 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000566
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000567 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000568
Douglas Gregor6f526752010-12-16 08:48:57 +0000569 // Check for unexpanded parameter packs.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000570 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6f526752010-12-16 08:48:57 +0000571 UPPC_DefaultArgument))
572 return Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000573
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000574 // Check the template argument itself.
575 if (CheckTemplateArgument(Param, DefaultTInfo)) {
576 Param->setInvalidDecl();
John McCalld226f652010-08-21 09:40:31 +0000577 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000578 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000579
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000580 Param->setDefaultArgument(DefaultTInfo, false);
581 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000582
John McCalld226f652010-08-21 09:40:31 +0000583 return Param;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000584}
585
Douglas Gregor2943aed2009-03-03 04:44:36 +0000586/// \brief Check that the type of a non-type template parameter is
587/// well-formed.
588///
589/// \returns the (possibly-promoted) parameter type if valid;
590/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump1eb44332009-09-09 15:08:12 +0000591QualType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000592Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora481ec42010-05-23 19:57:01 +0000593 // We don't allow variably-modified types as the type of non-type template
594 // parameters.
595 if (T->isVariablyModifiedType()) {
596 Diag(Loc, diag::err_variably_modified_nontype_template_param)
597 << T;
598 return QualType();
599 }
600
Douglas Gregor2943aed2009-03-03 04:44:36 +0000601 // C++ [temp.param]p4:
602 //
603 // A non-type template-parameter shall have one of the following
604 // (optionally cv-qualified) types:
605 //
606 // -- integral or enumeration type,
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000607 if (T->isIntegralOrEnumerationType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000608 // -- pointer to object or pointer to function,
Eli Friedman13578692010-08-05 02:49:48 +0000609 T->isPointerType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000610 // -- reference to object or reference to function,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000611 T->isReferenceType() ||
Douglas Gregor84ee2ee2011-05-21 23:15:46 +0000612 // -- pointer to member,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000613 T->isMemberPointerType() ||
Douglas Gregor84ee2ee2011-05-21 23:15:46 +0000614 // -- std::nullptr_t.
615 T->isNullPtrType() ||
Douglas Gregor2943aed2009-03-03 04:44:36 +0000616 // If T is a dependent type, we can't do the check now, so we
617 // assume that it is well-formed.
618 T->isDependentType())
619 return T;
620 // C++ [temp.param]p8:
621 //
622 // A non-type template-parameter of type "array of T" or
623 // "function returning T" is adjusted to be of type "pointer to
624 // T" or "pointer to function returning T", respectively.
625 else if (T->isArrayType())
626 // FIXME: Keep the type prior to promotion?
627 return Context.getArrayDecayedType(T);
628 else if (T->isFunctionType())
629 // FIXME: Keep the type prior to promotion?
630 return Context.getPointerType(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000631
Douglas Gregor2943aed2009-03-03 04:44:36 +0000632 Diag(Loc, diag::err_template_nontype_parm_bad_type)
633 << T;
634
635 return QualType();
636}
637
John McCalld226f652010-08-21 09:40:31 +0000638Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
639 unsigned Depth,
640 unsigned Position,
641 SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000642 Expr *Default) {
John McCallbf1a0282010-06-04 23:28:52 +0000643 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
644 QualType T = TInfo->getType();
Douglas Gregor72c3f312008-12-05 18:15:24 +0000645
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000646 assert(S->isTemplateParamScope() &&
647 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000648 bool Invalid = false;
649
650 IdentifierInfo *ParamName = D.getIdentifier();
651 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000652 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +0000653 LookupOrdinaryName,
654 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000655 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000656 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000657 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000658 }
659
Douglas Gregor4d2abba2010-12-16 15:36:43 +0000660 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
661 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000662 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000663 Invalid = true;
664 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000665
Douglas Gregor10738d32010-12-23 23:51:58 +0000666 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor72c3f312008-12-05 18:15:24 +0000667 NonTypeTemplateParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000668 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000669 D.getSourceRange().getBegin(),
John McCall7a9813c2010-01-22 00:28:27 +0000670 D.getIdentifierLoc(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000671 Depth, Position, ParamName, T,
Douglas Gregor10738d32010-12-23 23:51:58 +0000672 IsParameterPack, TInfo);
Douglas Gregor9a299e02011-03-04 17:52:15 +0000673 Param->setAccess(AS_public);
674
Douglas Gregor72c3f312008-12-05 18:15:24 +0000675 if (Invalid)
676 Param->setInvalidDecl();
677
678 if (D.getIdentifier()) {
679 // Add the template parameter into the current scope.
John McCalld226f652010-08-21 09:40:31 +0000680 S->AddDecl(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000681 IdResolver.AddDecl(Param);
682 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000683
Douglas Gregor61c4d282011-01-05 15:48:55 +0000684 // C++0x [temp.param]p9:
685 // A default template-argument may be specified for any kind of
686 // template-parameter that is not a template parameter pack.
687 if (Default && IsParameterPack) {
688 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
689 Default = 0;
690 }
691
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000692 // Check the well-formedness of the default template argument, if provided.
Douglas Gregor10738d32010-12-23 23:51:58 +0000693 if (Default) {
Douglas Gregor6f526752010-12-16 08:48:57 +0000694 // Check for unexpanded parameter packs.
695 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
696 return Param;
697
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000698 TemplateArgument Converted;
John Wiegley429bb272011-04-08 18:41:53 +0000699 ExprResult DefaultRes = CheckTemplateArgument(Param, Param->getType(), Default, Converted);
700 if (DefaultRes.isInvalid()) {
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000701 Param->setInvalidDecl();
John McCalld226f652010-08-21 09:40:31 +0000702 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000703 }
John Wiegley429bb272011-04-08 18:41:53 +0000704 Default = DefaultRes.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000705
John McCall9ae2f072010-08-23 23:25:46 +0000706 Param->setDefaultArgument(Default, false);
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000707 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000708
John McCalld226f652010-08-21 09:40:31 +0000709 return Param;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000710}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000711
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000712/// ActOnTemplateTemplateParameter - Called when a C++ template template
713/// parameter (e.g. T in template <template <typename> class T> class array)
714/// has been parsed. S is the current scope.
John McCalld226f652010-08-21 09:40:31 +0000715Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
716 SourceLocation TmpLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +0000717 TemplateParameterList *Params,
Douglas Gregor61c4d282011-01-05 15:48:55 +0000718 SourceLocation EllipsisLoc,
John McCalld226f652010-08-21 09:40:31 +0000719 IdentifierInfo *Name,
720 SourceLocation NameLoc,
721 unsigned Depth,
722 unsigned Position,
723 SourceLocation EqualLoc,
Douglas Gregor61c4d282011-01-05 15:48:55 +0000724 ParsedTemplateArgument Default) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000725 assert(S->isTemplateParamScope() &&
726 "Template template parameter not in template parameter scope!");
727
728 // Construct the parameter object.
Douglas Gregor61c4d282011-01-05 15:48:55 +0000729 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000730 TemplateTemplateParmDecl *Param =
John McCall7a9813c2010-01-22 00:28:27 +0000731 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000732 NameLoc.isInvalid()? TmpLoc : NameLoc,
733 Depth, Position, IsParameterPack,
Douglas Gregor61c4d282011-01-05 15:48:55 +0000734 Name, Params);
Douglas Gregor9a299e02011-03-04 17:52:15 +0000735 Param->setAccess(AS_public);
736
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000737 // If the template template parameter has a name, then link the identifier
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000738 // into the scope and lookup mechanisms.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000739 if (Name) {
John McCalld226f652010-08-21 09:40:31 +0000740 S->AddDecl(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000741 IdResolver.AddDecl(Param);
742 }
743
Douglas Gregor6f526752010-12-16 08:48:57 +0000744 if (Params->size() == 0) {
745 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
746 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
747 Param->setInvalidDecl();
748 }
749
Douglas Gregor61c4d282011-01-05 15:48:55 +0000750 // C++0x [temp.param]p9:
751 // A default template-argument may be specified for any kind of
752 // template-parameter that is not a template parameter pack.
753 if (IsParameterPack && !Default.isInvalid()) {
754 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
755 Default = ParsedTemplateArgument();
756 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000757
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000758 if (!Default.isInvalid()) {
759 // Check only that we have a template template argument. We don't want to
760 // try to check well-formedness now, because our template template parameter
761 // might have dependent types in its template parameters, which we wouldn't
762 // be able to match now.
763 //
764 // If none of the template template parameter's template arguments mention
765 // other template parameters, we could actually perform more checking here.
766 // However, it isn't worth doing.
767 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
768 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
769 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
770 << DefaultArg.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +0000771 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000772 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000773
Douglas Gregor6f526752010-12-16 08:48:57 +0000774 // Check for unexpanded parameter packs.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000775 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6f526752010-12-16 08:48:57 +0000776 DefaultArg.getArgument().getAsTemplate(),
777 UPPC_DefaultArgument))
778 return Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000779
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000780 Param->setDefaultArgument(DefaultArg, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000781 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000782
John McCalld226f652010-08-21 09:40:31 +0000783 return Param;
Douglas Gregord684b002009-02-10 19:49:53 +0000784}
785
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000786/// ActOnTemplateParameterList - Builds a TemplateParameterList that
787/// contains the template parameters in Params/NumParams.
Richard Trieu90ab75b2011-09-09 03:18:59 +0000788TemplateParameterList *
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000789Sema::ActOnTemplateParameterList(unsigned Depth,
790 SourceLocation ExportLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000791 SourceLocation TemplateLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000792 SourceLocation LAngleLoc,
John McCalld226f652010-08-21 09:40:31 +0000793 Decl **Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000794 SourceLocation RAngleLoc) {
795 if (ExportLoc.isValid())
Douglas Gregor51ffb0c2009-11-25 18:55:14 +0000796 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000797
Douglas Gregorddc29e12009-02-06 22:42:48 +0000798 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000799 (NamedDecl**)Params, NumParams,
Douglas Gregorbf4ea562009-09-15 16:23:51 +0000800 RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000801}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000802
John McCallb6217662010-03-15 10:12:16 +0000803static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
804 if (SS.isSet())
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000805 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
John McCallb6217662010-03-15 10:12:16 +0000806}
807
John McCallf312b1e2010-08-26 23:41:50 +0000808DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000809Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000810 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000811 IdentifierInfo *Name, SourceLocation NameLoc,
812 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000813 TemplateParameterList *TemplateParams,
Douglas Gregore7612302011-09-09 19:05:14 +0000814 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +0000815 unsigned NumOuterTemplateParamLists,
816 TemplateParameterList** OuterTemplateParamLists) {
Mike Stump1eb44332009-09-09 15:08:12 +0000817 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor05396e22009-08-25 17:23:04 +0000818 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000819 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000820 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000821
822 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000823 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000824 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000825
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000826 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
827 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorddc29e12009-02-06 22:42:48 +0000828
829 // There is no such thing as an unnamed class template.
830 if (!Name) {
831 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000832 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000833 }
834
835 // Find any previous declaration with this name.
Douglas Gregor05396e22009-08-25 17:23:04 +0000836 DeclContext *SemanticContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000837 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +0000838 ForRedeclaration);
Douglas Gregor05396e22009-08-25 17:23:04 +0000839 if (SS.isNotEmpty() && !SS.isInvalid()) {
840 SemanticContext = computeDeclContext(SS, true);
841 if (!SemanticContext) {
842 // FIXME: Produce a reasonable diagnostic here
843 return true;
844 }
Mike Stump1eb44332009-09-09 15:08:12 +0000845
John McCall77bb1aa2010-05-01 00:40:08 +0000846 if (RequireCompleteDeclContext(SS, SemanticContext))
847 return true;
848
Douglas Gregor20606502011-10-14 15:31:12 +0000849 // If we're adding a template to a dependent context, we may need to
850 // rebuilding some of the types used within the template parameter list,
851 // now that we know what the current instantiation is.
852 if (SemanticContext->isDependentContext()) {
853 ContextRAII SavedContext(*this, SemanticContext);
854 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
855 Invalid = true;
856 }
857
John McCalla24dc2e2009-11-17 02:14:36 +0000858 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor05396e22009-08-25 17:23:04 +0000859 } else {
860 SemanticContext = CurContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000861 LookupName(Previous, S);
Douglas Gregor05396e22009-08-25 17:23:04 +0000862 }
Mike Stump1eb44332009-09-09 15:08:12 +0000863
Douglas Gregor57265e32010-04-12 16:00:01 +0000864 if (Previous.isAmbiguous())
865 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000866
Douglas Gregorddc29e12009-02-06 22:42:48 +0000867 NamedDecl *PrevDecl = 0;
868 if (Previous.begin() != Previous.end())
Douglas Gregor57265e32010-04-12 16:00:01 +0000869 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000870
Douglas Gregorddc29e12009-02-06 22:42:48 +0000871 // If there is a previous declaration with the same name, check
872 // whether this is a valid redeclaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000873 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorddc29e12009-02-06 22:42:48 +0000874 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000875
876 // We may have found the injected-class-name of a class template,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000877 // class template partial specialization, or class template specialization.
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000878 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000879 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000880 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
881 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000882 PrevClassTemplate
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000883 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
884 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
885 PrevClassTemplate
886 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
887 ->getSpecializedTemplate();
888 }
889 }
890
John McCall65c49462009-12-18 11:25:59 +0000891 if (TUK == TUK_Friend) {
John McCalle129d442009-12-17 23:21:11 +0000892 // C++ [namespace.memdef]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000893 // [...] When looking for a prior declaration of a class or a function
894 // declared as a friend, and when the name of the friend class or
John McCalle129d442009-12-17 23:21:11 +0000895 // function is neither a qualified name nor a template-id, scopes outside
896 // the innermost enclosing namespace scope are not considered.
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000897 if (!SS.isSet()) {
898 DeclContext *OutermostContext = CurContext;
899 while (!OutermostContext->isFileContext())
900 OutermostContext = OutermostContext->getLookupParent();
John McCall65c49462009-12-18 11:25:59 +0000901
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000902 if (PrevDecl &&
903 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
904 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
905 SemanticContext = PrevDecl->getDeclContext();
906 } else {
907 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000908 // context we computed is the semantic context for our new
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000909 // declaration.
910 PrevDecl = PrevClassTemplate = 0;
911 SemanticContext = OutermostContext;
912 }
John McCalle129d442009-12-17 23:21:11 +0000913 }
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000914
John McCalle129d442009-12-17 23:21:11 +0000915 if (CurContext->isDependentContext()) {
916 // If this is a dependent context, we don't want to link the friend
917 // class template to the template in scope, because that would perform
918 // checking of the template parameter lists that can't be performed
919 // until the outer context is instantiated.
920 PrevDecl = PrevClassTemplate = 0;
921 }
922 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
923 PrevDecl = PrevClassTemplate = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000924
Douglas Gregorddc29e12009-02-06 22:42:48 +0000925 if (PrevClassTemplate) {
926 // Ensure that the template parameter lists are compatible.
927 if (!TemplateParameterListsAreEqual(TemplateParams,
928 PrevClassTemplate->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +0000929 /*Complain=*/true,
930 TPL_TemplateMatch))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000931 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000932
933 // C++ [temp.class]p4:
934 // In a redeclaration, partial specialization, explicit
935 // specialization or explicit instantiation of a class template,
936 // the class-key shall agree in kind with the original class
937 // template declaration (7.1.5.3).
938 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieubbf34c02011-06-10 03:11:26 +0000939 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
940 TUK == TUK_Definition, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000941 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +0000942 << Name
Douglas Gregor849b2432010-03-31 17:46:05 +0000943 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000944 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000945 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000946 }
947
Douglas Gregorddc29e12009-02-06 22:42:48 +0000948 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000949 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +0000950 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000951 Diag(NameLoc, diag::err_redefinition) << Name;
952 Diag(Def->getLocation(), diag::note_previous_definition);
953 // FIXME: Would it make sense to try to "forget" the previous
954 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000955 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000956 }
Douglas Gregor6311d2b2011-09-09 18:32:39 +0000957 }
Douglas Gregorddc29e12009-02-06 22:42:48 +0000958 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
959 // Maybe we will complain about the shadowed template parameter.
960 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
961 // Just pretend that we didn't see the previous declaration.
962 PrevDecl = 0;
963 } else if (PrevDecl) {
964 // C++ [temp]p5:
965 // A class template shall not have the same name as any other
966 // template, class, function, object, enumeration, enumerator,
967 // namespace, or type in the same scope (3.3), except as specified
968 // in (14.5.4).
969 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
970 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000971 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000972 }
973
Douglas Gregord684b002009-02-10 19:49:53 +0000974 // Check the template parameter list of this declaration, possibly
975 // merging in the template parameter list from the previous class
976 // template declaration.
977 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000978 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
Douglas Gregord89d86f2011-02-04 04:20:44 +0000979 (SS.isSet() && SemanticContext &&
Douglas Gregor461bf2e2011-02-04 12:22:53 +0000980 SemanticContext->isRecord() &&
981 SemanticContext->isDependentContext())
Douglas Gregord89d86f2011-02-04 04:20:44 +0000982 ? TPC_ClassTemplateMember
983 : TPC_ClassTemplate))
Douglas Gregord684b002009-02-10 19:49:53 +0000984 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000985
Douglas Gregor57265e32010-04-12 16:00:01 +0000986 if (SS.isSet()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000987 // If the name of the template was qualified, we must be defining the
Douglas Gregor57265e32010-04-12 16:00:01 +0000988 // template out-of-line.
989 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
990 !(TUK == TUK_Friend && CurContext->isDependentContext()))
991 Diag(NameLoc, diag::err_member_def_does_not_match)
992 << Name << SemanticContext << SS.getRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000993 }
994
Mike Stump1eb44332009-09-09 15:08:12 +0000995 CXXRecordDecl *NewClass =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000996 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Mike Stump1eb44332009-09-09 15:08:12 +0000997 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000998 PrevClassTemplate->getTemplatedDecl() : 0,
999 /*DelayTypeCreation=*/true);
John McCallb6217662010-03-15 10:12:16 +00001000 SetNestedNameSpecifier(NewClass, SS);
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00001001 if (NumOuterTemplateParamLists > 0)
1002 NewClass->setTemplateParameterListsInfo(Context,
1003 NumOuterTemplateParamLists,
1004 OuterTemplateParamLists);
Douglas Gregorddc29e12009-02-06 22:42:48 +00001005
1006 ClassTemplateDecl *NewTemplate
1007 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1008 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001009 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +00001010 NewClass->setDescribedClassTemplate(NewTemplate);
Douglas Gregor6311d2b2011-09-09 18:32:39 +00001011
1012 if (PrevClassTemplate && PrevClassTemplate->isModulePrivate()) {
1013 NewTemplate->setModulePrivate();
Douglas Gregore7612302011-09-09 19:05:14 +00001014 } else if (ModulePrivateLoc.isValid()) {
1015 if (PrevClassTemplate && !PrevClassTemplate->isModulePrivate())
1016 diagnoseModulePrivateRedeclaration(NewTemplate, PrevClassTemplate,
1017 ModulePrivateLoc);
1018 else
1019 NewTemplate->setModulePrivate();
1020 }
Douglas Gregor8d267c52011-09-09 02:06:17 +00001021
Douglas Gregoraafc0cc2009-05-15 19:11:46 +00001022 // Build the type for the class template declaration now.
Douglas Gregor24bae922010-07-08 18:37:38 +00001023 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCall3cb0ebd2010-03-10 03:28:59 +00001024 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregoraafc0cc2009-05-15 19:11:46 +00001025 assert(T->isDependentType() && "Class template type is not dependent?");
1026 (void)T;
1027
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001028 // If we are providing an explicit specialization of a member that is a
Douglas Gregorfd056bc2009-10-13 16:30:37 +00001029 // class template, make a note of that.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001030 if (PrevClassTemplate &&
Douglas Gregorfd056bc2009-10-13 16:30:37 +00001031 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1032 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001033
Anders Carlsson4cbe82c2009-03-26 01:24:28 +00001034 // Set the access specifier.
Douglas Gregord85bea22009-09-26 06:47:28 +00001035 if (!Invalid && TUK != TUK_Friend)
John McCall05b23ea2009-09-14 21:59:20 +00001036 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001037
Douglas Gregorddc29e12009-02-06 22:42:48 +00001038 // Set the lexical context of these templates
1039 NewClass->setLexicalDeclContext(CurContext);
1040 NewTemplate->setLexicalDeclContext(CurContext);
1041
John McCall0f434ec2009-07-31 02:45:11 +00001042 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +00001043 NewClass->startDefinition();
1044
1045 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001046 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +00001047
John McCall05b23ea2009-09-14 21:59:20 +00001048 if (TUK != TUK_Friend)
1049 PushOnScopeChains(NewTemplate, S);
1050 else {
Douglas Gregord85bea22009-09-26 06:47:28 +00001051 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall05b23ea2009-09-14 21:59:20 +00001052 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregord85bea22009-09-26 06:47:28 +00001053 NewClass->setAccess(PrevClassTemplate->getAccess());
1054 }
John McCall05b23ea2009-09-14 21:59:20 +00001055
Douglas Gregord85bea22009-09-26 06:47:28 +00001056 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
1057 PrevClassTemplate != NULL);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001058
John McCall05b23ea2009-09-14 21:59:20 +00001059 // Friend templates are visible in fairly strange ways.
1060 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00001061 DeclContext *DC = SemanticContext->getRedeclContext();
John McCall05b23ea2009-09-14 21:59:20 +00001062 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
1063 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1064 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001065 /* AddToContext = */ false);
John McCall05b23ea2009-09-14 21:59:20 +00001066 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001067
Douglas Gregord85bea22009-09-26 06:47:28 +00001068 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
1069 NewClass->getLocation(),
1070 NewTemplate,
1071 /*FIXME:*/NewClass->getLocation());
1072 Friend->setAccess(AS_public);
1073 CurContext->addDecl(Friend);
John McCall05b23ea2009-09-14 21:59:20 +00001074 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00001075
Douglas Gregord684b002009-02-10 19:49:53 +00001076 if (Invalid) {
1077 NewTemplate->setInvalidDecl();
1078 NewClass->setInvalidDecl();
1079 }
John McCalld226f652010-08-21 09:40:31 +00001080 return NewTemplate;
Douglas Gregorddc29e12009-02-06 22:42:48 +00001081}
1082
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001083/// \brief Diagnose the presence of a default template argument on a
1084/// template parameter, which is ill-formed in certain contexts.
1085///
1086/// \returns true if the default template argument should be dropped.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001087static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001088 Sema::TemplateParamListContext TPC,
1089 SourceLocation ParamLoc,
1090 SourceRange DefArgRange) {
1091 switch (TPC) {
1092 case Sema::TPC_ClassTemplate:
Richard Smith3e4c6c42011-05-05 21:57:07 +00001093 case Sema::TPC_TypeAliasTemplate:
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001094 return false;
1095
1096 case Sema::TPC_FunctionTemplate:
Douglas Gregord89d86f2011-02-04 04:20:44 +00001097 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001098 // C++ [temp.param]p9:
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001099 // A default template-argument shall not be specified in a
1100 // function template declaration or a function template
1101 // definition [...]
Douglas Gregord89d86f2011-02-04 04:20:44 +00001102 // If a friend function template declaration specifies a default
1103 // template-argument, that declaration shall be a definition and shall be
1104 // the only declaration of the function template in the translation unit.
1105 // (C++98/03 doesn't have this wording; see DR226).
Richard Smithebaf0e62011-10-18 20:49:44 +00001106 S.Diag(ParamLoc, S.getLangOptions().CPlusPlus0x ?
1107 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1108 : diag::ext_template_parameter_default_in_function_template)
1109 << DefArgRange;
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001110 return false;
1111
1112 case Sema::TPC_ClassTemplateMember:
1113 // C++0x [temp.param]p9:
1114 // A default template-argument shall not be specified in the
1115 // template-parameter-lists of the definition of a member of a
1116 // class template that appears outside of the member's class.
1117 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1118 << DefArgRange;
1119 return true;
1120
1121 case Sema::TPC_FriendFunctionTemplate:
1122 // C++ [temp.param]p9:
1123 // A default template-argument shall not be specified in a
1124 // friend template declaration.
1125 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1126 << DefArgRange;
1127 return true;
1128
1129 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1130 // for friend function templates if there is only a single
1131 // declaration (and it is a definition). Strange!
1132 }
1133
1134 return false;
1135}
1136
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001137/// \brief Check for unexpanded parameter packs within the template parameters
1138/// of a template template parameter, recursively.
Benjamin Kramerda57f3e2011-03-26 12:38:21 +00001139static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1140 TemplateTemplateParmDecl *TTP) {
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001141 TemplateParameterList *Params = TTP->getTemplateParameters();
1142 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1143 NamedDecl *P = Params->getParam(I);
1144 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001145 if (S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001146 NTTP->getTypeSourceInfo(),
1147 Sema::UPPC_NonTypeTemplateParameterType))
1148 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001149
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001150 continue;
1151 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001152
1153 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001154 = dyn_cast<TemplateTemplateParmDecl>(P))
1155 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1156 return true;
1157 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001158
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001159 return false;
1160}
1161
Douglas Gregord684b002009-02-10 19:49:53 +00001162/// \brief Checks the validity of a template parameter list, possibly
1163/// considering the template parameter list from a previous
1164/// declaration.
1165///
1166/// If an "old" template parameter list is provided, it must be
1167/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1168/// template parameter list.
1169///
1170/// \param NewParams Template parameter list for a new template
1171/// declaration. This template parameter list will be updated with any
1172/// default arguments that are carried through from the previous
1173/// template parameter list.
1174///
1175/// \param OldParams If provided, template parameter list from a
1176/// previous declaration of the same template. Default template
1177/// arguments will be merged from the old template parameter list to
1178/// the new template parameter list.
1179///
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001180/// \param TPC Describes the context in which we are checking the given
1181/// template parameter list.
1182///
Douglas Gregord684b002009-02-10 19:49:53 +00001183/// \returns true if an error occurred, false otherwise.
1184bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001185 TemplateParameterList *OldParams,
1186 TemplateParamListContext TPC) {
Douglas Gregord684b002009-02-10 19:49:53 +00001187 bool Invalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001188
Douglas Gregord684b002009-02-10 19:49:53 +00001189 // C++ [temp.param]p10:
1190 // The set of default template-arguments available for use with a
1191 // template declaration or definition is obtained by merging the
1192 // default arguments from the definition (if in scope) and all
1193 // declarations in scope in the same way default function
1194 // arguments are (8.3.6).
1195 bool SawDefaultArgument = false;
1196 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001197
Mike Stump1a35fde2009-02-11 23:03:27 +00001198 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +00001199 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +00001200 if (OldParams)
1201 OldParam = OldParams->begin();
1202
Douglas Gregorfd1a8fd2011-01-27 01:40:17 +00001203 bool RemoveDefaultArguments = false;
Douglas Gregord684b002009-02-10 19:49:53 +00001204 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1205 NewParamEnd = NewParams->end();
1206 NewParam != NewParamEnd; ++NewParam) {
1207 // Variables used to diagnose redundant default arguments
1208 bool RedundantDefaultArg = false;
1209 SourceLocation OldDefaultLoc;
1210 SourceLocation NewDefaultLoc;
1211
David Blaikie1368e582011-10-19 05:19:50 +00001212 // Variable used to diagnose missing default arguments
Douglas Gregord684b002009-02-10 19:49:53 +00001213 bool MissingDefaultArg = false;
1214
David Blaikie1368e582011-10-19 05:19:50 +00001215 // Variable used to diagnose non-final parameter packs
1216 bool SawParameterPack = false;
Anders Carlsson49d25572009-06-12 23:20:15 +00001217
Douglas Gregord684b002009-02-10 19:49:53 +00001218 if (TemplateTypeParmDecl *NewTypeParm
1219 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001220 // Check the presence of a default argument here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001221 if (NewTypeParm->hasDefaultArgument() &&
1222 DiagnoseDefaultTemplateArgument(*this, TPC,
1223 NewTypeParm->getLocation(),
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001224 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001225 .getSourceRange()))
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001226 NewTypeParm->removeDefaultArgument();
1227
1228 // Merge default arguments for template type parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00001229 TemplateTypeParmDecl *OldTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001230 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001231
Anders Carlsson49d25572009-06-12 23:20:15 +00001232 if (NewTypeParm->isParameterPack()) {
1233 assert(!NewTypeParm->hasDefaultArgument() &&
1234 "Parameter packs can't have a default argument!");
1235 SawParameterPack = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001236 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall833ca992009-10-29 08:12:44 +00001237 NewTypeParm->hasDefaultArgument()) {
Douglas Gregord684b002009-02-10 19:49:53 +00001238 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1239 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1240 SawDefaultArgument = true;
1241 RedundantDefaultArg = true;
1242 PreviousDefaultArgLoc = NewDefaultLoc;
1243 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1244 // Merge the default argument from the old declaration to the
1245 // new declaration.
1246 SawDefaultArgument = true;
John McCall833ca992009-10-29 08:12:44 +00001247 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregord684b002009-02-10 19:49:53 +00001248 true);
1249 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1250 } else if (NewTypeParm->hasDefaultArgument()) {
1251 SawDefaultArgument = true;
1252 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1253 } else if (SawDefaultArgument)
1254 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001255 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001256 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001257 // Check for unexpanded parameter packs.
1258 if (DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001259 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001260 UPPC_NonTypeTemplateParameterType)) {
1261 Invalid = true;
1262 continue;
1263 }
1264
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001265 // Check the presence of a default argument here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001266 if (NewNonTypeParm->hasDefaultArgument() &&
1267 DiagnoseDefaultTemplateArgument(*this, TPC,
1268 NewNonTypeParm->getLocation(),
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001269 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001270 NewNonTypeParm->removeDefaultArgument();
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001271 }
1272
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001273 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001274 NonTypeTemplateParmDecl *OldNonTypeParm
1275 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Douglas Gregor1ed64762011-01-05 16:19:19 +00001276 if (NewNonTypeParm->isParameterPack()) {
1277 assert(!NewNonTypeParm->hasDefaultArgument() &&
1278 "Parameter packs can't have a default argument!");
1279 SawParameterPack = true;
Douglas Gregor1ed64762011-01-05 16:19:19 +00001280 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001281 NewNonTypeParm->hasDefaultArgument()) {
1282 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1283 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1284 SawDefaultArgument = true;
1285 RedundantDefaultArg = true;
1286 PreviousDefaultArgLoc = NewDefaultLoc;
1287 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1288 // Merge the default argument from the old declaration to the
1289 // new declaration.
1290 SawDefaultArgument = true;
1291 // FIXME: We need to create a new kind of "default argument"
Douglas Gregor61c4d282011-01-05 15:48:55 +00001292 // expression that points to a previous non-type template
Douglas Gregord684b002009-02-10 19:49:53 +00001293 // parameter.
1294 NewNonTypeParm->setDefaultArgument(
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001295 OldNonTypeParm->getDefaultArgument(),
1296 /*Inherited=*/ true);
Douglas Gregord684b002009-02-10 19:49:53 +00001297 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1298 } else if (NewNonTypeParm->hasDefaultArgument()) {
1299 SawDefaultArgument = true;
1300 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1301 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001302 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001303 } else {
Douglas Gregord684b002009-02-10 19:49:53 +00001304 TemplateTemplateParmDecl *NewTemplateParm
1305 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001306
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001307 // Check for unexpanded parameter packs, recursively.
1308 if (DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
1309 Invalid = true;
1310 continue;
1311 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001312
David Blaikie1368e582011-10-19 05:19:50 +00001313 // Check the presence of a default argument here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001314 if (NewTemplateParm->hasDefaultArgument() &&
1315 DiagnoseDefaultTemplateArgument(*this, TPC,
1316 NewTemplateParm->getLocation(),
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001317 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001318 NewTemplateParm->removeDefaultArgument();
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001319
1320 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001321 TemplateTemplateParmDecl *OldTemplateParm
1322 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Douglas Gregor1ed64762011-01-05 16:19:19 +00001323 if (NewTemplateParm->isParameterPack()) {
1324 assert(!NewTemplateParm->hasDefaultArgument() &&
1325 "Parameter packs can't have a default argument!");
1326 SawParameterPack = true;
Douglas Gregor1ed64762011-01-05 16:19:19 +00001327 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001328 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor788cd062009-11-11 01:00:40 +00001329 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1330 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001331 SawDefaultArgument = true;
1332 RedundantDefaultArg = true;
1333 PreviousDefaultArgLoc = NewDefaultLoc;
1334 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1335 // Merge the default argument from the old declaration to the
1336 // new declaration.
1337 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +00001338 // FIXME: We need to create a new kind of "default argument" expression
1339 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +00001340 NewTemplateParm->setDefaultArgument(
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001341 OldTemplateParm->getDefaultArgument(),
1342 /*Inherited=*/ true);
Douglas Gregor788cd062009-11-11 01:00:40 +00001343 PreviousDefaultArgLoc
1344 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001345 } else if (NewTemplateParm->hasDefaultArgument()) {
1346 SawDefaultArgument = true;
Douglas Gregor788cd062009-11-11 01:00:40 +00001347 PreviousDefaultArgLoc
1348 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001349 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001350 MissingDefaultArg = true;
Douglas Gregord684b002009-02-10 19:49:53 +00001351 }
1352
David Blaikie1368e582011-10-19 05:19:50 +00001353 // C++0x [temp.param]p11:
1354 // If a template parameter of a primary class template or alias template
1355 // is a template parameter pack, it shall be the last template parameter.
1356 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
1357 (TPC == TPC_ClassTemplate || TPC == TPC_TypeAliasTemplate)) {
1358 Diag((*NewParam)->getLocation(),
1359 diag::err_template_param_pack_must_be_last_template_parameter);
1360 Invalid = true;
1361 }
1362
Douglas Gregord684b002009-02-10 19:49:53 +00001363 if (RedundantDefaultArg) {
1364 // C++ [temp.param]p12:
1365 // A template-parameter shall not be given default arguments
1366 // by two different declarations in the same scope.
1367 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1368 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1369 Invalid = true;
Douglas Gregoree5d21f2011-02-04 03:57:22 +00001370 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregord684b002009-02-10 19:49:53 +00001371 // C++ [temp.param]p11:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001372 // If a template-parameter of a class template has a default
1373 // template-argument, each subsequent template-parameter shall either
Douglas Gregorb49e4152011-01-05 16:21:17 +00001374 // have a default template-argument supplied or be a template parameter
1375 // pack.
Mike Stump1eb44332009-09-09 15:08:12 +00001376 Diag((*NewParam)->getLocation(),
Douglas Gregord684b002009-02-10 19:49:53 +00001377 diag::err_template_param_default_arg_missing);
1378 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1379 Invalid = true;
Douglas Gregorfd1a8fd2011-01-27 01:40:17 +00001380 RemoveDefaultArguments = true;
Douglas Gregord684b002009-02-10 19:49:53 +00001381 }
1382
1383 // If we have an old template parameter list that we're merging
1384 // in, move on to the next parameter.
1385 if (OldParams)
1386 ++OldParam;
1387 }
1388
Douglas Gregorfd1a8fd2011-01-27 01:40:17 +00001389 // We were missing some default arguments at the end of the list, so remove
1390 // all of the default arguments.
1391 if (RemoveDefaultArguments) {
1392 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1393 NewParamEnd = NewParams->end();
1394 NewParam != NewParamEnd; ++NewParam) {
1395 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1396 TTP->removeDefaultArgument();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001397 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregorfd1a8fd2011-01-27 01:40:17 +00001398 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1399 NTTP->removeDefaultArgument();
1400 else
1401 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1402 }
1403 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001404
Douglas Gregord684b002009-02-10 19:49:53 +00001405 return Invalid;
1406}
Douglas Gregorc15cb382009-02-09 23:23:08 +00001407
John McCall4e2cbb22010-10-20 05:44:58 +00001408namespace {
1409
1410/// A class which looks for a use of a certain level of template
1411/// parameter.
1412struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1413 typedef RecursiveASTVisitor<DependencyChecker> super;
1414
1415 unsigned Depth;
1416 bool Match;
1417
1418 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1419 NamedDecl *ND = Params->getParam(0);
1420 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1421 Depth = PD->getDepth();
1422 } else if (NonTypeTemplateParmDecl *PD =
1423 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1424 Depth = PD->getDepth();
1425 } else {
1426 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1427 }
1428 }
1429
1430 bool Matches(unsigned ParmDepth) {
1431 if (ParmDepth >= Depth) {
1432 Match = true;
1433 return true;
1434 }
1435 return false;
1436 }
1437
1438 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1439 return !Matches(T->getDepth());
1440 }
1441
1442 bool TraverseTemplateName(TemplateName N) {
1443 if (TemplateTemplateParmDecl *PD =
1444 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
1445 if (Matches(PD->getDepth())) return false;
1446 return super::TraverseTemplateName(N);
1447 }
1448
1449 bool VisitDeclRefExpr(DeclRefExpr *E) {
1450 if (NonTypeTemplateParmDecl *PD =
1451 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) {
1452 if (PD->getDepth() == Depth) {
1453 Match = true;
1454 return false;
1455 }
1456 }
1457 return super::VisitDeclRefExpr(E);
1458 }
Douglas Gregor18c83392011-05-13 00:34:01 +00001459
1460 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1461 return TraverseType(T->getInjectedSpecializationType());
1462 }
John McCall4e2cbb22010-10-20 05:44:58 +00001463};
1464}
1465
Douglas Gregorc8406492011-05-10 18:27:06 +00001466/// Determines whether a given type depends on the given parameter
John McCall4e2cbb22010-10-20 05:44:58 +00001467/// list.
1468static bool
Douglas Gregorc8406492011-05-10 18:27:06 +00001469DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
John McCall4e2cbb22010-10-20 05:44:58 +00001470 DependencyChecker Checker(Params);
Douglas Gregorc8406492011-05-10 18:27:06 +00001471 Checker.TraverseType(T);
John McCall4e2cbb22010-10-20 05:44:58 +00001472 return Checker.Match;
1473}
1474
Douglas Gregorc8406492011-05-10 18:27:06 +00001475// Find the source range corresponding to the named type in the given
1476// nested-name-specifier, if any.
1477static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1478 QualType T,
1479 const CXXScopeSpec &SS) {
1480 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1481 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1482 if (const Type *CurType = NNS->getAsType()) {
1483 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1484 return NNSLoc.getTypeLoc().getSourceRange();
1485 } else
1486 break;
1487
1488 NNSLoc = NNSLoc.getPrefix();
1489 }
1490
1491 return SourceRange();
1492}
1493
Mike Stump1eb44332009-09-09 15:08:12 +00001494/// \brief Match the given template parameter lists to the given scope
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001495/// specifier, returning the template parameter list that applies to the
1496/// name.
1497///
1498/// \param DeclStartLoc the start of the declaration that has a scope
1499/// specifier or a template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +00001500///
Douglas Gregorc8406492011-05-10 18:27:06 +00001501/// \param DeclLoc The location of the declaration itself.
1502///
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001503/// \param SS the scope specifier that will be matched to the given template
1504/// parameter lists. This scope specifier precedes a qualified name that is
1505/// being declared.
1506///
1507/// \param ParamLists the template parameter lists, from the outermost to the
1508/// innermost template parameter lists.
1509///
1510/// \param NumParamLists the number of template parameter lists in ParamLists.
1511///
John McCall77e8b112010-04-13 20:37:33 +00001512/// \param IsFriend Whether to apply the slightly different rules for
1513/// matching template parameters to scope specifiers in friend
1514/// declarations.
1515///
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001516/// \param IsExplicitSpecialization will be set true if the entity being
1517/// declared is an explicit specialization, false otherwise.
1518///
Mike Stump1eb44332009-09-09 15:08:12 +00001519/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001520/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00001521/// parameter list may have template parameters (if we're declaring a
Mike Stump1eb44332009-09-09 15:08:12 +00001522/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00001523/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001524/// itself a template).
1525TemplateParameterList *
1526Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
Douglas Gregorc8406492011-05-10 18:27:06 +00001527 SourceLocation DeclLoc,
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001528 const CXXScopeSpec &SS,
1529 TemplateParameterList **ParamLists,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001530 unsigned NumParamLists,
John McCall77e8b112010-04-13 20:37:33 +00001531 bool IsFriend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001532 bool &IsExplicitSpecialization,
1533 bool &Invalid) {
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001534 IsExplicitSpecialization = false;
Douglas Gregorc8406492011-05-10 18:27:06 +00001535 Invalid = false;
1536
1537 // The sequence of nested types to which we will match up the template
1538 // parameter lists. We first build this list by starting with the type named
1539 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001540 SmallVector<QualType, 4> NestedTypes;
Douglas Gregorc8406492011-05-10 18:27:06 +00001541 QualType T;
Douglas Gregor714c9922011-05-15 17:27:27 +00001542 if (SS.getScopeRep()) {
1543 if (CXXRecordDecl *Record
1544 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1545 T = Context.getTypeDeclType(Record);
1546 else
1547 T = QualType(SS.getScopeRep()->getAsType(), 0);
1548 }
Douglas Gregorc8406492011-05-10 18:27:06 +00001549
1550 // If we found an explicit specialization that prevents us from needing
1551 // 'template<>' headers, this will be set to the location of that
1552 // explicit specialization.
1553 SourceLocation ExplicitSpecLoc;
1554
1555 while (!T.isNull()) {
1556 NestedTypes.push_back(T);
1557
1558 // Retrieve the parent of a record type.
1559 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1560 // If this type is an explicit specialization, we're done.
1561 if (ClassTemplateSpecializationDecl *Spec
1562 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1563 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1564 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1565 ExplicitSpecLoc = Spec->getLocation();
1566 break;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001567 }
Douglas Gregorc8406492011-05-10 18:27:06 +00001568 } else if (Record->getTemplateSpecializationKind()
1569 == TSK_ExplicitSpecialization) {
1570 ExplicitSpecLoc = Record->getLocation();
John McCall77e8b112010-04-13 20:37:33 +00001571 break;
1572 }
Douglas Gregorc8406492011-05-10 18:27:06 +00001573
1574 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1575 T = Context.getTypeDeclType(Parent);
1576 else
1577 T = QualType();
1578 continue;
1579 }
1580
1581 if (const TemplateSpecializationType *TST
1582 = T->getAs<TemplateSpecializationType>()) {
1583 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1584 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1585 T = Context.getTypeDeclType(Parent);
1586 else
1587 T = QualType();
1588 continue;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001589 }
Douglas Gregorc8406492011-05-10 18:27:06 +00001590 }
1591
1592 // Look one step prior in a dependent template specialization type.
1593 if (const DependentTemplateSpecializationType *DependentTST
1594 = T->getAs<DependentTemplateSpecializationType>()) {
1595 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1596 T = QualType(NNS->getAsType(), 0);
1597 else
1598 T = QualType();
1599 continue;
1600 }
1601
1602 // Look one step prior in a dependent name type.
1603 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1604 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1605 T = QualType(NNS->getAsType(), 0);
1606 else
1607 T = QualType();
1608 continue;
1609 }
1610
1611 // Retrieve the parent of an enumeration type.
1612 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1613 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1614 // check here.
1615 EnumDecl *Enum = EnumT->getDecl();
1616
1617 // Get to the parent type.
1618 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1619 T = Context.getTypeDeclType(Parent);
1620 else
1621 T = QualType();
1622 continue;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001623 }
Mike Stump1eb44332009-09-09 15:08:12 +00001624
Douglas Gregorc8406492011-05-10 18:27:06 +00001625 T = QualType();
1626 }
1627 // Reverse the nested types list, since we want to traverse from the outermost
1628 // to the innermost while checking template-parameter-lists.
1629 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregorb88e8882009-07-30 17:40:51 +00001630
Douglas Gregorc8406492011-05-10 18:27:06 +00001631 // C++0x [temp.expl.spec]p17:
1632 // A member or a member template may be nested within many
1633 // enclosing class templates. In an explicit specialization for
1634 // such a member, the member declaration shall be preceded by a
1635 // template<> for each enclosing class template that is
1636 // explicitly specialized.
Douglas Gregor89b9f102011-06-06 15:22:55 +00001637 bool SawNonEmptyTemplateParameterList = false;
Douglas Gregorc8406492011-05-10 18:27:06 +00001638 unsigned ParamIdx = 0;
1639 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1640 ++TypeIdx) {
1641 T = NestedTypes[TypeIdx];
1642
1643 // Whether we expect a 'template<>' header.
1644 bool NeedEmptyTemplateHeader = false;
1645
1646 // Whether we expect a template header with parameters.
1647 bool NeedNonemptyTemplateHeader = false;
1648
1649 // For a dependent type, the set of template parameters that we
1650 // expect to see.
1651 TemplateParameterList *ExpectedTemplateParams = 0;
1652
Douglas Gregor175c5bb2011-05-11 23:26:17 +00001653 // C++0x [temp.expl.spec]p15:
1654 // A member or a member template may be nested within many enclosing
1655 // class templates. In an explicit specialization for such a member, the
1656 // member declaration shall be preceded by a template<> for each
1657 // enclosing class template that is explicitly specialized.
Douglas Gregorc8406492011-05-10 18:27:06 +00001658 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1659 if (ClassTemplatePartialSpecializationDecl *Partial
1660 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1661 ExpectedTemplateParams = Partial->getTemplateParameters();
1662 NeedNonemptyTemplateHeader = true;
1663 } else if (Record->isDependentType()) {
1664 if (Record->getDescribedClassTemplate()) {
John McCall31f17ec2010-04-27 00:57:59 +00001665 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregorc8406492011-05-10 18:27:06 +00001666 ->getTemplateParameters();
1667 NeedNonemptyTemplateHeader = true;
1668 }
1669 } else if (ClassTemplateSpecializationDecl *Spec
1670 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1671 // C++0x [temp.expl.spec]p4:
1672 // Members of an explicitly specialized class template are defined
1673 // in the same manner as members of normal classes, and not using
1674 // the template<> syntax.
1675 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1676 NeedEmptyTemplateHeader = true;
1677 else
Douglas Gregor95ea4502011-06-01 22:37:07 +00001678 continue;
Douglas Gregorc8406492011-05-10 18:27:06 +00001679 } else if (Record->getTemplateSpecializationKind()) {
1680 if (Record->getTemplateSpecializationKind()
Douglas Gregor175c5bb2011-05-11 23:26:17 +00001681 != TSK_ExplicitSpecialization &&
1682 TypeIdx == NumTypes - 1)
1683 IsExplicitSpecialization = true;
1684
1685 continue;
Douglas Gregorc8406492011-05-10 18:27:06 +00001686 }
1687 } else if (const TemplateSpecializationType *TST
1688 = T->getAs<TemplateSpecializationType>()) {
1689 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1690 ExpectedTemplateParams = Template->getTemplateParameters();
1691 NeedNonemptyTemplateHeader = true;
1692 }
1693 } else if (T->getAs<DependentTemplateSpecializationType>()) {
1694 // FIXME: We actually could/should check the template arguments here
1695 // against the corresponding template parameter list.
1696 NeedNonemptyTemplateHeader = false;
1697 }
1698
Douglas Gregor89b9f102011-06-06 15:22:55 +00001699 // C++ [temp.expl.spec]p16:
1700 // In an explicit specialization declaration for a member of a class
1701 // template or a member template that ap- pears in namespace scope, the
1702 // member template and some of its enclosing class templates may remain
1703 // unspecialized, except that the declaration shall not explicitly
1704 // specialize a class member template if its en- closing class templates
1705 // are not explicitly specialized as well.
1706 if (ParamIdx < NumParamLists) {
1707 if (ParamLists[ParamIdx]->size() == 0) {
1708 if (SawNonEmptyTemplateParameterList) {
1709 Diag(DeclLoc, diag::err_specialize_member_of_template)
1710 << ParamLists[ParamIdx]->getSourceRange();
1711 Invalid = true;
1712 IsExplicitSpecialization = false;
1713 return 0;
1714 }
1715 } else
1716 SawNonEmptyTemplateParameterList = true;
1717 }
1718
Douglas Gregorc8406492011-05-10 18:27:06 +00001719 if (NeedEmptyTemplateHeader) {
1720 // If we're on the last of the types, and we need a 'template<>' header
1721 // here, then it's an explicit specialization.
1722 if (TypeIdx == NumTypes - 1)
1723 IsExplicitSpecialization = true;
1724
1725 if (ParamIdx < NumParamLists) {
1726 if (ParamLists[ParamIdx]->size() > 0) {
1727 // The header has template parameters when it shouldn't. Complain.
1728 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1729 diag::err_template_param_list_matches_nontemplate)
1730 << T
1731 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1732 ParamLists[ParamIdx]->getRAngleLoc())
1733 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1734 Invalid = true;
1735 return 0;
1736 }
1737
1738 // Consume this template header.
1739 ++ParamIdx;
1740 continue;
1741 }
1742
1743 if (!IsFriend) {
1744 // We don't have a template header, but we should.
1745 SourceLocation ExpectedTemplateLoc;
1746 if (NumParamLists > 0)
1747 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1748 else
1749 ExpectedTemplateLoc = DeclStartLoc;
1750
1751 Diag(DeclLoc, diag::err_template_spec_needs_header)
1752 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS)
1753 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1754 }
1755
1756 continue;
1757 }
1758
1759 if (NeedNonemptyTemplateHeader) {
1760 // In friend declarations we can have template-ids which don't
1761 // depend on the corresponding template parameter lists. But
1762 // assume that empty parameter lists are supposed to match this
1763 // template-id.
1764 if (IsFriend && T->isDependentType()) {
1765 if (ParamIdx < NumParamLists &&
1766 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
1767 ExpectedTemplateParams = 0;
1768 else
1769 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001770 }
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001771
Douglas Gregorc8406492011-05-10 18:27:06 +00001772 if (ParamIdx < NumParamLists) {
1773 // Check the template parameter list, if we can.
1774 if (ExpectedTemplateParams &&
1775 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1776 ExpectedTemplateParams,
1777 true, TPL_TemplateMatch))
1778 Invalid = true;
1779
1780 if (!Invalid &&
1781 CheckTemplateParameterList(ParamLists[ParamIdx], 0,
1782 TPC_ClassTemplateMember))
1783 Invalid = true;
1784
1785 ++ParamIdx;
1786 continue;
1787 }
1788
1789 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
1790 << T
1791 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1792 Invalid = true;
1793 continue;
1794 }
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001795 }
Douglas Gregorc8406492011-05-10 18:27:06 +00001796
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001797 // If there were at least as many template-ids as there were template
1798 // parameter lists, then there are no template parameter lists remaining for
1799 // the declaration itself.
John McCall4e2cbb22010-10-20 05:44:58 +00001800 if (ParamIdx >= NumParamLists)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001801 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001802
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001803 // If there were too many template parameter lists, complain about that now.
Douglas Gregorc8406492011-05-10 18:27:06 +00001804 if (ParamIdx < NumParamLists - 1) {
1805 bool HasAnyExplicitSpecHeader = false;
1806 bool AllExplicitSpecHeaders = true;
1807 for (unsigned I = ParamIdx; I != NumParamLists - 1; ++I) {
1808 if (ParamLists[I]->size() == 0)
1809 HasAnyExplicitSpecHeader = true;
1810 else
1811 AllExplicitSpecHeaders = false;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001812 }
Douglas Gregorc8406492011-05-10 18:27:06 +00001813
1814 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1815 AllExplicitSpecHeaders? diag::warn_template_spec_extra_headers
1816 : diag::err_template_spec_extra_headers)
1817 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1818 ParamLists[NumParamLists - 2]->getRAngleLoc());
1819
1820 // If there was a specialization somewhere, such that 'template<>' is
1821 // not required, and there were any 'template<>' headers, note where the
1822 // specialization occurred.
1823 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
1824 Diag(ExplicitSpecLoc,
1825 diag::note_explicit_template_spec_does_not_need_header)
1826 << NestedTypes.back();
1827
1828 // We have a template parameter list with no corresponding scope, which
1829 // means that the resulting template declaration can't be instantiated
1830 // properly (we'll end up with dependent nodes when we shouldn't).
1831 if (!AllExplicitSpecHeaders)
1832 Invalid = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001833 }
Mike Stump1eb44332009-09-09 15:08:12 +00001834
Douglas Gregor89b9f102011-06-06 15:22:55 +00001835 // C++ [temp.expl.spec]p16:
1836 // In an explicit specialization declaration for a member of a class
1837 // template or a member template that ap- pears in namespace scope, the
1838 // member template and some of its enclosing class templates may remain
1839 // unspecialized, except that the declaration shall not explicitly
1840 // specialize a class member template if its en- closing class templates
1841 // are not explicitly specialized as well.
1842 if (ParamLists[NumParamLists - 1]->size() == 0 &&
1843 SawNonEmptyTemplateParameterList) {
1844 Diag(DeclLoc, diag::err_specialize_member_of_template)
1845 << ParamLists[ParamIdx]->getSourceRange();
1846 Invalid = true;
1847 IsExplicitSpecialization = false;
1848 return 0;
1849 }
1850
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001851 // Return the last template parameter list, which corresponds to the
1852 // entity being declared.
1853 return ParamLists[NumParamLists - 1];
1854}
1855
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +00001856void Sema::NoteAllFoundTemplates(TemplateName Name) {
1857 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
1858 Diag(Template->getLocation(), diag::note_template_declared_here)
1859 << (isa<FunctionTemplateDecl>(Template)? 0
1860 : isa<ClassTemplateDecl>(Template)? 1
Richard Smith3e4c6c42011-05-05 21:57:07 +00001861 : isa<TypeAliasTemplateDecl>(Template)? 2
1862 : 3)
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +00001863 << Template->getDeclName();
1864 return;
1865 }
1866
1867 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
1868 for (OverloadedTemplateStorage::iterator I = OST->begin(),
1869 IEnd = OST->end();
1870 I != IEnd; ++I)
1871 Diag((*I)->getLocation(), diag::note_template_declared_here)
1872 << 0 << (*I)->getDeclName();
1873
1874 return;
1875 }
1876}
1877
1878
Douglas Gregor7532dc62009-03-30 22:58:21 +00001879QualType Sema::CheckTemplateIdType(TemplateName Name,
1880 SourceLocation TemplateLoc,
Douglas Gregor67714232011-03-03 02:41:12 +00001881 TemplateArgumentListInfo &TemplateArgs) {
John McCall14606042011-06-30 08:33:18 +00001882 DependentTemplateName *DTN
1883 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3e4c6c42011-05-05 21:57:07 +00001884 if (DTN && DTN->isIdentifier())
1885 // When building a template-id where the template-name is dependent,
1886 // assume the template is a type template. Either our assumption is
1887 // correct, or the code is ill-formed and will be diagnosed when the
1888 // dependent name is substituted.
1889 return Context.getDependentTemplateSpecializationType(ETK_None,
1890 DTN->getQualifier(),
1891 DTN->getIdentifier(),
1892 TemplateArgs);
1893
Douglas Gregor7532dc62009-03-30 22:58:21 +00001894 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +00001895 if (!Template || isa<FunctionTemplateDecl>(Template)) {
1896 // We might have a substituted template template parameter pack. If so,
1897 // build a template specialization type for it.
1898 if (Name.getAsSubstTemplateTemplateParmPack())
1899 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3e4c6c42011-05-05 21:57:07 +00001900
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +00001901 Diag(TemplateLoc, diag::err_template_id_not_a_type)
1902 << Name;
1903 NoteAllFoundTemplates(Name);
1904 return QualType();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001905 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001906
Douglas Gregor40808ce2009-03-09 23:48:35 +00001907 // Check that the template argument list is well-formed for this
1908 // template.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001909 SmallVector<TemplateArgument, 4> Converted;
John McCalld5532b62009-11-23 01:53:49 +00001910 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00001911 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001912 return QualType();
1913
Douglas Gregor910f8002010-11-07 23:05:16 +00001914 assert((Converted.size() == Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +00001915 "Converted template argument list is too short!");
1916
1917 QualType CanonType;
1918
Douglas Gregor561f8122011-07-01 01:22:09 +00001919 bool InstantiationDependent = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00001920 if (TypeAliasTemplateDecl *AliasTemplate
1921 = dyn_cast<TypeAliasTemplateDecl>(Template)) {
1922 // Find the canonical type for this type alias template specialization.
1923 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
1924 if (Pattern->isInvalidDecl())
1925 return QualType();
1926
1927 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1928 Converted.data(), Converted.size());
1929
1930 // Only substitute for the innermost template argument list.
1931 MultiLevelTemplateArgumentList TemplateArgLists;
Richard Smith18041742011-05-14 15:04:18 +00001932 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
Richard Smithaff37b42011-05-12 00:06:17 +00001933 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
1934 for (unsigned I = 0; I < Depth; ++I)
1935 TemplateArgLists.addOuterTemplateArguments(0, 0);
Richard Smith3e4c6c42011-05-05 21:57:07 +00001936
1937 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
1938 CanonType = SubstType(Pattern->getUnderlyingType(),
1939 TemplateArgLists, AliasTemplate->getLocation(),
1940 AliasTemplate->getDeclName());
1941 if (CanonType.isNull())
1942 return QualType();
1943 } else if (Name.isDependent() ||
1944 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor561f8122011-07-01 01:22:09 +00001945 TemplateArgs, InstantiationDependent)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001946 // This class template specialization is a dependent
1947 // type. Therefore, its canonical type is another class template
1948 // specialization type that contains all of the converted
1949 // arguments in canonical form. This ensures that, e.g., A<T> and
1950 // A<T, T> have identical types when A is declared as:
1951 //
1952 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001953 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00001954 CanonType = Context.getTemplateSpecializationType(CanonName,
Douglas Gregor910f8002010-11-07 23:05:16 +00001955 Converted.data(),
1956 Converted.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001957
Douglas Gregor1275ae02009-07-28 23:00:59 +00001958 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall833ca992009-10-29 08:12:44 +00001959 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001960 // In the future, we need to teach getTemplateSpecializationType to only
1961 // build the canonical type and return that to us.
1962 CanonType = Context.getCanonicalType(CanonType);
John McCall31f17ec2010-04-27 00:57:59 +00001963
1964 // This might work out to be a current instantiation, in which
1965 // case the canonical type needs to be the InjectedClassNameType.
1966 //
1967 // TODO: in theory this could be a simple hashtable lookup; most
1968 // changes to CurContext don't change the set of current
1969 // instantiations.
1970 if (isa<ClassTemplateDecl>(Template)) {
1971 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1972 // If we get out to a namespace, we're done.
1973 if (Ctx->isFileContext()) break;
1974
1975 // If this isn't a record, keep looking.
1976 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1977 if (!Record) continue;
1978
1979 // Look for one of the two cases with InjectedClassNameTypes
1980 // and check whether it's the same template.
1981 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1982 !Record->getDescribedClassTemplate())
1983 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001984
John McCall31f17ec2010-04-27 00:57:59 +00001985 // Fetch the injected class name type and check whether its
1986 // injected type is equal to the type we just built.
1987 QualType ICNT = Context.getTypeDeclType(Record);
1988 QualType Injected = cast<InjectedClassNameType>(ICNT)
1989 ->getInjectedSpecializationType();
1990
1991 if (CanonType != Injected->getCanonicalTypeInternal())
1992 continue;
1993
1994 // If so, the canonical type of this TST is the injected
1995 // class name type of the record we just found.
1996 assert(ICNT.isCanonical());
1997 CanonType = ICNT;
John McCall31f17ec2010-04-27 00:57:59 +00001998 break;
1999 }
2000 }
Mike Stump1eb44332009-09-09 15:08:12 +00002001 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00002002 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00002003 // Find the class template specialization declaration that
2004 // corresponds to these arguments.
Douglas Gregor40808ce2009-03-09 23:48:35 +00002005 void *InsertPos = 0;
2006 ClassTemplateSpecializationDecl *Decl
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002007 = ClassTemplate->findSpecialization(Converted.data(), Converted.size(),
Douglas Gregor910f8002010-11-07 23:05:16 +00002008 InsertPos);
Douglas Gregor40808ce2009-03-09 23:48:35 +00002009 if (!Decl) {
2010 // This is the first time we have referenced this class template
2011 // specialization. Create the canonical declaration and add it to
2012 // the set of specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00002013 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor13c85772010-05-06 00:28:52 +00002014 ClassTemplate->getTemplatedDecl()->getTagKind(),
2015 ClassTemplate->getDeclContext(),
Abramo Bagnara09d82122011-10-03 20:34:03 +00002016 ClassTemplate->getTemplatedDecl()->getLocStart(),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002017 ClassTemplate->getLocation(),
Douglas Gregor910f8002010-11-07 23:05:16 +00002018 ClassTemplate,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002019 Converted.data(),
Douglas Gregor910f8002010-11-07 23:05:16 +00002020 Converted.size(), 0);
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00002021 ClassTemplate->AddSpecialization(Decl, InsertPos);
Douglas Gregor40808ce2009-03-09 23:48:35 +00002022 Decl->setLexicalDeclContext(CurContext);
2023 }
2024
2025 CanonType = Context.getTypeDeclType(Decl);
John McCall3cb0ebd2010-03-10 03:28:59 +00002026 assert(isa<RecordType>(CanonType) &&
2027 "type of non-dependent specialization is not a RecordType");
Douglas Gregor40808ce2009-03-09 23:48:35 +00002028 }
Mike Stump1eb44332009-09-09 15:08:12 +00002029
Douglas Gregor40808ce2009-03-09 23:48:35 +00002030 // Build the fully-sugared type for this class template
2031 // specialization, which refers back to the class template
2032 // specialization we created or found.
John McCall71d74bc2010-06-13 09:25:03 +00002033 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +00002034}
2035
John McCallf312b1e2010-08-26 23:41:50 +00002036TypeResult
Douglas Gregor059101f2011-03-02 00:47:37 +00002037Sema::ActOnTemplateIdType(CXXScopeSpec &SS,
2038 TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00002039 SourceLocation LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002040 ASTTemplateArgsPtr TemplateArgsIn,
John McCall6b2becf2009-09-08 17:47:29 +00002041 SourceLocation RAngleLoc) {
Douglas Gregor059101f2011-03-02 00:47:37 +00002042 if (SS.isInvalid())
2043 return true;
2044
Douglas Gregor7532dc62009-03-30 22:58:21 +00002045 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00002046
Douglas Gregor40808ce2009-03-09 23:48:35 +00002047 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00002048 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00002049 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002050
Douglas Gregora88f09f2011-02-28 17:23:35 +00002051 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2052 QualType T = Context.getDependentTemplateSpecializationType(ETK_None,
2053 DTN->getQualifier(),
2054 DTN->getIdentifier(),
2055 TemplateArgs);
2056
2057 // Build type-source information.
2058 TypeLocBuilder TLB;
2059 DependentTemplateSpecializationTypeLoc SpecTL
2060 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Douglas Gregor059101f2011-03-02 00:47:37 +00002061 SpecTL.setKeywordLoc(SourceLocation());
Douglas Gregora88f09f2011-02-28 17:23:35 +00002062 SpecTL.setNameLoc(TemplateLoc);
2063 SpecTL.setLAngleLoc(LAngleLoc);
2064 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor94fdffa2011-03-01 20:11:18 +00002065 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Douglas Gregora88f09f2011-02-28 17:23:35 +00002066 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2067 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2068 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2069 }
2070
John McCalld5532b62009-11-23 01:53:49 +00002071 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00002072 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00002073
2074 if (Result.isNull())
2075 return true;
2076
Douglas Gregor059101f2011-03-02 00:47:37 +00002077 // Build type-source information.
2078 TypeLocBuilder TLB;
2079 TemplateSpecializationTypeLoc SpecTL
2080 = TLB.push<TemplateSpecializationTypeLoc>(Result);
2081 SpecTL.setTemplateNameLoc(TemplateLoc);
2082 SpecTL.setLAngleLoc(LAngleLoc);
2083 SpecTL.setRAngleLoc(RAngleLoc);
2084 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2085 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall833ca992009-10-29 08:12:44 +00002086
Douglas Gregor059101f2011-03-02 00:47:37 +00002087 if (SS.isNotEmpty()) {
2088 // Create an elaborated-type-specifier containing the nested-name-specifier.
2089 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2090 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2091 ElabTL.setKeywordLoc(SourceLocation());
2092 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2093 }
2094
2095 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall6b2becf2009-09-08 17:47:29 +00002096}
John McCallf1bbbb42009-09-04 01:14:41 +00002097
Douglas Gregor059101f2011-03-02 00:47:37 +00002098TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallf312b1e2010-08-26 23:41:50 +00002099 TypeSpecifierType TagSpec,
Douglas Gregor059101f2011-03-02 00:47:37 +00002100 SourceLocation TagLoc,
2101 CXXScopeSpec &SS,
2102 TemplateTy TemplateD,
2103 SourceLocation TemplateLoc,
2104 SourceLocation LAngleLoc,
2105 ASTTemplateArgsPtr TemplateArgsIn,
2106 SourceLocation RAngleLoc) {
2107 TemplateName Template = TemplateD.getAsVal<TemplateName>();
2108
2109 // Translate the parser's template argument list in our AST format.
2110 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2111 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2112
2113 // Determine the tag kind
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002114 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregor059101f2011-03-02 00:47:37 +00002115 ElaboratedTypeKeyword Keyword
2116 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002117
Douglas Gregor059101f2011-03-02 00:47:37 +00002118 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2119 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2120 DTN->getQualifier(),
2121 DTN->getIdentifier(),
2122 TemplateArgs);
2123
2124 // Build type-source information.
2125 TypeLocBuilder TLB;
2126 DependentTemplateSpecializationTypeLoc SpecTL
2127 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2128 SpecTL.setKeywordLoc(TagLoc);
2129 SpecTL.setNameLoc(TemplateLoc);
2130 SpecTL.setLAngleLoc(LAngleLoc);
2131 SpecTL.setRAngleLoc(RAngleLoc);
2132 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
2133 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2134 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2135 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2136 }
Richard Smith3e4c6c42011-05-05 21:57:07 +00002137
2138 if (TypeAliasTemplateDecl *TAT =
2139 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2140 // C++0x [dcl.type.elab]p2:
2141 // If the identifier resolves to a typedef-name or the simple-template-id
2142 // resolves to an alias template specialization, the
2143 // elaborated-type-specifier is ill-formed.
2144 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2145 Diag(TAT->getLocation(), diag::note_declared_at);
2146 }
Douglas Gregor059101f2011-03-02 00:47:37 +00002147
2148 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2149 if (Result.isNull())
Matt Beaumont-Gay3a51d412011-08-25 23:22:24 +00002150 return TypeResult(true);
Douglas Gregor059101f2011-03-02 00:47:37 +00002151
2152 // Check the tag kind
2153 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCall6b2becf2009-09-08 17:47:29 +00002154 RecordDecl *D = RT->getDecl();
Douglas Gregor059101f2011-03-02 00:47:37 +00002155
John McCall6b2becf2009-09-08 17:47:29 +00002156 IdentifierInfo *Id = D->getIdentifier();
2157 assert(Id && "templated class must have an identifier");
Douglas Gregor059101f2011-03-02 00:47:37 +00002158
Richard Trieubbf34c02011-06-10 03:11:26 +00002159 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
2160 TagLoc, *Id)) {
John McCall6b2becf2009-09-08 17:47:29 +00002161 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregor059101f2011-03-02 00:47:37 +00002162 << Result
Douglas Gregor849b2432010-03-31 17:46:05 +00002163 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCallc4e70192009-09-11 04:59:25 +00002164 Diag(D->getLocation(), diag::note_previous_use);
John McCallf1bbbb42009-09-04 01:14:41 +00002165 }
2166 }
Douglas Gregor059101f2011-03-02 00:47:37 +00002167
2168 // Provide source-location information for the template specialization.
2169 TypeLocBuilder TLB;
2170 TemplateSpecializationTypeLoc SpecTL
2171 = TLB.push<TemplateSpecializationTypeLoc>(Result);
2172 SpecTL.setTemplateNameLoc(TemplateLoc);
2173 SpecTL.setLAngleLoc(LAngleLoc);
2174 SpecTL.setRAngleLoc(RAngleLoc);
2175 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2176 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCallf1bbbb42009-09-04 01:14:41 +00002177
Douglas Gregor059101f2011-03-02 00:47:37 +00002178 // Construct an elaborated type containing the nested-name-specifier (if any)
2179 // and keyword.
2180 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2181 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2182 ElabTL.setKeywordLoc(TagLoc);
2183 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2184 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor55f6b142009-02-09 18:46:07 +00002185}
2186
John McCall60d7b3a2010-08-24 06:29:42 +00002187ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Douglas Gregor4c9be892011-02-28 20:01:57 +00002188 LookupResult &R,
2189 bool RequiresADL,
John McCalld5532b62009-11-23 01:53:49 +00002190 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002191 // FIXME: Can we do any checking at this point? I guess we could check the
2192 // template arguments that we have against the template name, if the template
Mike Stump1eb44332009-09-09 15:08:12 +00002193 // name refers to a single template. That's not a terribly common case,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002194 // though.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00002195 // foo<int> could identify a single function unambiguously
2196 // This approach does NOT work, since f<int>(1);
2197 // gets resolved prior to resorting to overload resolution
2198 // i.e., template<class T> void f(double);
2199 // vs template<class T, class U> void f(U);
John McCallf7a1a742009-11-24 19:00:30 +00002200
2201 // These should be filtered out by our callers.
2202 assert(!R.empty() && "empty lookup results when building templateid");
2203 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
2204
John McCallc373d482010-01-27 01:50:18 +00002205 // We don't want lookup warnings at this point.
2206 R.suppressDiagnostics();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002207
John McCallf7a1a742009-11-24 19:00:30 +00002208 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002209 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002210 SS.getWithLocInContext(Context),
Abramo Bagnara25777432010-08-11 22:01:17 +00002211 R.getLookupNameInfo(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002212 RequiresADL, TemplateArgs,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002213 R.begin(), R.end());
John McCallf7a1a742009-11-24 19:00:30 +00002214
2215 return Owned(ULE);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002216}
2217
John McCallf7a1a742009-11-24 19:00:30 +00002218// We actually only call this from template instantiation.
John McCall60d7b3a2010-08-24 06:29:42 +00002219ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002220Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002221 const DeclarationNameInfo &NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +00002222 const TemplateArgumentListInfo &TemplateArgs) {
2223 DeclContext *DC;
2224 if (!(DC = computeDeclContext(SS, false)) ||
2225 DC->isDependentContext() ||
John McCall77bb1aa2010-05-01 00:40:08 +00002226 RequireCompleteDeclContext(SS, DC))
Abramo Bagnara25777432010-08-11 22:01:17 +00002227 return BuildDependentDeclRefExpr(SS, NameInfo, &TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002228
Douglas Gregor1fd6d442010-05-21 23:18:07 +00002229 bool MemberOfUnknownSpecialization;
Abramo Bagnara25777432010-08-11 22:01:17 +00002230 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Douglas Gregor1fd6d442010-05-21 23:18:07 +00002231 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
2232 MemberOfUnknownSpecialization);
Mike Stump1eb44332009-09-09 15:08:12 +00002233
John McCallf7a1a742009-11-24 19:00:30 +00002234 if (R.isAmbiguous())
2235 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002236
John McCallf7a1a742009-11-24 19:00:30 +00002237 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002238 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
2239 << NameInfo.getName() << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00002240 return ExprError();
2241 }
2242
2243 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002244 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
2245 << (NestedNameSpecifier*) SS.getScopeRep()
2246 << NameInfo.getName() << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00002247 Diag(Temp->getLocation(), diag::note_referenced_class_template);
2248 return ExprError();
2249 }
2250
2251 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002252}
2253
Douglas Gregorc45c2322009-03-31 00:43:58 +00002254/// \brief Form a dependent template name.
2255///
2256/// This action forms a dependent template name given the template
2257/// name and its (presumably dependent) scope specifier. For
2258/// example, given "MetaFun::template apply", the scope specifier \p
2259/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
2260/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002261TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregord6ab2322010-06-16 23:00:59 +00002262 SourceLocation TemplateKWLoc,
2263 CXXScopeSpec &SS,
2264 UnqualifiedId &Name,
John McCallb3d87482010-08-24 05:47:05 +00002265 ParsedType ObjectType,
Douglas Gregord6ab2322010-06-16 23:00:59 +00002266 bool EnteringContext,
2267 TemplateTy &Result) {
Richard Smithebaf0e62011-10-18 20:49:44 +00002268 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
2269 Diag(TemplateKWLoc,
2270 getLangOptions().CPlusPlus0x ?
2271 diag::warn_cxx98_compat_template_outside_of_template :
2272 diag::ext_template_outside_of_template)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002273 << FixItHint::CreateRemoval(TemplateKWLoc);
2274
Douglas Gregor0707bc52010-01-19 16:01:07 +00002275 DeclContext *LookupCtx = 0;
2276 if (SS.isSet())
2277 LookupCtx = computeDeclContext(SS, EnteringContext);
2278 if (!LookupCtx && ObjectType)
John McCallb3d87482010-08-24 05:47:05 +00002279 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor0707bc52010-01-19 16:01:07 +00002280 if (LookupCtx) {
Douglas Gregorc45c2322009-03-31 00:43:58 +00002281 // C++0x [temp.names]p5:
2282 // If a name prefixed by the keyword template is not the name of
2283 // a template, the program is ill-formed. [Note: the keyword
2284 // template may not be applied to non-template members of class
2285 // templates. -end note ] [ Note: as is the case with the
2286 // typename prefix, the template prefix is allowed in cases
2287 // where it is not strictly necessary; i.e., when the
2288 // nested-name-specifier or the expression on the left of the ->
2289 // or . is not dependent on a template-parameter, or the use
2290 // does not appear in the scope of a template. -end note]
2291 //
2292 // Note: C++03 was more strict here, because it banned the use of
2293 // the "template" keyword prior to a template-name that was not a
2294 // dependent name. C++ DR468 relaxed this requirement (the
2295 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregor732281d2010-06-14 22:07:54 +00002296 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00002297 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c153532010-08-06 12:11:11 +00002298 TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name,
2299 ObjectType, EnteringContext, Result,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00002300 MemberOfUnknownSpecialization);
Douglas Gregor0707bc52010-01-19 16:01:07 +00002301 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
2302 isa<CXXRecordDecl>(LookupCtx) &&
Douglas Gregord078bd22011-03-11 23:27:41 +00002303 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
2304 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
Douglas Gregord6ab2322010-06-16 23:00:59 +00002305 // This is a dependent template. Handle it below.
Douglas Gregor9edad9b2010-01-14 17:47:39 +00002306 } else if (TNK == TNK_Non_template) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002307 Diag(Name.getSourceRange().getBegin(),
Douglas Gregor014e88d2009-11-03 23:16:33 +00002308 diag::err_template_kw_refers_to_non_template)
Abramo Bagnara25777432010-08-11 22:01:17 +00002309 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregor0278e122010-05-05 05:58:24 +00002310 << Name.getSourceRange()
2311 << TemplateKWLoc;
Douglas Gregord6ab2322010-06-16 23:00:59 +00002312 return TNK_Non_template;
Douglas Gregor9edad9b2010-01-14 17:47:39 +00002313 } else {
2314 // We found something; return it.
Douglas Gregord6ab2322010-06-16 23:00:59 +00002315 return TNK;
Douglas Gregorc45c2322009-03-31 00:43:58 +00002316 }
Douglas Gregorc45c2322009-03-31 00:43:58 +00002317 }
2318
Mike Stump1eb44332009-09-09 15:08:12 +00002319 NestedNameSpecifier *Qualifier
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002320 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002321
Douglas Gregor014e88d2009-11-03 23:16:33 +00002322 switch (Name.getKind()) {
2323 case UnqualifiedId::IK_Identifier:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002324 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregord6ab2322010-06-16 23:00:59 +00002325 Name.Identifier));
2326 return TNK_Dependent_template_name;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002327
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002328 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregord6ab2322010-06-16 23:00:59 +00002329 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002330 Name.OperatorFunctionId.Operator));
Douglas Gregord6ab2322010-06-16 23:00:59 +00002331 return TNK_Dependent_template_name;
Sean Hunte6252d12009-11-28 08:58:14 +00002332
2333 case UnqualifiedId::IK_LiteralOperatorId:
David Blaikieb219cfc2011-09-23 05:06:16 +00002334 llvm_unreachable(
2335 "We don't support these; Parse shouldn't have allowed propagation");
Sean Hunte6252d12009-11-28 08:58:14 +00002336
Douglas Gregor014e88d2009-11-03 23:16:33 +00002337 default:
2338 break;
2339 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002340
2341 Diag(Name.getSourceRange().getBegin(),
Douglas Gregor014e88d2009-11-03 23:16:33 +00002342 diag::err_template_kw_refers_to_non_template)
Abramo Bagnara25777432010-08-11 22:01:17 +00002343 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregor0278e122010-05-05 05:58:24 +00002344 << Name.getSourceRange()
2345 << TemplateKWLoc;
Douglas Gregord6ab2322010-06-16 23:00:59 +00002346 return TNK_Non_template;
Douglas Gregorc45c2322009-03-31 00:43:58 +00002347}
2348
Mike Stump1eb44332009-09-09 15:08:12 +00002349bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00002350 const TemplateArgumentLoc &AL,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002351 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall833ca992009-10-29 08:12:44 +00002352 const TemplateArgument &Arg = AL.getArgument();
2353
Anders Carlsson436b1562009-06-13 00:33:33 +00002354 // Check template type parameter.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00002355 switch(Arg.getKind()) {
2356 case TemplateArgument::Type:
Anders Carlsson436b1562009-06-13 00:33:33 +00002357 // C++ [temp.arg.type]p1:
2358 // A template-argument for a template-parameter which is a
2359 // type shall be a type-id.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00002360 break;
2361 case TemplateArgument::Template: {
2362 // We have a template type parameter but the template argument
2363 // is a template without any arguments.
2364 SourceRange SR = AL.getSourceRange();
2365 TemplateName Name = Arg.getAsTemplate();
2366 Diag(SR.getBegin(), diag::err_template_missing_args)
2367 << Name << SR;
2368 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
2369 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlsson436b1562009-06-13 00:33:33 +00002370
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00002371 return true;
2372 }
2373 default: {
Anders Carlsson436b1562009-06-13 00:33:33 +00002374 // We have a template type parameter but the template argument
2375 // is not a type.
John McCall828bff22009-10-29 18:45:58 +00002376 SourceRange SR = AL.getSourceRange();
2377 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlsson436b1562009-06-13 00:33:33 +00002378 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00002379
Anders Carlsson436b1562009-06-13 00:33:33 +00002380 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002381 }
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00002382 }
Anders Carlsson436b1562009-06-13 00:33:33 +00002383
John McCalla93c9342009-12-07 02:54:59 +00002384 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlsson436b1562009-06-13 00:33:33 +00002385 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002386
Anders Carlsson436b1562009-06-13 00:33:33 +00002387 // Add the converted template type argument.
Douglas Gregore559ca12011-06-17 22:11:49 +00002388 QualType ArgType = Context.getCanonicalType(Arg.getAsType());
2389
2390 // Objective-C ARC:
2391 // If an explicitly-specified template argument type is a lifetime type
2392 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
2393 if (getLangOptions().ObjCAutoRefCount &&
2394 ArgType->isObjCLifetimeType() &&
2395 !ArgType.getObjCLifetime()) {
2396 Qualifiers Qs;
2397 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
2398 ArgType = Context.getQualifiedType(ArgType, Qs);
2399 }
2400
2401 Converted.push_back(TemplateArgument(ArgType));
Anders Carlsson436b1562009-06-13 00:33:33 +00002402 return false;
2403}
2404
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002405/// \brief Substitute template arguments into the default template argument for
2406/// the given template type parameter.
2407///
2408/// \param SemaRef the semantic analysis object for which we are performing
2409/// the substitution.
2410///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002411/// \param Template the template that we are synthesizing template arguments
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002412/// for.
2413///
2414/// \param TemplateLoc the location of the template name that started the
2415/// template-id we are checking.
2416///
2417/// \param RAngleLoc the location of the right angle bracket ('>') that
2418/// terminates the template-id.
2419///
2420/// \param Param the template template parameter whose default we are
2421/// substituting into.
2422///
2423/// \param Converted the list of template arguments provided for template
2424/// parameters that precede \p Param in the template parameter list.
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002425/// \returns the substituted template argument, or NULL if an error occurred.
John McCalla93c9342009-12-07 02:54:59 +00002426static TypeSourceInfo *
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002427SubstDefaultTemplateArgument(Sema &SemaRef,
2428 TemplateDecl *Template,
2429 SourceLocation TemplateLoc,
2430 SourceLocation RAngleLoc,
2431 TemplateTypeParmDecl *Param,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002432 SmallVectorImpl<TemplateArgument> &Converted) {
John McCalla93c9342009-12-07 02:54:59 +00002433 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002434
2435 // If the argument type is dependent, instantiate it now based
2436 // on the previously-computed template arguments.
2437 if (ArgType->getType()->isDependentType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002438 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor910f8002010-11-07 23:05:16 +00002439 Converted.data(), Converted.size());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002440
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002441 MultiLevelTemplateArgumentList AllTemplateArgs
2442 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2443
2444 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00002445 Template, Converted.data(),
2446 Converted.size(),
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002447 SourceRange(TemplateLoc, RAngleLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002448
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002449 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
2450 Param->getDefaultArgumentLoc(),
2451 Param->getDeclName());
2452 }
2453
2454 return ArgType;
2455}
2456
2457/// \brief Substitute template arguments into the default template argument for
2458/// the given non-type template parameter.
2459///
2460/// \param SemaRef the semantic analysis object for which we are performing
2461/// the substitution.
2462///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002463/// \param Template the template that we are synthesizing template arguments
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002464/// for.
2465///
2466/// \param TemplateLoc the location of the template name that started the
2467/// template-id we are checking.
2468///
2469/// \param RAngleLoc the location of the right angle bracket ('>') that
2470/// terminates the template-id.
2471///
Douglas Gregor788cd062009-11-11 01:00:40 +00002472/// \param Param the non-type template parameter whose default we are
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002473/// substituting into.
2474///
2475/// \param Converted the list of template arguments provided for template
2476/// parameters that precede \p Param in the template parameter list.
2477///
2478/// \returns the substituted template argument, or NULL if an error occurred.
John McCall60d7b3a2010-08-24 06:29:42 +00002479static ExprResult
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002480SubstDefaultTemplateArgument(Sema &SemaRef,
2481 TemplateDecl *Template,
2482 SourceLocation TemplateLoc,
2483 SourceLocation RAngleLoc,
2484 NonTypeTemplateParmDecl *Param,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002485 SmallVectorImpl<TemplateArgument> &Converted) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002486 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor910f8002010-11-07 23:05:16 +00002487 Converted.data(), Converted.size());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002488
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002489 MultiLevelTemplateArgumentList AllTemplateArgs
2490 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002491
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002492 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00002493 Template, Converted.data(),
2494 Converted.size(),
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002495 SourceRange(TemplateLoc, RAngleLoc));
2496
2497 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
2498}
2499
Douglas Gregor788cd062009-11-11 01:00:40 +00002500/// \brief Substitute template arguments into the default template argument for
2501/// the given template template parameter.
2502///
2503/// \param SemaRef the semantic analysis object for which we are performing
2504/// the substitution.
2505///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002506/// \param Template the template that we are synthesizing template arguments
Douglas Gregor788cd062009-11-11 01:00:40 +00002507/// for.
2508///
2509/// \param TemplateLoc the location of the template name that started the
2510/// template-id we are checking.
2511///
2512/// \param RAngleLoc the location of the right angle bracket ('>') that
2513/// terminates the template-id.
2514///
2515/// \param Param the template template parameter whose default we are
2516/// substituting into.
2517///
2518/// \param Converted the list of template arguments provided for template
2519/// parameters that precede \p Param in the template parameter list.
2520///
Douglas Gregor1d752d72011-03-02 18:46:51 +00002521/// \param QualifierLoc Will be set to the nested-name-specifier (with
2522/// source-location information) that precedes the template name.
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002523///
Douglas Gregor788cd062009-11-11 01:00:40 +00002524/// \returns the substituted template argument, or NULL if an error occurred.
2525static TemplateName
2526SubstDefaultTemplateArgument(Sema &SemaRef,
2527 TemplateDecl *Template,
2528 SourceLocation TemplateLoc,
2529 SourceLocation RAngleLoc,
2530 TemplateTemplateParmDecl *Param,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002531 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002532 NestedNameSpecifierLoc &QualifierLoc) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002533 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor910f8002010-11-07 23:05:16 +00002534 Converted.data(), Converted.size());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002535
Douglas Gregor788cd062009-11-11 01:00:40 +00002536 MultiLevelTemplateArgumentList AllTemplateArgs
2537 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002538
Douglas Gregor788cd062009-11-11 01:00:40 +00002539 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00002540 Template, Converted.data(),
2541 Converted.size(),
Douglas Gregor788cd062009-11-11 01:00:40 +00002542 SourceRange(TemplateLoc, RAngleLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002543
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002544 // Substitute into the nested-name-specifier first,
Douglas Gregor1d752d72011-03-02 18:46:51 +00002545 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002546 if (QualifierLoc) {
2547 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2548 AllTemplateArgs);
2549 if (!QualifierLoc)
2550 return TemplateName();
2551 }
2552
Douglas Gregor1d752d72011-03-02 18:46:51 +00002553 return SemaRef.SubstTemplateName(QualifierLoc,
Douglas Gregor788cd062009-11-11 01:00:40 +00002554 Param->getDefaultArgument().getArgument().getAsTemplate(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002555 Param->getDefaultArgument().getTemplateNameLoc(),
Douglas Gregor788cd062009-11-11 01:00:40 +00002556 AllTemplateArgs);
2557}
2558
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002559/// \brief If the given template parameter has a default template
2560/// argument, substitute into that default template argument and
2561/// return the corresponding template argument.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002562TemplateArgumentLoc
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002563Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
2564 SourceLocation TemplateLoc,
2565 SourceLocation RAngleLoc,
2566 Decl *Param,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002567 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor910f8002010-11-07 23:05:16 +00002568 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002569 if (!TypeParm->hasDefaultArgument())
2570 return TemplateArgumentLoc();
2571
John McCalla93c9342009-12-07 02:54:59 +00002572 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002573 TemplateLoc,
2574 RAngleLoc,
2575 TypeParm,
2576 Converted);
2577 if (DI)
2578 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
2579
2580 return TemplateArgumentLoc();
2581 }
2582
2583 if (NonTypeTemplateParmDecl *NonTypeParm
2584 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2585 if (!NonTypeParm->hasDefaultArgument())
2586 return TemplateArgumentLoc();
2587
John McCall60d7b3a2010-08-24 06:29:42 +00002588 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002589 TemplateLoc,
2590 RAngleLoc,
2591 NonTypeParm,
2592 Converted);
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002593 if (Arg.isInvalid())
2594 return TemplateArgumentLoc();
2595
2596 Expr *ArgE = Arg.takeAs<Expr>();
2597 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
2598 }
2599
2600 TemplateTemplateParmDecl *TempTempParm
2601 = cast<TemplateTemplateParmDecl>(Param);
2602 if (!TempTempParm->hasDefaultArgument())
2603 return TemplateArgumentLoc();
2604
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002605
Douglas Gregor1d752d72011-03-02 18:46:51 +00002606 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002607 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002608 TemplateLoc,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002609 RAngleLoc,
2610 TempTempParm,
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002611 Converted,
2612 QualifierLoc);
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002613 if (TName.isNull())
2614 return TemplateArgumentLoc();
2615
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002616 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002617 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002618 TempTempParm->getDefaultArgument().getTemplateNameLoc());
2619}
2620
Douglas Gregore7526412009-11-11 19:31:23 +00002621/// \brief Check that the given template argument corresponds to the given
2622/// template parameter.
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002623///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002624/// \param Param The template parameter against which the argument will be
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002625/// checked.
2626///
2627/// \param Arg The template argument.
2628///
2629/// \param Template The template in which the template argument resides.
2630///
2631/// \param TemplateLoc The location of the template name for the template
2632/// whose argument list we're matching.
2633///
2634/// \param RAngleLoc The location of the right angle bracket ('>') that closes
2635/// the template argument list.
2636///
2637/// \param ArgumentPackIndex The index into the argument pack where this
2638/// argument will be placed. Only valid if the parameter is a parameter pack.
2639///
2640/// \param Converted The checked, converted argument will be added to the
2641/// end of this small vector.
2642///
2643/// \param CTAK Describes how we arrived at this particular template argument:
2644/// explicitly written, deduced, etc.
2645///
2646/// \returns true on error, false otherwise.
Douglas Gregore7526412009-11-11 19:31:23 +00002647bool Sema::CheckTemplateArgument(NamedDecl *Param,
2648 const TemplateArgumentLoc &Arg,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002649 NamedDecl *Template,
Douglas Gregore7526412009-11-11 19:31:23 +00002650 SourceLocation TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002651 SourceLocation RAngleLoc,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002652 unsigned ArgumentPackIndex,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002653 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor02024a92010-03-28 02:42:43 +00002654 CheckTemplateArgumentKind CTAK) {
Douglas Gregord9e15302009-11-11 19:41:09 +00002655 // Check template type parameters.
2656 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregore7526412009-11-11 19:31:23 +00002657 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002658
Douglas Gregord9e15302009-11-11 19:41:09 +00002659 // Check non-type template parameters.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002660 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregore7526412009-11-11 19:31:23 +00002661 // Do substitution on the type of the non-type template parameter
Peter Collingbourne9f6f6a12010-12-10 17:08:53 +00002662 // with the template arguments we've seen thus far. But if the
2663 // template has a dependent context then we cannot substitute yet.
Douglas Gregore7526412009-11-11 19:31:23 +00002664 QualType NTTPType = NTTP->getType();
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002665 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
2666 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002667
Peter Collingbourne9f6f6a12010-12-10 17:08:53 +00002668 if (NTTPType->isDependentType() &&
2669 !isa<TemplateTemplateParmDecl>(Template) &&
2670 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregore7526412009-11-11 19:31:23 +00002671 // Do substitution on the type of the non-type template parameter.
2672 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Douglas Gregor910f8002010-11-07 23:05:16 +00002673 NTTP, Converted.data(), Converted.size(),
Douglas Gregore7526412009-11-11 19:31:23 +00002674 SourceRange(TemplateLoc, RAngleLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002675
2676 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor910f8002010-11-07 23:05:16 +00002677 Converted.data(), Converted.size());
Douglas Gregore7526412009-11-11 19:31:23 +00002678 NTTPType = SubstType(NTTPType,
2679 MultiLevelTemplateArgumentList(TemplateArgs),
2680 NTTP->getLocation(),
2681 NTTP->getDeclName());
2682 // If that worked, check the non-type template parameter type
2683 // for validity.
2684 if (!NTTPType.isNull())
2685 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2686 NTTP->getLocation());
2687 if (NTTPType.isNull())
2688 return true;
2689 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002690
Douglas Gregore7526412009-11-11 19:31:23 +00002691 switch (Arg.getArgument().getKind()) {
2692 case TemplateArgument::Null:
David Blaikieb219cfc2011-09-23 05:06:16 +00002693 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002694
Douglas Gregore7526412009-11-11 19:31:23 +00002695 case TemplateArgument::Expression: {
Douglas Gregore7526412009-11-11 19:31:23 +00002696 TemplateArgument Result;
John Wiegley429bb272011-04-08 18:41:53 +00002697 ExprResult Res =
2698 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
2699 Result, CTAK);
2700 if (Res.isInvalid())
Douglas Gregore7526412009-11-11 19:31:23 +00002701 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002702
Douglas Gregor910f8002010-11-07 23:05:16 +00002703 Converted.push_back(Result);
Douglas Gregore7526412009-11-11 19:31:23 +00002704 break;
2705 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002706
Douglas Gregore7526412009-11-11 19:31:23 +00002707 case TemplateArgument::Declaration:
2708 case TemplateArgument::Integral:
2709 // We've already checked this template argument, so just copy
2710 // it to the list of converted arguments.
Douglas Gregor910f8002010-11-07 23:05:16 +00002711 Converted.push_back(Arg.getArgument());
Douglas Gregore7526412009-11-11 19:31:23 +00002712 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002713
Douglas Gregore7526412009-11-11 19:31:23 +00002714 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00002715 case TemplateArgument::TemplateExpansion:
Douglas Gregore7526412009-11-11 19:31:23 +00002716 // We were given a template template argument. It may not be ill-formed;
2717 // see below.
2718 if (DependentTemplateName *DTN
Douglas Gregora7fc9012011-01-05 18:58:31 +00002719 = Arg.getArgument().getAsTemplateOrTemplatePattern()
2720 .getAsDependentTemplateName()) {
Douglas Gregore7526412009-11-11 19:31:23 +00002721 // We have a template argument such as \c T::template X, which we
2722 // parsed as a template template argument. However, since we now
2723 // know that we need a non-type template argument, convert this
Abramo Bagnara25777432010-08-11 22:01:17 +00002724 // template name into an expression.
2725
2726 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
2727 Arg.getTemplateNameLoc());
2728
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00002729 CXXScopeSpec SS;
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002730 SS.Adopt(Arg.getTemplateQualifierLoc());
John Wiegley429bb272011-04-08 18:41:53 +00002731 ExprResult E = Owned(DependentScopeDeclRefExpr::Create(Context,
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00002732 SS.getWithLocInContext(Context),
John Wiegley429bb272011-04-08 18:41:53 +00002733 NameInfo));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002734
Douglas Gregora7fc9012011-01-05 18:58:31 +00002735 // If we parsed the template argument as a pack expansion, create a
2736 // pack expansion expression.
2737 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
John Wiegley429bb272011-04-08 18:41:53 +00002738 E = ActOnPackExpansion(E.take(), Arg.getTemplateEllipsisLoc());
2739 if (E.isInvalid())
Douglas Gregora7fc9012011-01-05 18:58:31 +00002740 return true;
Douglas Gregora7fc9012011-01-05 18:58:31 +00002741 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002742
Douglas Gregore7526412009-11-11 19:31:23 +00002743 TemplateArgument Result;
John Wiegley429bb272011-04-08 18:41:53 +00002744 E = CheckTemplateArgument(NTTP, NTTPType, E.take(), Result);
2745 if (E.isInvalid())
Douglas Gregore7526412009-11-11 19:31:23 +00002746 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002747
Douglas Gregor910f8002010-11-07 23:05:16 +00002748 Converted.push_back(Result);
Douglas Gregore7526412009-11-11 19:31:23 +00002749 break;
2750 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002751
Douglas Gregore7526412009-11-11 19:31:23 +00002752 // We have a template argument that actually does refer to a class
Richard Smith3e4c6c42011-05-05 21:57:07 +00002753 // template, alias template, or template template parameter, and
Douglas Gregore7526412009-11-11 19:31:23 +00002754 // therefore cannot be a non-type template argument.
2755 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2756 << Arg.getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002757
Douglas Gregore7526412009-11-11 19:31:23 +00002758 Diag(Param->getLocation(), diag::note_template_param_here);
2759 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002760
Douglas Gregore7526412009-11-11 19:31:23 +00002761 case TemplateArgument::Type: {
2762 // We have a non-type template parameter but the template
2763 // argument is a type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002764
Douglas Gregore7526412009-11-11 19:31:23 +00002765 // C++ [temp.arg]p2:
2766 // In a template-argument, an ambiguity between a type-id and
2767 // an expression is resolved to a type-id, regardless of the
2768 // form of the corresponding template-parameter.
2769 //
2770 // We warn specifically about this case, since it can be rather
2771 // confusing for users.
2772 QualType T = Arg.getArgument().getAsType();
2773 SourceRange SR = Arg.getSourceRange();
2774 if (T->isFunctionType())
2775 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2776 else
2777 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2778 Diag(Param->getLocation(), diag::note_template_param_here);
2779 return true;
2780 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002781
Douglas Gregore7526412009-11-11 19:31:23 +00002782 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002783 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002784 break;
2785 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002786
Douglas Gregore7526412009-11-11 19:31:23 +00002787 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002788 }
2789
2790
Douglas Gregore7526412009-11-11 19:31:23 +00002791 // Check template template parameters.
2792 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002793
Douglas Gregore7526412009-11-11 19:31:23 +00002794 // Substitute into the template parameter list of the template
2795 // template parameter, since previously-supplied template arguments
2796 // may appear within the template template parameter.
2797 {
2798 // Set up a template instantiation context.
2799 LocalInstantiationScope Scope(*this);
2800 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Douglas Gregor910f8002010-11-07 23:05:16 +00002801 TempParm, Converted.data(), Converted.size(),
Douglas Gregore7526412009-11-11 19:31:23 +00002802 SourceRange(TemplateLoc, RAngleLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002803
2804 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor910f8002010-11-07 23:05:16 +00002805 Converted.data(), Converted.size());
Douglas Gregore7526412009-11-11 19:31:23 +00002806 TempParm = cast_or_null<TemplateTemplateParmDecl>(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002807 SubstDecl(TempParm, CurContext,
Douglas Gregore7526412009-11-11 19:31:23 +00002808 MultiLevelTemplateArgumentList(TemplateArgs)));
2809 if (!TempParm)
2810 return true;
Douglas Gregore7526412009-11-11 19:31:23 +00002811 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002812
Douglas Gregore7526412009-11-11 19:31:23 +00002813 switch (Arg.getArgument().getKind()) {
2814 case TemplateArgument::Null:
David Blaikieb219cfc2011-09-23 05:06:16 +00002815 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002816
Douglas Gregore7526412009-11-11 19:31:23 +00002817 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00002818 case TemplateArgument::TemplateExpansion:
Douglas Gregore7526412009-11-11 19:31:23 +00002819 if (CheckTemplateArgument(TempParm, Arg))
2820 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002821
Douglas Gregor910f8002010-11-07 23:05:16 +00002822 Converted.push_back(Arg.getArgument());
Douglas Gregore7526412009-11-11 19:31:23 +00002823 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002824
Douglas Gregore7526412009-11-11 19:31:23 +00002825 case TemplateArgument::Expression:
2826 case TemplateArgument::Type:
2827 // We have a template template parameter but the template
2828 // argument does not refer to a template.
Richard Smith3e4c6c42011-05-05 21:57:07 +00002829 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
2830 << getLangOptions().CPlusPlus0x;
Douglas Gregore7526412009-11-11 19:31:23 +00002831 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002832
Douglas Gregore7526412009-11-11 19:31:23 +00002833 case TemplateArgument::Declaration:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002834 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002835 "Declaration argument with template template parameter");
2836 break;
2837 case TemplateArgument::Integral:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002838 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002839 "Integral argument with template template parameter");
2840 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002841
Douglas Gregore7526412009-11-11 19:31:23 +00002842 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002843 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002844 break;
2845 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002846
Douglas Gregore7526412009-11-11 19:31:23 +00002847 return false;
2848}
2849
Douglas Gregorc15cb382009-02-09 23:23:08 +00002850/// \brief Check that the given template argument list is well-formed
2851/// for specializing the given template.
2852bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2853 SourceLocation TemplateLoc,
Douglas Gregor67714232011-03-03 02:41:12 +00002854 TemplateArgumentListInfo &TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00002855 bool PartialTemplateArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002856 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002857 TemplateParameterList *Params = Template->getTemplateParameters();
2858 unsigned NumParams = Params->size();
John McCalld5532b62009-11-23 01:53:49 +00002859 unsigned NumArgs = TemplateArgs.size();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002860 bool Invalid = false;
2861
John McCalld5532b62009-11-23 01:53:49 +00002862 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2863
Mike Stump1eb44332009-09-09 15:08:12 +00002864 bool HasParameterPack =
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002865 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump1eb44332009-09-09 15:08:12 +00002866
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002867 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00002868 (NumArgs < Params->getMinRequiredArguments() &&
2869 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002870 // FIXME: point at either the first arg beyond what we can handle,
2871 // or the '>', depending on whether we have too many or too few
2872 // arguments.
2873 SourceRange Range;
2874 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00002875 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002876 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2877 << (NumArgs > NumParams)
2878 << (isa<ClassTemplateDecl>(Template)? 0 :
2879 isa<FunctionTemplateDecl>(Template)? 1 :
2880 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2881 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00002882 Diag(Template->getLocation(), diag::note_template_decl_here)
2883 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002884 Invalid = true;
2885 }
Mike Stump1eb44332009-09-09 15:08:12 +00002886
2887 // C++ [temp.arg]p1:
Douglas Gregorc15cb382009-02-09 23:23:08 +00002888 // [...] The type and form of each template-argument specified in
2889 // a template-id shall match the type and form specified for the
2890 // corresponding parameter declared by the template in its
2891 // template-parameter-list.
Douglas Gregor67714232011-03-03 02:41:12 +00002892 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002893 SmallVector<TemplateArgument, 2> ArgumentPack;
Douglas Gregor14be16b2010-12-20 16:57:52 +00002894 TemplateParameterList::iterator Param = Params->begin(),
2895 ParamEnd = Params->end();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002896 unsigned ArgIdx = 0;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00002897 LocalInstantiationScope InstScope(*this, true);
Douglas Gregor14be16b2010-12-20 16:57:52 +00002898 while (Param != ParamEnd) {
Douglas Gregorf35f8282009-11-11 21:54:23 +00002899 if (ArgIdx < NumArgs) {
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002900 // If we have an expanded parameter pack, make sure we don't have too
2901 // many arguments.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002902 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002903 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002904 if (NTTP->isExpandedParameterPack() &&
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002905 ArgumentPack.size() >= NTTP->getNumExpansionTypes()) {
2906 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2907 << true
2908 << (isa<ClassTemplateDecl>(Template)? 0 :
2909 isa<FunctionTemplateDecl>(Template)? 1 :
2910 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2911 << Template;
2912 Diag(Template->getLocation(), diag::note_template_decl_here)
2913 << Params->getSourceRange();
2914 return true;
2915 }
2916 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002917
Douglas Gregorf35f8282009-11-11 21:54:23 +00002918 // Check the template argument we were given.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002919 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2920 TemplateLoc, RAngleLoc,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002921 ArgumentPack.size(), Converted))
Douglas Gregorf35f8282009-11-11 21:54:23 +00002922 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002923
Douglas Gregor14be16b2010-12-20 16:57:52 +00002924 if ((*Param)->isTemplateParameterPack()) {
2925 // The template parameter was a template parameter pack, so take the
2926 // deduced argument and place it on the argument pack. Note that we
2927 // stay on the same template parameter so that we can deduce more
2928 // arguments.
2929 ArgumentPack.push_back(Converted.back());
2930 Converted.pop_back();
2931 } else {
2932 // Move to the next template parameter.
2933 ++Param;
2934 }
2935 ++ArgIdx;
Douglas Gregorf35f8282009-11-11 21:54:23 +00002936 continue;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002937 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002938
Douglas Gregor8735b292011-06-03 02:59:40 +00002939 // If we're checking a partial template argument list, we're done.
2940 if (PartialTemplateArgs) {
2941 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
2942 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
2943 ArgumentPack.data(),
2944 ArgumentPack.size()));
2945
2946 return Invalid;
2947 }
2948
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002949 // If we have a template parameter pack with no more corresponding
Douglas Gregor14be16b2010-12-20 16:57:52 +00002950 // arguments, just break out now and we'll fill in the argument pack below.
2951 if ((*Param)->isTemplateParameterPack())
2952 break;
Douglas Gregorf968d832011-05-27 01:19:52 +00002953
Douglas Gregorf35f8282009-11-11 21:54:23 +00002954 // We have a default template argument that we will use.
2955 TemplateArgumentLoc Arg;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002956
Douglas Gregorf35f8282009-11-11 21:54:23 +00002957 // Retrieve the default template argument from the template
2958 // parameter. For each kind of template parameter, we substitute the
2959 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002960 // (when the template parameter was part of a nested template) into
Douglas Gregorf35f8282009-11-11 21:54:23 +00002961 // the default argument.
2962 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2963 if (!TTP->hasDefaultArgument()) {
Douglas Gregor8735b292011-06-03 02:59:40 +00002964 assert(Invalid && "Missing default argument");
Douglas Gregorf35f8282009-11-11 21:54:23 +00002965 break;
2966 }
2967
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002968 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002969 Template,
2970 TemplateLoc,
2971 RAngleLoc,
2972 TTP,
2973 Converted);
2974 if (!ArgType)
2975 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002976
Douglas Gregorf35f8282009-11-11 21:54:23 +00002977 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2978 ArgType);
2979 } else if (NonTypeTemplateParmDecl *NTTP
2980 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2981 if (!NTTP->hasDefaultArgument()) {
Douglas Gregor8735b292011-06-03 02:59:40 +00002982 assert(Invalid && "Missing default argument");
Douglas Gregorf35f8282009-11-11 21:54:23 +00002983 break;
2984 }
2985
John McCall60d7b3a2010-08-24 06:29:42 +00002986 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002987 TemplateLoc,
2988 RAngleLoc,
2989 NTTP,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002990 Converted);
2991 if (E.isInvalid())
2992 return true;
2993
2994 Expr *Ex = E.takeAs<Expr>();
2995 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2996 } else {
2997 TemplateTemplateParmDecl *TempParm
2998 = cast<TemplateTemplateParmDecl>(*Param);
2999
3000 if (!TempParm->hasDefaultArgument()) {
Douglas Gregor8735b292011-06-03 02:59:40 +00003001 assert(Invalid && "Missing default argument");
Douglas Gregorf35f8282009-11-11 21:54:23 +00003002 break;
3003 }
3004
Douglas Gregor1d752d72011-03-02 18:46:51 +00003005 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregorf35f8282009-11-11 21:54:23 +00003006 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003007 TemplateLoc,
3008 RAngleLoc,
Douglas Gregorf35f8282009-11-11 21:54:23 +00003009 TempParm,
Douglas Gregorb6744ef2011-03-02 17:09:35 +00003010 Converted,
3011 QualifierLoc);
Douglas Gregorf35f8282009-11-11 21:54:23 +00003012 if (Name.isNull())
3013 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003014
Douglas Gregorb6744ef2011-03-02 17:09:35 +00003015 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
3016 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregorf35f8282009-11-11 21:54:23 +00003017 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003018
Douglas Gregorf35f8282009-11-11 21:54:23 +00003019 // Introduce an instantiation record that describes where we are using
3020 // the default template argument.
3021 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00003022 Converted.data(), Converted.size(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003023 SourceRange(TemplateLoc, RAngleLoc));
3024
Douglas Gregorf35f8282009-11-11 21:54:23 +00003025 // Check the default template argument.
Douglas Gregord9e15302009-11-11 19:41:09 +00003026 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00003027 RAngleLoc, 0, Converted))
Douglas Gregore7526412009-11-11 19:31:23 +00003028 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003029
Douglas Gregor67714232011-03-03 02:41:12 +00003030 // Core issue 150 (assumed resolution): if this is a template template
3031 // parameter, keep track of the default template arguments from the
3032 // template definition.
3033 if (isTemplateTemplateParameter)
3034 TemplateArgs.addArgument(Arg);
3035
Douglas Gregor14be16b2010-12-20 16:57:52 +00003036 // Move to the next template parameter and argument.
3037 ++Param;
3038 ++ArgIdx;
Douglas Gregorc15cb382009-02-09 23:23:08 +00003039 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003040
Douglas Gregor14be16b2010-12-20 16:57:52 +00003041 // Form argument packs for each of the parameter packs remaining.
3042 while (Param != ParamEnd) {
Douglas Gregord3731192011-01-10 07:32:04 +00003043 // If we're checking a partial list of template arguments, don't fill
3044 // in arguments for non-template parameter packs.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003045
3046 if ((*Param)->isTemplateParameterPack()) {
David Blaikie1368e582011-10-19 05:19:50 +00003047 if (!HasParameterPack)
3048 return true;
Douglas Gregor8735b292011-06-03 02:59:40 +00003049 if (ArgumentPack.empty())
Douglas Gregor14be16b2010-12-20 16:57:52 +00003050 Converted.push_back(TemplateArgument(0, 0));
Douglas Gregor203e6a32011-01-11 23:09:57 +00003051 else {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003052 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3053 ArgumentPack.data(),
Douglas Gregor203e6a32011-01-11 23:09:57 +00003054 ArgumentPack.size()));
Douglas Gregor14be16b2010-12-20 16:57:52 +00003055 ArgumentPack.clear();
3056 }
3057 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003058
Douglas Gregor14be16b2010-12-20 16:57:52 +00003059 ++Param;
3060 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003061
Douglas Gregorc15cb382009-02-09 23:23:08 +00003062 return Invalid;
3063}
3064
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003065namespace {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003066 class UnnamedLocalNoLinkageFinder
3067 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003068 {
3069 Sema &S;
3070 SourceRange SR;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003071
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003072 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003073
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003074 public:
3075 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
3076
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003077 bool Visit(QualType T) {
3078 return inherited::Visit(T.getTypePtr());
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003079 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003080
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003081#define TYPE(Class, Parent) \
3082 bool Visit##Class##Type(const Class##Type *);
3083#define ABSTRACT_TYPE(Class, Parent) \
3084 bool Visit##Class##Type(const Class##Type *) { return false; }
3085#define NON_CANONICAL_TYPE(Class, Parent) \
3086 bool Visit##Class##Type(const Class##Type *) { return false; }
3087#include "clang/AST/TypeNodes.def"
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003088
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003089 bool VisitTagDecl(const TagDecl *Tag);
3090 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
3091 };
3092}
3093
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003094bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003095 return false;
3096}
3097
3098bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
3099 return Visit(T->getElementType());
3100}
3101
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003102bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003103 return Visit(T->getPointeeType());
3104}
3105
3106bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003107 const BlockPointerType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003108 return Visit(T->getPointeeType());
3109}
3110
3111bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003112 const LValueReferenceType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003113 return Visit(T->getPointeeType());
3114}
3115
3116bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003117 const RValueReferenceType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003118 return Visit(T->getPointeeType());
3119}
3120
3121bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003122 const MemberPointerType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003123 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
3124}
3125
3126bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003127 const ConstantArrayType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003128 return Visit(T->getElementType());
3129}
3130
3131bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003132 const IncompleteArrayType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003133 return Visit(T->getElementType());
3134}
3135
3136bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003137 const VariableArrayType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003138 return Visit(T->getElementType());
3139}
3140
3141bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003142 const DependentSizedArrayType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003143 return Visit(T->getElementType());
3144}
3145
3146bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003147 const DependentSizedExtVectorType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003148 return Visit(T->getElementType());
3149}
3150
3151bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
3152 return Visit(T->getElementType());
3153}
3154
3155bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
3156 return Visit(T->getElementType());
3157}
3158
3159bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
3160 const FunctionProtoType* T) {
3161 for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003162 AEnd = T->arg_type_end();
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003163 A != AEnd; ++A) {
3164 if (Visit(*A))
3165 return true;
3166 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003167
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003168 return Visit(T->getResultType());
3169}
3170
3171bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
3172 const FunctionNoProtoType* T) {
3173 return Visit(T->getResultType());
3174}
3175
3176bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
3177 const UnresolvedUsingType*) {
3178 return false;
3179}
3180
3181bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
3182 return false;
3183}
3184
3185bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
3186 return Visit(T->getUnderlyingType());
3187}
3188
3189bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
3190 return false;
3191}
3192
Sean Huntca63c202011-05-24 22:41:36 +00003193bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
3194 const UnaryTransformType*) {
3195 return false;
3196}
3197
Richard Smith34b41d92011-02-20 03:19:35 +00003198bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
3199 return Visit(T->getDeducedType());
3200}
3201
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003202bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
3203 return VisitTagDecl(T->getDecl());
3204}
3205
3206bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
3207 return VisitTagDecl(T->getDecl());
3208}
3209
3210bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
3211 const TemplateTypeParmType*) {
3212 return false;
3213}
3214
Douglas Gregorc3069d62011-01-14 02:55:32 +00003215bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
3216 const SubstTemplateTypeParmPackType *) {
3217 return false;
3218}
3219
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003220bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
3221 const TemplateSpecializationType*) {
3222 return false;
3223}
3224
3225bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
3226 const InjectedClassNameType* T) {
3227 return VisitTagDecl(T->getDecl());
3228}
3229
3230bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
3231 const DependentNameType* T) {
3232 return VisitNestedNameSpecifier(T->getQualifier());
3233}
3234
3235bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
3236 const DependentTemplateSpecializationType* T) {
3237 return VisitNestedNameSpecifier(T->getQualifier());
3238}
3239
Douglas Gregor7536dd52010-12-20 02:24:11 +00003240bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
3241 const PackExpansionType* T) {
3242 return Visit(T->getPattern());
3243}
3244
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003245bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
3246 return false;
3247}
3248
3249bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
3250 const ObjCInterfaceType *) {
3251 return false;
3252}
3253
3254bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
3255 const ObjCObjectPointerType *) {
3256 return false;
3257}
3258
Eli Friedmanb001de72011-10-06 23:00:33 +00003259bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
3260 return Visit(T->getValueType());
3261}
3262
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003263bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
3264 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smithebaf0e62011-10-18 20:49:44 +00003265 S.Diag(SR.getBegin(),
3266 S.getLangOptions().CPlusPlus0x ?
3267 diag::warn_cxx98_compat_template_arg_local_type :
3268 diag::ext_template_arg_local_type)
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003269 << S.Context.getTypeDeclType(Tag) << SR;
3270 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003271 }
3272
Richard Smith162e1c12011-04-15 14:24:37 +00003273 if (!Tag->getDeclName() && !Tag->getTypedefNameForAnonDecl()) {
Richard Smithebaf0e62011-10-18 20:49:44 +00003274 S.Diag(SR.getBegin(),
3275 S.getLangOptions().CPlusPlus0x ?
3276 diag::warn_cxx98_compat_template_arg_unnamed_type :
3277 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003278 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
3279 return true;
3280 }
3281
3282 return false;
3283}
3284
3285bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
3286 NestedNameSpecifier *NNS) {
3287 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
3288 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003289
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003290 switch (NNS->getKind()) {
3291 case NestedNameSpecifier::Identifier:
3292 case NestedNameSpecifier::Namespace:
Douglas Gregor14aba762011-02-24 02:36:08 +00003293 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003294 case NestedNameSpecifier::Global:
3295 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003296
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003297 case NestedNameSpecifier::TypeSpec:
3298 case NestedNameSpecifier::TypeSpecWithTemplate:
3299 return Visit(QualType(NNS->getAsType(), 0));
3300 }
Fariborz Jahanian7b1ec6c2010-10-13 16:19:16 +00003301 return false;
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003302}
3303
3304
Douglas Gregorc15cb382009-02-09 23:23:08 +00003305/// \brief Check a template argument against its corresponding
3306/// template type parameter.
3307///
3308/// This routine implements the semantics of C++ [temp.arg.type]. It
3309/// returns true if an error occurred, and false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00003310bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCalla93c9342009-12-07 02:54:59 +00003311 TypeSourceInfo *ArgInfo) {
3312 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall833ca992009-10-29 08:12:44 +00003313 QualType Arg = ArgInfo->getType();
Douglas Gregor0fddb972010-05-22 16:17:30 +00003314 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth17fb8552010-09-03 21:12:34 +00003315
3316 if (Arg->isVariablyModifiedType()) {
3317 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor4b52e252009-12-21 23:17:24 +00003318 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00003319 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00003320 }
3321
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003322 // C++03 [temp.arg.type]p2:
3323 // A local type, a type with no linkage, an unnamed type or a type
3324 // compounded from any of these types shall not be used as a
3325 // template-argument for a template type-parameter.
3326 //
Richard Smithebaf0e62011-10-18 20:49:44 +00003327 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003328 // a warning.
Richard Smithebaf0e62011-10-18 20:49:44 +00003329 if (LangOpts.CPlusPlus0x ?
3330 Diags.getDiagnosticLevel(diag::warn_cxx98_compat_template_arg_unnamed_type,
3331 SR.getBegin()) != DiagnosticsEngine::Ignored ||
3332 Diags.getDiagnosticLevel(diag::warn_cxx98_compat_template_arg_local_type,
3333 SR.getBegin()) != DiagnosticsEngine::Ignored :
3334 Arg->hasUnnamedOrLocalType()) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003335 UnnamedLocalNoLinkageFinder Finder(*this, SR);
3336 (void)Finder.Visit(Context.getCanonicalType(Arg));
3337 }
3338
Douglas Gregorc15cb382009-02-09 23:23:08 +00003339 return false;
3340}
3341
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003342/// \brief Checks whether the given template argument is the address
3343/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003344static bool
Douglas Gregorb7a09262010-04-01 18:32:35 +00003345CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
3346 NonTypeTemplateParmDecl *Param,
3347 QualType ParamType,
3348 Expr *ArgIn,
3349 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003350 bool Invalid = false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00003351 Expr *Arg = ArgIn;
3352 QualType ArgType = Arg->getType();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003353
3354 // See through any implicit casts we added to fix the type.
John McCall91a57552011-07-15 05:09:51 +00003355 Arg = Arg->IgnoreImpCasts();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003356
3357 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00003358 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003359 // A template-argument for a non-type, non-template
3360 // template-parameter shall be one of: [...]
3361 //
3362 // -- the address of an object or function with external
3363 // linkage, including function templates and function
3364 // template-ids but excluding non-static class members,
3365 // expressed as & id-expression where the & is optional if
3366 // the name refers to a function or array, or if the
3367 // corresponding template-parameter is a reference; or
Mike Stump1eb44332009-09-09 15:08:12 +00003368
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003369 // In C++98/03 mode, give an extension warning on any extra parentheses.
3370 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
3371 bool ExtraParens = false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003372 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smithebaf0e62011-10-18 20:49:44 +00003373 if (!Invalid && !ExtraParens) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003374 S.Diag(Arg->getSourceRange().getBegin(),
Richard Smithebaf0e62011-10-18 20:49:44 +00003375 S.getLangOptions().CPlusPlus0x ?
3376 diag::warn_cxx98_compat_template_arg_extra_parens :
3377 diag::ext_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003378 << Arg->getSourceRange();
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003379 ExtraParens = true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003380 }
3381
3382 Arg = Parens->getSubExpr();
3383 }
3384
John McCall91a57552011-07-15 05:09:51 +00003385 while (SubstNonTypeTemplateParmExpr *subst =
3386 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
3387 Arg = subst->getReplacement()->IgnoreImpCasts();
3388
Douglas Gregorb7a09262010-04-01 18:32:35 +00003389 bool AddressTaken = false;
3390 SourceLocation AddrOpLoc;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003391 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00003392 if (UnOp->getOpcode() == UO_AddrOf) {
John McCall91a57552011-07-15 05:09:51 +00003393 Arg = UnOp->getSubExpr();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003394 AddressTaken = true;
3395 AddrOpLoc = UnOp->getOperatorLoc();
3396 }
Francois Picheta343a412011-04-29 09:08:14 +00003397 }
John McCall91a57552011-07-15 05:09:51 +00003398
Francois Pichet62ec1f22011-09-17 17:15:52 +00003399 if (S.getLangOptions().MicrosoftExt && isa<CXXUuidofExpr>(Arg)) {
John McCall91a57552011-07-15 05:09:51 +00003400 Converted = TemplateArgument(ArgIn);
3401 return false;
3402 }
3403
3404 while (SubstNonTypeTemplateParmExpr *subst =
3405 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
3406 Arg = subst->getReplacement()->IgnoreImpCasts();
3407
3408 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
Douglas Gregorb7a09262010-04-01 18:32:35 +00003409 if (!DRE) {
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003410 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
3411 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003412 S.Diag(Param->getLocation(), diag::note_template_param_here);
3413 return true;
3414 }
Chandler Carruth038cc392010-01-31 10:01:20 +00003415
3416 // Stop checking the precise nature of the argument if it is value dependent,
3417 // it should be checked when instantiated.
Douglas Gregorb7a09262010-04-01 18:32:35 +00003418 if (Arg->isValueDependent()) {
John McCall3fa5cae2010-10-26 07:05:15 +00003419 Converted = TemplateArgument(ArgIn);
Chandler Carruth038cc392010-01-31 10:01:20 +00003420 return false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00003421 }
Chandler Carruth038cc392010-01-31 10:01:20 +00003422
Douglas Gregorb7a09262010-04-01 18:32:35 +00003423 if (!isa<ValueDecl>(DRE->getDecl())) {
3424 S.Diag(Arg->getSourceRange().getBegin(),
3425 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003426 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003427 S.Diag(Param->getLocation(), diag::note_template_param_here);
3428 return true;
3429 }
3430
3431 NamedDecl *Entity = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003432
3433 // Cannot refer to non-static data members
Douglas Gregorb7a09262010-04-01 18:32:35 +00003434 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
3435 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003436 << Field << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003437 S.Diag(Param->getLocation(), diag::note_template_param_here);
3438 return true;
3439 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003440
3441 // Cannot refer to non-static member functions
3442 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb7a09262010-04-01 18:32:35 +00003443 if (!Method->isStatic()) {
3444 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003445 << Method << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003446 S.Diag(Param->getLocation(), diag::note_template_param_here);
3447 return true;
3448 }
Mike Stump1eb44332009-09-09 15:08:12 +00003449
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003450 // Functions must have external linkage.
3451 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00003452 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003453 S.Diag(Arg->getSourceRange().getBegin(),
3454 diag::err_template_arg_function_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003455 << Func << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003456 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003457 << true;
3458 return true;
3459 }
3460
3461 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003462 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003463
Douglas Gregorb7a09262010-04-01 18:32:35 +00003464 // If the template parameter has pointer type, the function decays.
3465 if (ParamType->isPointerType() && !AddressTaken)
3466 ArgType = S.Context.getPointerType(Func->getType());
3467 else if (AddressTaken && ParamType->isReferenceType()) {
3468 // If we originally had an address-of operator, but the
3469 // parameter has reference type, complain and (if things look
3470 // like they will work) drop the address-of operator.
3471 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
3472 ParamType.getNonReferenceType())) {
3473 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3474 << ParamType;
3475 S.Diag(Param->getLocation(), diag::note_template_param_here);
3476 return true;
3477 }
3478
3479 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3480 << ParamType
3481 << FixItHint::CreateRemoval(AddrOpLoc);
3482 S.Diag(Param->getLocation(), diag::note_template_param_here);
3483
3484 ArgType = Func->getType();
3485 }
3486 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00003487 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003488 S.Diag(Arg->getSourceRange().getBegin(),
3489 diag::err_template_arg_object_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003490 << Var << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003491 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003492 << true;
3493 return true;
3494 }
3495
Douglas Gregorb7a09262010-04-01 18:32:35 +00003496 // A value of reference type is not an object.
3497 if (Var->getType()->isReferenceType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003498 S.Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorb7a09262010-04-01 18:32:35 +00003499 diag::err_template_arg_reference_var)
3500 << Var->getType() << Arg->getSourceRange();
3501 S.Diag(Param->getLocation(), diag::note_template_param_here);
3502 return true;
3503 }
3504
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003505 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003506 Entity = Var;
Douglas Gregorb7a09262010-04-01 18:32:35 +00003507
3508 // If the template parameter has pointer type, we must have taken
3509 // the address of this object.
3510 if (ParamType->isReferenceType()) {
3511 if (AddressTaken) {
3512 // If we originally had an address-of operator, but the
3513 // parameter has reference type, complain and (if things look
3514 // like they will work) drop the address-of operator.
3515 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
3516 ParamType.getNonReferenceType())) {
3517 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3518 << ParamType;
3519 S.Diag(Param->getLocation(), diag::note_template_param_here);
3520 return true;
3521 }
3522
3523 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3524 << ParamType
3525 << FixItHint::CreateRemoval(AddrOpLoc);
3526 S.Diag(Param->getLocation(), diag::note_template_param_here);
3527
3528 ArgType = Var->getType();
3529 }
3530 } else if (!AddressTaken && ParamType->isPointerType()) {
3531 if (Var->getType()->isArrayType()) {
3532 // Array-to-pointer decay.
3533 ArgType = S.Context.getArrayDecayedType(Var->getType());
3534 } else {
3535 // If the template parameter has pointer type but the address of
3536 // this object was not taken, complain and (possibly) recover by
3537 // taking the address of the entity.
3538 ArgType = S.Context.getPointerType(Var->getType());
3539 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
3540 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
3541 << ParamType;
3542 S.Diag(Param->getLocation(), diag::note_template_param_here);
3543 return true;
3544 }
3545
3546 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
3547 << ParamType
3548 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
3549
3550 S.Diag(Param->getLocation(), diag::note_template_param_here);
3551 }
3552 }
3553 } else {
3554 // We found something else, but we don't know specifically what it is.
3555 S.Diag(Arg->getSourceRange().getBegin(),
3556 diag::err_template_arg_not_object_or_func)
3557 << Arg->getSourceRange();
3558 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
3559 return true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003560 }
Mike Stump1eb44332009-09-09 15:08:12 +00003561
John McCallf85e1932011-06-15 23:02:42 +00003562 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003563 if (ParamType->isPointerType() &&
Douglas Gregorb7a09262010-04-01 18:32:35 +00003564 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
John McCallf85e1932011-06-15 23:02:42 +00003565 S.IsQualificationConversion(ArgType, ParamType, false,
3566 ObjCLifetimeConversion)) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003567 // For pointer-to-object types, qualification conversions are
3568 // permitted.
3569 } else {
3570 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
3571 if (!ParamRef->getPointeeType()->isFunctionType()) {
3572 // C++ [temp.arg.nontype]p5b3:
3573 // For a non-type template-parameter of type reference to
3574 // object, no conversions apply. The type referred to by the
3575 // reference may be more cv-qualified than the (otherwise
3576 // identical) type of the template- argument. The
3577 // template-parameter is bound directly to the
3578 // template-argument, which shall be an lvalue.
3579
3580 // FIXME: Other qualifiers?
3581 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
3582 unsigned ArgQuals = ArgType.getCVRQualifiers();
3583
3584 if ((ParamQuals | ArgQuals) != ParamQuals) {
3585 S.Diag(Arg->getSourceRange().getBegin(),
3586 diag::err_template_arg_ref_bind_ignores_quals)
3587 << ParamType << Arg->getType()
3588 << Arg->getSourceRange();
3589 S.Diag(Param->getLocation(), diag::note_template_param_here);
3590 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003591 }
Douglas Gregorb7a09262010-04-01 18:32:35 +00003592 }
3593 }
3594
3595 // At this point, the template argument refers to an object or
3596 // function with external linkage. We now need to check whether the
3597 // argument and parameter types are compatible.
3598 if (!S.Context.hasSameUnqualifiedType(ArgType,
3599 ParamType.getNonReferenceType())) {
3600 // We can't perform this conversion or binding.
3601 if (ParamType->isReferenceType())
3602 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
John McCall91a57552011-07-15 05:09:51 +00003603 << ParamType << ArgIn->getType() << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003604 else
3605 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
John McCall91a57552011-07-15 05:09:51 +00003606 << ArgIn->getType() << ParamType << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003607 S.Diag(Param->getLocation(), diag::note_template_param_here);
3608 return true;
3609 }
3610 }
3611
3612 // Create the template argument.
3613 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor77c13e02010-04-24 18:20:53 +00003614 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb7a09262010-04-01 18:32:35 +00003615 return false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003616}
3617
3618/// \brief Checks whether the given template argument is a pointer to
3619/// member constant according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003620bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
Douglas Gregorcaddba02009-11-12 18:38:13 +00003621 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003622 bool Invalid = false;
3623
3624 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00003625 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003626 Arg = Cast->getSubExpr();
3627
3628 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00003629 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003630 // A template-argument for a non-type, non-template
3631 // template-parameter shall be one of: [...]
3632 //
3633 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregora2813ce2009-10-23 18:54:35 +00003634 DeclRefExpr *DRE = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003635
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003636 // In C++98/03 mode, give an extension warning on any extra parentheses.
3637 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
3638 bool ExtraParens = false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003639 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smithebaf0e62011-10-18 20:49:44 +00003640 if (!Invalid && !ExtraParens) {
Mike Stump1eb44332009-09-09 15:08:12 +00003641 Diag(Arg->getSourceRange().getBegin(),
Richard Smithebaf0e62011-10-18 20:49:44 +00003642 getLangOptions().CPlusPlus0x ?
3643 diag::warn_cxx98_compat_template_arg_extra_parens :
3644 diag::ext_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003645 << Arg->getSourceRange();
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003646 ExtraParens = true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003647 }
3648
3649 Arg = Parens->getSubExpr();
3650 }
3651
John McCall91a57552011-07-15 05:09:51 +00003652 while (SubstNonTypeTemplateParmExpr *subst =
3653 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
3654 Arg = subst->getReplacement()->IgnoreImpCasts();
3655
Douglas Gregorcaddba02009-11-12 18:38:13 +00003656 // A pointer-to-member constant written &Class::member.
3657 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00003658 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00003659 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
3660 if (DRE && !DRE->getQualifier())
3661 DRE = 0;
3662 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003663 }
Douglas Gregorcaddba02009-11-12 18:38:13 +00003664 // A constant of pointer-to-member type.
3665 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
3666 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
3667 if (VD->getType()->isMemberPointerType()) {
3668 if (isa<NonTypeTemplateParmDecl>(VD) ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003669 (isa<VarDecl>(VD) &&
Douglas Gregorcaddba02009-11-12 18:38:13 +00003670 Context.getCanonicalType(VD->getType()).isConstQualified())) {
3671 if (Arg->isTypeDependent() || Arg->isValueDependent())
John McCall3fa5cae2010-10-26 07:05:15 +00003672 Converted = TemplateArgument(Arg);
Douglas Gregorcaddba02009-11-12 18:38:13 +00003673 else
3674 Converted = TemplateArgument(VD->getCanonicalDecl());
3675 return Invalid;
3676 }
3677 }
3678 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003679
Douglas Gregorcaddba02009-11-12 18:38:13 +00003680 DRE = 0;
3681 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003682
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003683 if (!DRE)
3684 return Diag(Arg->getSourceRange().getBegin(),
3685 diag::err_template_arg_not_pointer_to_member_form)
3686 << Arg->getSourceRange();
3687
3688 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
3689 assert((isa<FieldDecl>(DRE->getDecl()) ||
3690 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
3691 "Only non-static member pointers can make it here");
3692
3693 // Okay: this is the address of a non-static member, and therefore
3694 // a member pointer constant.
Douglas Gregorcaddba02009-11-12 18:38:13 +00003695 if (Arg->isTypeDependent() || Arg->isValueDependent())
John McCall3fa5cae2010-10-26 07:05:15 +00003696 Converted = TemplateArgument(Arg);
Douglas Gregorcaddba02009-11-12 18:38:13 +00003697 else
3698 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003699 return Invalid;
3700 }
3701
3702 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00003703 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003704 diag::err_template_arg_not_pointer_to_member_form)
3705 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003706 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003707 diag::note_template_arg_refers_here);
3708 return true;
3709}
3710
Douglas Gregorc15cb382009-02-09 23:23:08 +00003711/// \brief Check a template argument against its corresponding
3712/// non-type template parameter.
3713///
Douglas Gregor2943aed2009-03-03 04:44:36 +00003714/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley429bb272011-04-08 18:41:53 +00003715/// If an error occurred, it returns ExprError(); otherwise, it
3716/// returns the converted template argument. \p
Douglas Gregor2943aed2009-03-03 04:44:36 +00003717/// InstantiatedParamType is the type of the non-type template
3718/// parameter after it has been instantiated.
John Wiegley429bb272011-04-08 18:41:53 +00003719ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
3720 QualType InstantiatedParamType, Expr *Arg,
3721 TemplateArgument &Converted,
3722 CheckTemplateArgumentKind CTAK) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00003723 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
3724
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003725 // If either the parameter has a dependent type or the argument is
3726 // type-dependent, there's nothing we can check now.
Douglas Gregor40808ce2009-03-09 23:48:35 +00003727 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
3728 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003729 Converted = TemplateArgument(Arg);
John Wiegley429bb272011-04-08 18:41:53 +00003730 return Owned(Arg);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003731 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003732
3733 // C++ [temp.arg.nontype]p5:
3734 // The following conversions are performed on each expression used
3735 // as a non-type template-argument. If a non-type
3736 // template-argument cannot be converted to the type of the
3737 // corresponding template-parameter then the program is
3738 // ill-formed.
3739 //
3740 // -- for a non-type template-parameter of integral or
3741 // enumeration type, integral promotions (4.5) and integral
3742 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00003743 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00003744 QualType ArgType = Arg->getType();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003745 if (ParamType->isIntegralOrEnumerationType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003746 // C++ [temp.arg.nontype]p1:
3747 // A template-argument for a non-type, non-template
3748 // template-parameter shall be one of:
3749 //
3750 // -- an integral constant-expression of integral or enumeration
3751 // type; or
3752 // -- the name of a non-type template-parameter; or
3753 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003754 llvm::APSInt Value;
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003755 if (!ArgType->isIntegralOrEnumerationType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003756 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003757 diag::err_template_arg_not_integral_or_enumeral)
3758 << ArgType << Arg->getSourceRange();
3759 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley429bb272011-04-08 18:41:53 +00003760 return ExprError();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003761 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003762 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003763 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
3764 << ArgType << Arg->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003765 return ExprError();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003766 }
3767
Douglas Gregor02024a92010-03-28 02:42:43 +00003768 // From here on out, all we care about are the unqualified forms
3769 // of the parameter and argument types.
3770 ParamType = ParamType.getUnqualifiedType();
3771 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003772
3773 // Try to convert the argument to the parameter's type.
Douglas Gregorff524392009-11-04 21:50:46 +00003774 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003775 // Okay: no conversion necessary
Douglas Gregor02024a92010-03-28 02:42:43 +00003776 } else if (CTAK == CTAK_Deduced) {
3777 // C++ [temp.deduct.type]p17:
3778 // If, in the declaration of a function template with a non-type
3779 // template-parameter, the non-type template- parameter is used
3780 // in an expression in the function parameter-list and, if the
3781 // corresponding template-argument is deduced, the
3782 // template-argument type shall match the type of the
3783 // template-parameter exactly, except that a template-argument
3784 // deduced from an array bound may be of any integral type.
3785 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
3786 << ArgType << ParamType;
3787 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley429bb272011-04-08 18:41:53 +00003788 return ExprError();
John McCalldaa8e4e2010-11-15 09:13:47 +00003789 } else if (ParamType->isBooleanType()) {
3790 // This is an integral-to-boolean conversion.
John Wiegley429bb272011-04-08 18:41:53 +00003791 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).take();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003792 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
3793 !ParamType->isEnumeralType()) {
3794 // This is an integral promotion or conversion.
John Wiegley429bb272011-04-08 18:41:53 +00003795 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).take();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003796 } else {
3797 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00003798 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003799 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00003800 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003801 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley429bb272011-04-08 18:41:53 +00003802 return ExprError();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003803 }
3804
Douglas Gregorc7469372011-05-04 21:55:00 +00003805 // Add the value of this argument to the list of converted
3806 // arguments. We use the bitwidth and signedness of the template
3807 // parameter.
3808 if (Arg->isValueDependent()) {
3809 // The argument is value-dependent. Create a new
3810 // TemplateArgument with the converted expression.
3811 Converted = TemplateArgument(Arg);
3812 return Owned(Arg);
3813 }
3814
Douglas Gregorf80a9d52009-03-14 00:20:21 +00003815 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall183700f2009-09-21 23:43:11 +00003816 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003817 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00003818
Douglas Gregorc7469372011-05-04 21:55:00 +00003819 if (ParamType->isBooleanType()) {
3820 // Value must be zero or one.
3821 Value = Value != 0;
3822 unsigned AllowedBits = Context.getTypeSize(IntegerType);
3823 if (Value.getBitWidth() != AllowedBits)
3824 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor575a1c92011-05-20 16:38:50 +00003825 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorc7469372011-05-04 21:55:00 +00003826 } else {
Douglas Gregor1a6e0342010-03-26 02:38:37 +00003827 llvm::APSInt OldValue = Value;
Douglas Gregorc7469372011-05-04 21:55:00 +00003828
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003829 // Coerce the template argument's value to the value it will have
Douglas Gregor1a6e0342010-03-26 02:38:37 +00003830 // based on the template parameter's type.
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00003831 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00003832 if (Value.getBitWidth() != AllowedBits)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003833 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor575a1c92011-05-20 16:38:50 +00003834 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorc7469372011-05-04 21:55:00 +00003835
Douglas Gregor1a6e0342010-03-26 02:38:37 +00003836 // Complain if an unsigned parameter received a negative value.
Douglas Gregor575a1c92011-05-20 16:38:50 +00003837 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorc7469372011-05-04 21:55:00 +00003838 && (OldValue.isSigned() && OldValue.isNegative())) {
Douglas Gregor1a6e0342010-03-26 02:38:37 +00003839 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
3840 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3841 << Arg->getSourceRange();
3842 Diag(Param->getLocation(), diag::note_template_param_here);
3843 }
Douglas Gregorc7469372011-05-04 21:55:00 +00003844
Douglas Gregor1a6e0342010-03-26 02:38:37 +00003845 // Complain if we overflowed the template parameter's type.
3846 unsigned RequiredBits;
Douglas Gregor575a1c92011-05-20 16:38:50 +00003847 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregor1a6e0342010-03-26 02:38:37 +00003848 RequiredBits = OldValue.getActiveBits();
3849 else if (OldValue.isUnsigned())
3850 RequiredBits = OldValue.getActiveBits() + 1;
3851 else
3852 RequiredBits = OldValue.getMinSignedBits();
3853 if (RequiredBits > AllowedBits) {
3854 Diag(Arg->getSourceRange().getBegin(),
3855 diag::warn_template_arg_too_large)
3856 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3857 << Arg->getSourceRange();
3858 Diag(Param->getLocation(), diag::note_template_param_here);
3859 }
Douglas Gregorf80a9d52009-03-14 00:20:21 +00003860 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003861
John McCall833ca992009-10-29 08:12:44 +00003862 Converted = TemplateArgument(Value,
Douglas Gregor6b63f552011-08-09 01:55:14 +00003863 ParamType->isEnumeralType()
3864 ? Context.getCanonicalType(ParamType)
3865 : IntegerType);
John Wiegley429bb272011-04-08 18:41:53 +00003866 return Owned(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003867 }
Douglas Gregora35284b2009-02-11 00:19:33 +00003868
John McCall6bb80172010-03-30 21:47:33 +00003869 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
3870
Douglas Gregorb7a09262010-04-01 18:32:35 +00003871 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
3872 // from a template argument of type std::nullptr_t to a non-type
3873 // template parameter of type pointer to object, pointer to
3874 // function, or pointer-to-member, respectively.
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00003875 if (ArgType->isNullPtrType()) {
3876 if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
3877 Converted = TemplateArgument((NamedDecl *)0);
3878 return Owned(Arg);
3879 }
3880
3881 if (ParamType->isNullPtrType()) {
3882 llvm::APSInt Zero(Context.getTypeSize(Context.NullPtrTy), true);
3883 Converted = TemplateArgument(Zero, Context.NullPtrTy);
3884 return Owned(Arg);
3885 }
Douglas Gregorb7a09262010-04-01 18:32:35 +00003886 }
3887
Douglas Gregorb86b0572009-02-11 01:18:59 +00003888 // Handle pointer-to-function, reference-to-function, and
3889 // pointer-to-member-function all in (roughly) the same way.
3890 if (// -- For a non-type template-parameter of type pointer to
3891 // function, only the function-to-pointer conversion (4.3) is
3892 // applied. If the template-argument represents a set of
3893 // overloaded functions (or a pointer to such), the matching
3894 // function is selected from the set (13.4).
3895 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003896 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00003897 // -- For a non-type template-parameter of type reference to
3898 // function, no conversions apply. If the template-argument
3899 // represents a set of overloaded functions, the matching
3900 // function is selected from the set (13.4).
3901 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003902 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00003903 // -- For a non-type template-parameter of type pointer to
3904 // member function, no conversions apply. If the
3905 // template-argument represents a set of overloaded member
3906 // functions, the matching member function is selected from
3907 // the set (13.4).
3908 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003909 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00003910 ->isFunctionType())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003911
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003912 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003913 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003914 true,
3915 FoundResult)) {
3916 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
John Wiegley429bb272011-04-08 18:41:53 +00003917 return ExprError();
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003918
3919 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3920 ArgType = Arg->getType();
3921 } else
John Wiegley429bb272011-04-08 18:41:53 +00003922 return ExprError();
Douglas Gregora35284b2009-02-11 00:19:33 +00003923 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003924
John Wiegley429bb272011-04-08 18:41:53 +00003925 if (!ParamType->isMemberPointerType()) {
3926 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3927 ParamType,
3928 Arg, Converted))
3929 return ExprError();
3930 return Owned(Arg);
3931 }
Douglas Gregorb7a09262010-04-01 18:32:35 +00003932
John McCallf85e1932011-06-15 23:02:42 +00003933 bool ObjCLifetimeConversion;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003934 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType(),
John McCallf85e1932011-06-15 23:02:42 +00003935 false, ObjCLifetimeConversion)) {
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00003936 Arg = ImpCastExprToType(Arg, ParamType, CK_NoOp,
3937 Arg->getValueKind()).take();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003938 } else if (!Context.hasSameUnqualifiedType(ArgType,
3939 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00003940 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00003941 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregora35284b2009-02-11 00:19:33 +00003942 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00003943 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00003944 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley429bb272011-04-08 18:41:53 +00003945 return ExprError();
Douglas Gregora35284b2009-02-11 00:19:33 +00003946 }
Mike Stump1eb44332009-09-09 15:08:12 +00003947
John Wiegley429bb272011-04-08 18:41:53 +00003948 if (CheckTemplateArgumentPointerToMember(Arg, Converted))
3949 return ExprError();
3950 return Owned(Arg);
Douglas Gregora35284b2009-02-11 00:19:33 +00003951 }
3952
Chris Lattnerfe90de72009-02-20 21:37:53 +00003953 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00003954 // -- for a non-type template-parameter of type pointer to
3955 // object, qualification conversions (4.4) and the
3956 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00003957 // C++0x also allows a value of std::nullptr_t.
Eli Friedman13578692010-08-05 02:49:48 +00003958 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00003959 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00003960
John Wiegley429bb272011-04-08 18:41:53 +00003961 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3962 ParamType,
3963 Arg, Converted))
3964 return ExprError();
3965 return Owned(Arg);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00003966 }
Mike Stump1eb44332009-09-09 15:08:12 +00003967
Ted Kremenek6217b802009-07-29 21:53:49 +00003968 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00003969 // -- For a non-type template-parameter of type reference to
3970 // object, no conversions apply. The type referred to by the
3971 // reference may be more cv-qualified than the (otherwise
3972 // identical) type of the template-argument. The
3973 // template-parameter is bound directly to the
3974 // template-argument, which must be an lvalue.
Eli Friedman13578692010-08-05 02:49:48 +00003975 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00003976 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00003977
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003978 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003979 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
3980 ParamRefType->getPointeeType(),
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003981 true,
3982 FoundResult)) {
3983 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
John Wiegley429bb272011-04-08 18:41:53 +00003984 return ExprError();
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003985
3986 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3987 ArgType = Arg->getType();
3988 } else
John Wiegley429bb272011-04-08 18:41:53 +00003989 return ExprError();
Douglas Gregorb86b0572009-02-11 01:18:59 +00003990 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003991
John Wiegley429bb272011-04-08 18:41:53 +00003992 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3993 ParamType,
3994 Arg, Converted))
3995 return ExprError();
3996 return Owned(Arg);
Douglas Gregorb86b0572009-02-11 01:18:59 +00003997 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00003998
3999 // -- For a non-type template-parameter of type pointer to data
4000 // member, qualification conversions (4.4) are applied.
4001 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
4002
John McCallf85e1932011-06-15 23:02:42 +00004003 bool ObjCLifetimeConversion;
Douglas Gregor8e6563b2009-02-11 18:22:40 +00004004 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00004005 // Types match exactly: nothing more to do here.
John McCallf85e1932011-06-15 23:02:42 +00004006 } else if (IsQualificationConversion(ArgType, ParamType, false,
4007 ObjCLifetimeConversion)) {
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00004008 Arg = ImpCastExprToType(Arg, ParamType, CK_NoOp,
4009 Arg->getValueKind()).take();
Douglas Gregor658bbb52009-02-11 16:16:59 +00004010 } else {
4011 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00004012 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor658bbb52009-02-11 16:16:59 +00004013 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00004014 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00004015 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley429bb272011-04-08 18:41:53 +00004016 return ExprError();
Douglas Gregor658bbb52009-02-11 16:16:59 +00004017 }
4018
John Wiegley429bb272011-04-08 18:41:53 +00004019 if (CheckTemplateArgumentPointerToMember(Arg, Converted))
4020 return ExprError();
4021 return Owned(Arg);
Douglas Gregorc15cb382009-02-09 23:23:08 +00004022}
4023
4024/// \brief Check a template argument against its corresponding
4025/// template template parameter.
4026///
4027/// This routine implements the semantics of C++ [temp.arg.template].
4028/// It returns true if an error occurred, and false otherwise.
4029bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor788cd062009-11-11 01:00:40 +00004030 const TemplateArgumentLoc &Arg) {
4031 TemplateName Name = Arg.getArgument().getAsTemplate();
4032 TemplateDecl *Template = Name.getAsTemplateDecl();
4033 if (!Template) {
4034 // Any dependent template name is fine.
4035 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
4036 return false;
4037 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00004038
Richard Smith3e4c6c42011-05-05 21:57:07 +00004039 // C++0x [temp.arg.template]p1:
Douglas Gregordd0574e2009-02-10 00:24:35 +00004040 // A template-argument for a template template-parameter shall be
Richard Smith3e4c6c42011-05-05 21:57:07 +00004041 // the name of a class template or an alias template, expressed as an
4042 // id-expression. When the template-argument names a class template, only
Douglas Gregordd0574e2009-02-10 00:24:35 +00004043 // primary class templates are considered when matching the
4044 // template template argument with the corresponding parameter;
4045 // partial specializations are not considered even if their
4046 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00004047 //
4048 // Note that we also allow template template parameters here, which
4049 // will happen when we are dealing with, e.g., class template
4050 // partial specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00004051 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3e4c6c42011-05-05 21:57:07 +00004052 !isa<TemplateTemplateParmDecl>(Template) &&
4053 !isa<TypeAliasTemplateDecl>(Template)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004054 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregordd0574e2009-02-10 00:24:35 +00004055 "Only function templates are possible here");
Douglas Gregor788cd062009-11-11 01:00:40 +00004056 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregore53060f2009-06-25 22:08:12 +00004057 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00004058 << Template;
4059 }
4060
4061 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
4062 Param->getTemplateParameters(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004063 true,
Douglas Gregorfb898e12009-11-12 16:20:59 +00004064 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor788cd062009-11-11 01:00:40 +00004065 Arg.getLocation());
Douglas Gregorc15cb382009-02-09 23:23:08 +00004066}
4067
Douglas Gregor02024a92010-03-28 02:42:43 +00004068/// \brief Given a non-type template argument that refers to a
4069/// declaration and the type of its corresponding non-type template
4070/// parameter, produce an expression that properly refers to that
4071/// declaration.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004072ExprResult
Douglas Gregor02024a92010-03-28 02:42:43 +00004073Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
4074 QualType ParamType,
4075 SourceLocation Loc) {
4076 assert(Arg.getKind() == TemplateArgument::Declaration &&
4077 "Only declaration template arguments permitted here");
4078 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
4079
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004080 if (VD->getDeclContext()->isRecord() &&
Douglas Gregor02024a92010-03-28 02:42:43 +00004081 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
4082 // If the value is a class member, we might have a pointer-to-member.
4083 // Determine whether the non-type template template parameter is of
4084 // pointer-to-member type. If so, we need to build an appropriate
4085 // expression for a pointer-to-member, since a "normal" DeclRefExpr
4086 // would refer to the member itself.
4087 if (ParamType->isMemberPointerType()) {
4088 QualType ClassType
4089 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
4090 NestedNameSpecifier *Qualifier
John McCall9ae2f072010-08-23 23:25:46 +00004091 = NestedNameSpecifier::Create(Context, 0, false,
4092 ClassType.getTypePtr());
Douglas Gregor02024a92010-03-28 02:42:43 +00004093 CXXScopeSpec SS;
Douglas Gregorc34348a2011-02-24 17:54:50 +00004094 SS.MakeTrivial(Context, Qualifier, Loc);
John McCalldfa1edb2010-11-23 20:48:44 +00004095
4096 // The actual value-ness of this is unimportant, but for
4097 // internal consistency's sake, references to instance methods
4098 // are r-values.
4099 ExprValueKind VK = VK_LValue;
4100 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
4101 VK = VK_RValue;
4102
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004103 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCallf89e55a2010-11-18 06:31:45 +00004104 VD->getType().getNonReferenceType(),
John McCalldfa1edb2010-11-23 20:48:44 +00004105 VK,
John McCallf89e55a2010-11-18 06:31:45 +00004106 Loc,
4107 &SS);
Douglas Gregor02024a92010-03-28 02:42:43 +00004108 if (RefExpr.isInvalid())
4109 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004110
John McCall2de56d12010-08-25 11:45:40 +00004111 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004112
Douglas Gregorc0c83002010-04-30 21:46:38 +00004113 // We might need to perform a trailing qualification conversion, since
4114 // the element type on the parameter could be more qualified than the
4115 // element type in the expression we constructed.
John McCallf85e1932011-06-15 23:02:42 +00004116 bool ObjCLifetimeConversion;
Douglas Gregorc0c83002010-04-30 21:46:38 +00004117 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCallf85e1932011-06-15 23:02:42 +00004118 ParamType.getUnqualifiedType(), false,
4119 ObjCLifetimeConversion))
John Wiegley429bb272011-04-08 18:41:53 +00004120 RefExpr = ImpCastExprToType(RefExpr.take(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004121
Douglas Gregor02024a92010-03-28 02:42:43 +00004122 assert(!RefExpr.isInvalid() &&
4123 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorc0c83002010-04-30 21:46:38 +00004124 ParamType.getUnqualifiedType()));
Douglas Gregor02024a92010-03-28 02:42:43 +00004125 return move(RefExpr);
4126 }
4127 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004128
Douglas Gregor02024a92010-03-28 02:42:43 +00004129 QualType T = VD->getType().getNonReferenceType();
4130 if (ParamType->isPointerType()) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00004131 // When the non-type template parameter is a pointer, take the
4132 // address of the declaration.
John McCallf89e55a2010-11-18 06:31:45 +00004133 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregor02024a92010-03-28 02:42:43 +00004134 if (RefExpr.isInvalid())
4135 return ExprError();
Douglas Gregorb7a09262010-04-01 18:32:35 +00004136
4137 if (T->isFunctionType() || T->isArrayType()) {
4138 // Decay functions and arrays.
John Wiegley429bb272011-04-08 18:41:53 +00004139 RefExpr = DefaultFunctionArrayConversion(RefExpr.take());
4140 if (RefExpr.isInvalid())
4141 return ExprError();
Douglas Gregorb7a09262010-04-01 18:32:35 +00004142
4143 return move(RefExpr);
Douglas Gregor02024a92010-03-28 02:42:43 +00004144 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004145
Douglas Gregorb7a09262010-04-01 18:32:35 +00004146 // Take the address of everything else
John McCall2de56d12010-08-25 11:45:40 +00004147 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregor02024a92010-03-28 02:42:43 +00004148 }
4149
John McCallf89e55a2010-11-18 06:31:45 +00004150 ExprValueKind VK = VK_RValue;
4151
Douglas Gregor02024a92010-03-28 02:42:43 +00004152 // If the non-type template parameter has reference type, qualify the
4153 // resulting declaration reference with the extra qualifiers on the
4154 // type that the reference refers to.
John McCallf89e55a2010-11-18 06:31:45 +00004155 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
4156 VK = VK_LValue;
4157 T = Context.getQualifiedType(T,
4158 TargetRef->getPointeeType().getQualifiers());
4159 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004160
John McCallf89e55a2010-11-18 06:31:45 +00004161 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregor02024a92010-03-28 02:42:43 +00004162}
4163
4164/// \brief Construct a new expression that refers to the given
4165/// integral template argument with the given source-location
4166/// information.
4167///
4168/// This routine takes care of the mapping from an integral template
4169/// argument (which may have any integral type) to the appropriate
4170/// literal value.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004171ExprResult
Douglas Gregor02024a92010-03-28 02:42:43 +00004172Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
4173 SourceLocation Loc) {
4174 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregord3731192011-01-10 07:32:04 +00004175 "Operation is only valid for integral template arguments");
Douglas Gregor02024a92010-03-28 02:42:43 +00004176 QualType T = Arg.getIntegralType();
Douglas Gregor5cee1192011-07-27 05:40:30 +00004177 if (T->isAnyCharacterType()) {
4178 CharacterLiteral::CharacterKind Kind;
4179 if (T->isWideCharType())
4180 Kind = CharacterLiteral::Wide;
4181 else if (T->isChar16Type())
4182 Kind = CharacterLiteral::UTF16;
4183 else if (T->isChar32Type())
4184 Kind = CharacterLiteral::UTF32;
4185 else
4186 Kind = CharacterLiteral::Ascii;
4187
Douglas Gregor02024a92010-03-28 02:42:43 +00004188 return Owned(new (Context) CharacterLiteral(
Douglas Gregor5cee1192011-07-27 05:40:30 +00004189 Arg.getAsIntegral()->getZExtValue(),
4190 Kind, T, Loc));
4191 }
4192
Douglas Gregor02024a92010-03-28 02:42:43 +00004193 if (T->isBooleanType())
4194 return Owned(new (Context) CXXBoolLiteralExpr(
4195 Arg.getAsIntegral()->getBoolValue(),
Chris Lattner223de242011-04-25 20:37:58 +00004196 T, Loc));
Douglas Gregor02024a92010-03-28 02:42:43 +00004197
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00004198 if (T->isNullPtrType())
4199 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
4200
Chris Lattner223de242011-04-25 20:37:58 +00004201 // If this is an enum type that we're instantiating, we need to use an integer
4202 // type the same size as the enumerator. We don't want to build an
4203 // IntegerLiteral with enum type.
Peter Collingbournefb7b3632010-12-15 15:06:14 +00004204 QualType BT;
4205 if (const EnumType *ET = T->getAs<EnumType>())
Chris Lattner223de242011-04-25 20:37:58 +00004206 BT = ET->getDecl()->getIntegerType();
Peter Collingbournefb7b3632010-12-15 15:06:14 +00004207 else
4208 BT = T;
4209
John McCall4e9272d2011-07-15 07:47:58 +00004210 Expr *E = IntegerLiteral::Create(Context, *Arg.getAsIntegral(), BT, Loc);
4211 if (T->isEnumeralType()) {
4212 // FIXME: This is a hack. We need a better way to handle substituted
4213 // non-type template parameters.
4214 E = CStyleCastExpr::Create(Context, T, VK_RValue, CK_IntegralCast, E, 0,
4215 Context.getTrivialTypeSourceInfo(T, Loc),
4216 Loc, Loc);
4217 }
4218
4219 return Owned(E);
Douglas Gregor02024a92010-03-28 02:42:43 +00004220}
4221
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004222/// \brief Match two template parameters within template parameter lists.
4223static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
4224 bool Complain,
4225 Sema::TemplateParameterListEqualKind Kind,
4226 SourceLocation TemplateArgLoc) {
4227 // Check the actual kind (type, non-type, template).
4228 if (Old->getKind() != New->getKind()) {
4229 if (Complain) {
4230 unsigned NextDiag = diag::err_template_param_different_kind;
4231 if (TemplateArgLoc.isValid()) {
4232 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
4233 NextDiag = diag::note_template_param_different_kind;
4234 }
4235 S.Diag(New->getLocation(), NextDiag)
4236 << (Kind != Sema::TPL_TemplateMatch);
4237 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
4238 << (Kind != Sema::TPL_TemplateMatch);
4239 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004240
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004241 return false;
4242 }
4243
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004244 // Check that both are parameter packs are neither are parameter packs.
4245 // However, if we are matching a template template argument to a
Douglas Gregora0347822011-01-13 00:08:50 +00004246 // template template parameter, the template template parameter can have
4247 // a parameter pack where the template template argument does not.
4248 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
4249 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
4250 Old->isTemplateParameterPack())) {
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004251 if (Complain) {
4252 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
4253 if (TemplateArgLoc.isValid()) {
4254 S.Diag(TemplateArgLoc,
4255 diag::err_template_arg_template_params_mismatch);
4256 NextDiag = diag::note_template_parameter_pack_non_pack;
4257 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004258
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004259 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
4260 : isa<NonTypeTemplateParmDecl>(New)? 1
4261 : 2;
4262 S.Diag(New->getLocation(), NextDiag)
4263 << ParamKind << New->isParameterPack();
4264 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
4265 << ParamKind << Old->isParameterPack();
4266 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004267
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004268 return false;
4269 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004270
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004271 // For non-type template parameters, check the type of the parameter.
4272 if (NonTypeTemplateParmDecl *OldNTTP
4273 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
4274 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004275
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004276 // If we are matching a template template argument to a template
4277 // template parameter and one of the non-type template parameter types
4278 // is dependent, then we must wait until template instantiation time
4279 // to actually compare the arguments.
4280 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
4281 (OldNTTP->getType()->isDependentType() ||
4282 NewNTTP->getType()->isDependentType()))
4283 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004284
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004285 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
4286 if (Complain) {
4287 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
4288 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004289 S.Diag(TemplateArgLoc,
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004290 diag::err_template_arg_template_params_mismatch);
4291 NextDiag = diag::note_template_nontype_parm_different_type;
4292 }
4293 S.Diag(NewNTTP->getLocation(), NextDiag)
4294 << NewNTTP->getType()
4295 << (Kind != Sema::TPL_TemplateMatch);
4296 S.Diag(OldNTTP->getLocation(),
4297 diag::note_template_nontype_parm_prev_declaration)
4298 << OldNTTP->getType();
4299 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004300
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004301 return false;
4302 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004303
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004304 return true;
4305 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004306
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004307 // For template template parameters, check the template parameter types.
4308 // The template parameter lists of template template
4309 // parameters must agree.
4310 if (TemplateTemplateParmDecl *OldTTP
4311 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004312 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004313 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
4314 OldTTP->getTemplateParameters(),
4315 Complain,
4316 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004317 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004318 : Kind),
4319 TemplateArgLoc);
4320 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004321
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004322 return true;
4323}
Douglas Gregor02024a92010-03-28 02:42:43 +00004324
Douglas Gregora0347822011-01-13 00:08:50 +00004325/// \brief Diagnose a known arity mismatch when comparing template argument
4326/// lists.
4327static
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004328void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregora0347822011-01-13 00:08:50 +00004329 TemplateParameterList *New,
4330 TemplateParameterList *Old,
4331 Sema::TemplateParameterListEqualKind Kind,
4332 SourceLocation TemplateArgLoc) {
4333 unsigned NextDiag = diag::err_template_param_list_different_arity;
4334 if (TemplateArgLoc.isValid()) {
4335 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
4336 NextDiag = diag::note_template_param_list_different_arity;
4337 }
4338 S.Diag(New->getTemplateLoc(), NextDiag)
4339 << (New->size() > Old->size())
4340 << (Kind != Sema::TPL_TemplateMatch)
4341 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
4342 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
4343 << (Kind != Sema::TPL_TemplateMatch)
4344 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
4345}
4346
Douglas Gregorddc29e12009-02-06 22:42:48 +00004347/// \brief Determine whether the given template parameter lists are
4348/// equivalent.
4349///
Mike Stump1eb44332009-09-09 15:08:12 +00004350/// \param New The new template parameter list, typically written in the
Douglas Gregorddc29e12009-02-06 22:42:48 +00004351/// source code as part of a new template declaration.
4352///
4353/// \param Old The old template parameter list, typically found via
4354/// name lookup of the template declared with this template parameter
4355/// list.
4356///
4357/// \param Complain If true, this routine will produce a diagnostic if
4358/// the template parameter lists are not equivalent.
4359///
Douglas Gregorfb898e12009-11-12 16:20:59 +00004360/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregordd0574e2009-02-10 00:24:35 +00004361///
4362/// \param TemplateArgLoc If this source location is valid, then we
4363/// are actually checking the template parameter list of a template
4364/// argument (New) against the template parameter list of its
4365/// corresponding template template parameter (Old). We produce
4366/// slightly different diagnostics in this scenario.
4367///
Douglas Gregorddc29e12009-02-06 22:42:48 +00004368/// \returns True if the template parameter lists are equal, false
4369/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00004370bool
Douglas Gregorddc29e12009-02-06 22:42:48 +00004371Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
4372 TemplateParameterList *Old,
4373 bool Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00004374 TemplateParameterListEqualKind Kind,
Douglas Gregordd0574e2009-02-10 00:24:35 +00004375 SourceLocation TemplateArgLoc) {
Douglas Gregora0347822011-01-13 00:08:50 +00004376 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
4377 if (Complain)
4378 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
4379 TemplateArgLoc);
Douglas Gregorddc29e12009-02-06 22:42:48 +00004380
4381 return false;
4382 }
4383
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004384 // C++0x [temp.arg.template]p3:
4385 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004386 // when each of the template parameters in the template-parameter-list of
Richard Smith3e4c6c42011-05-05 21:57:07 +00004387 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004388 // (call it A) matches the corresponding template parameter in the
Douglas Gregora0347822011-01-13 00:08:50 +00004389 // template-parameter-list of P. [...]
4390 TemplateParameterList::iterator NewParm = New->begin();
4391 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorddc29e12009-02-06 22:42:48 +00004392 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregora0347822011-01-13 00:08:50 +00004393 OldParmEnd = Old->end();
4394 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregorc421f542011-01-13 18:47:47 +00004395 if (Kind != TPL_TemplateTemplateArgumentMatch ||
4396 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregora0347822011-01-13 00:08:50 +00004397 if (NewParm == NewParmEnd) {
4398 if (Complain)
4399 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
4400 TemplateArgLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004401
Douglas Gregora0347822011-01-13 00:08:50 +00004402 return false;
4403 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004404
Douglas Gregora0347822011-01-13 00:08:50 +00004405 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
4406 Kind, TemplateArgLoc))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004407 return false;
4408
Douglas Gregora0347822011-01-13 00:08:50 +00004409 ++NewParm;
4410 continue;
4411 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004412
Douglas Gregora0347822011-01-13 00:08:50 +00004413 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004414 // [...] When P's template- parameter-list contains a template parameter
4415 // pack (14.5.3), the template parameter pack will match zero or more
4416 // template parameters or template parameter packs in the
Douglas Gregora0347822011-01-13 00:08:50 +00004417 // template-parameter-list of A with the same type and form as the
4418 // template parameter pack in P (ignoring whether those template
4419 // parameters are template parameter packs).
4420 for (; NewParm != NewParmEnd; ++NewParm) {
4421 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
4422 Kind, TemplateArgLoc))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004423 return false;
Douglas Gregora0347822011-01-13 00:08:50 +00004424 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00004425 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004426
Douglas Gregora0347822011-01-13 00:08:50 +00004427 // Make sure we exhausted all of the arguments.
4428 if (NewParm != NewParmEnd) {
4429 if (Complain)
4430 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
4431 TemplateArgLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004432
Douglas Gregora0347822011-01-13 00:08:50 +00004433 return false;
4434 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004435
Douglas Gregorddc29e12009-02-06 22:42:48 +00004436 return true;
4437}
4438
4439/// \brief Check whether a template can be declared within this scope.
4440///
4441/// If the template declaration is valid in this scope, returns
4442/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump1eb44332009-09-09 15:08:12 +00004443bool
Douglas Gregor05396e22009-08-25 17:23:04 +00004444Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00004445 // Find the nearest enclosing declaration scope.
4446 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4447 (S->getFlags() & Scope::TemplateParamScope) != 0)
4448 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00004449
Douglas Gregorddc29e12009-02-06 22:42:48 +00004450 // C++ [temp]p2:
4451 // A template-declaration can appear only as a namespace scope or
4452 // class scope declaration.
4453 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00004454 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
4455 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump1eb44332009-09-09 15:08:12 +00004456 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor05396e22009-08-25 17:23:04 +00004457 << TemplateParams->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004458
Eli Friedman1503f772009-07-31 01:43:05 +00004459 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00004460 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00004461
4462 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
4463 return false;
4464
Mike Stump1eb44332009-09-09 15:08:12 +00004465 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004466 diag::err_template_outside_namespace_or_class_scope)
4467 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00004468}
Douglas Gregorcc636682009-02-17 23:15:12 +00004469
Douglas Gregord5cb8762009-10-07 00:13:32 +00004470/// \brief Determine what kind of template specialization the given declaration
4471/// is.
4472static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
4473 if (!D)
4474 return TSK_Undeclared;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004475
Douglas Gregorf6b11852009-10-08 15:14:33 +00004476 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
4477 return Record->getTemplateSpecializationKind();
Douglas Gregord5cb8762009-10-07 00:13:32 +00004478 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
4479 return Function->getTemplateSpecializationKind();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004480 if (VarDecl *Var = dyn_cast<VarDecl>(D))
4481 return Var->getTemplateSpecializationKind();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004482
Douglas Gregord5cb8762009-10-07 00:13:32 +00004483 return TSK_Undeclared;
4484}
4485
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004486/// \brief Check whether a specialization is well-formed in the current
Douglas Gregor9302da62009-10-14 23:50:59 +00004487/// context.
Douglas Gregor88b70942009-02-25 22:02:03 +00004488///
Douglas Gregor9302da62009-10-14 23:50:59 +00004489/// This routine determines whether a template specialization can be declared
4490/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00004491///
4492/// \param S the semantic analysis object for which this check is being
4493/// performed.
4494///
4495/// \param Specialized the entity being specialized or instantiated, which
4496/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004497/// a member of a class template (member function, static data member,
Douglas Gregord5cb8762009-10-07 00:13:32 +00004498/// member class).
4499///
4500/// \param PrevDecl the previous declaration of this entity, if any.
4501///
4502/// \param Loc the location of the explicit specialization or instantiation of
4503/// this entity.
4504///
4505/// \param IsPartialSpecialization whether this is a partial specialization of
4506/// a class template.
4507///
Douglas Gregord5cb8762009-10-07 00:13:32 +00004508/// \returns true if there was an error that we cannot recover from, false
4509/// otherwise.
4510static bool CheckTemplateSpecializationScope(Sema &S,
4511 NamedDecl *Specialized,
4512 NamedDecl *PrevDecl,
4513 SourceLocation Loc,
Douglas Gregor9302da62009-10-14 23:50:59 +00004514 bool IsPartialSpecialization) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00004515 // Keep these "kind" numbers in sync with the %select statements in the
4516 // various diagnostics emitted by this routine.
4517 int EntityKind = 0;
Ted Kremenekfe62b062011-01-14 22:31:36 +00004518 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00004519 EntityKind = IsPartialSpecialization? 1 : 0;
Ted Kremenekfe62b062011-01-14 22:31:36 +00004520 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00004521 EntityKind = 2;
Ted Kremenekfe62b062011-01-14 22:31:36 +00004522 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00004523 EntityKind = 3;
4524 else if (isa<VarDecl>(Specialized))
4525 EntityKind = 4;
4526 else if (isa<RecordDecl>(Specialized))
4527 EntityKind = 5;
4528 else {
Douglas Gregor9302da62009-10-14 23:50:59 +00004529 S.Diag(Loc, diag::err_template_spec_unknown_kind);
4530 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregord5cb8762009-10-07 00:13:32 +00004531 return true;
4532 }
4533
Douglas Gregor88b70942009-02-25 22:02:03 +00004534 // C++ [temp.expl.spec]p2:
4535 // An explicit specialization shall be declared in the namespace
4536 // of which the template is a member, or, for member templates, in
4537 // the namespace of which the enclosing class or enclosing class
4538 // template is a member. An explicit specialization of a member
4539 // function, member class or static data member of a class
4540 // template shall be declared in the namespace of which the class
4541 // template is a member. Such a declaration may also be a
4542 // definition. If the declaration is not a definition, the
4543 // specialization may be defined later in the name- space in which
4544 // the explicit specialization was declared, or in a namespace
4545 // that encloses the one in which the explicit specialization was
4546 // declared.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004547 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00004548 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00004549 << Specialized;
Douglas Gregor88b70942009-02-25 22:02:03 +00004550 return true;
4551 }
Douglas Gregor7974c3b2009-10-07 17:21:34 +00004552
Douglas Gregor0a407472009-10-07 17:30:37 +00004553 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
Francois Pichet62ec1f22011-09-17 17:15:52 +00004554 if (S.getLangOptions().MicrosoftExt) {
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004555 // Do not warn for class scope explicit specialization during
4556 // instantiation, warning was already emitted during pattern
4557 // semantic analysis.
4558 if (!S.ActiveTemplateInstantiations.size())
4559 S.Diag(Loc, diag::ext_function_specialization_in_class)
4560 << Specialized;
4561 } else {
4562 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
4563 << Specialized;
4564 return true;
4565 }
Douglas Gregor0a407472009-10-07 17:30:37 +00004566 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004567
Douglas Gregor8e0c1182011-10-20 16:41:18 +00004568 if (S.CurContext->isRecord() &&
4569 !S.CurContext->Equals(Specialized->getDeclContext())) {
4570 // Make sure that we're specializing in the right record context.
4571 // Otherwise, things can go horribly wrong.
4572 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
4573 << Specialized;
4574 return true;
4575 }
4576
Douglas Gregor7974c3b2009-10-07 17:21:34 +00004577 // C++ [temp.class.spec]p6:
4578 // A class template partial specialization may be declared or redeclared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004579 // in any namespace scope in which its definition may be defined (14.5.1
4580 // and 14.5.2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00004581 bool ComplainedAboutScope = false;
Douglas Gregor8e0c1182011-10-20 16:41:18 +00004582 DeclContext *SpecializedContext
Douglas Gregord5cb8762009-10-07 00:13:32 +00004583 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor7974c3b2009-10-07 17:21:34 +00004584 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004585 if ((!PrevDecl ||
Douglas Gregor9302da62009-10-14 23:50:59 +00004586 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
4587 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
Douglas Gregor121dc9a2010-09-12 05:08:28 +00004588 // C++ [temp.exp.spec]p2:
4589 // An explicit specialization shall be declared in the namespace of which
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004590 // the template is a member, or, for member templates, in the namespace
Douglas Gregor121dc9a2010-09-12 05:08:28 +00004591 // of which the enclosing class or enclosing class template is a member.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004592 // An explicit specialization of a member function, member class or
4593 // static data member of a class template shall be declared in the
Douglas Gregor121dc9a2010-09-12 05:08:28 +00004594 // namespace of which the class template is a member.
4595 //
4596 // C++0x [temp.expl.spec]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004597 // An explicit specialization shall be declared in a namespace enclosing
Douglas Gregor121dc9a2010-09-12 05:08:28 +00004598 // the specialized template.
Richard Smithebaf0e62011-10-18 20:49:44 +00004599 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
4600 bool IsCPlusPlus0xExtension = DC->Encloses(SpecializedContext);
4601 if (isa<TranslationUnitDecl>(SpecializedContext)) {
4602 assert(!IsCPlusPlus0xExtension &&
4603 "DC encloses TU but isn't in enclosing namespace set");
4604 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregora4d5de52010-09-12 05:24:55 +00004605 << EntityKind << Specialized;
Richard Smithebaf0e62011-10-18 20:49:44 +00004606 } else if (isa<NamespaceDecl>(SpecializedContext)) {
4607 int Diag;
4608 if (!IsCPlusPlus0xExtension)
4609 Diag = diag::err_template_spec_decl_out_of_scope;
4610 else if (!S.getLangOptions().CPlusPlus0x)
4611 Diag = diag::ext_template_spec_decl_out_of_scope;
4612 else
4613 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
4614 S.Diag(Loc, Diag)
4615 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
4616 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004617
Douglas Gregor9302da62009-10-14 23:50:59 +00004618 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Richard Smithebaf0e62011-10-18 20:49:44 +00004619 ComplainedAboutScope =
4620 !(IsCPlusPlus0xExtension && S.getLangOptions().CPlusPlus0x);
Douglas Gregor88b70942009-02-25 22:02:03 +00004621 }
Douglas Gregor88b70942009-02-25 22:02:03 +00004622 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004623
4624 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregor9302da62009-10-14 23:50:59 +00004625 // namespace.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004626 // Note that HandleDeclarator() performs this check for explicit
Douglas Gregord5cb8762009-10-07 00:13:32 +00004627 // specializations of function templates, static data members, and member
4628 // functions, so we skip the check here for those kinds of entities.
4629 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregor7974c3b2009-10-07 17:21:34 +00004630 // Should we refactor that check, so that it occurs later?
4631 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor9302da62009-10-14 23:50:59 +00004632 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
4633 isa<FunctionDecl>(Specialized))) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00004634 if (isa<TranslationUnitDecl>(SpecializedContext))
4635 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
4636 << EntityKind << Specialized;
4637 else if (isa<NamespaceDecl>(SpecializedContext))
4638 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
4639 << EntityKind << Specialized
4640 << cast<NamedDecl>(SpecializedContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004641
Douglas Gregor9302da62009-10-14 23:50:59 +00004642 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor88b70942009-02-25 22:02:03 +00004643 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004644
Douglas Gregord5cb8762009-10-07 00:13:32 +00004645 // FIXME: check for specialization-after-instantiation errors and such.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004646
Douglas Gregor88b70942009-02-25 22:02:03 +00004647 return false;
4648}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004649
Douglas Gregorbacb9492011-01-03 21:13:47 +00004650/// \brief Subroutine of Sema::CheckClassTemplatePartialSpecializationArgs
4651/// that checks non-type template partial specialization arguments.
4652static bool CheckNonTypeClassTemplatePartialSpecializationArgs(Sema &S,
4653 NonTypeTemplateParmDecl *Param,
4654 const TemplateArgument *Args,
4655 unsigned NumArgs) {
4656 for (unsigned I = 0; I != NumArgs; ++I) {
4657 if (Args[I].getKind() == TemplateArgument::Pack) {
4658 if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004659 Args[I].pack_begin(),
Douglas Gregorbacb9492011-01-03 21:13:47 +00004660 Args[I].pack_size()))
4661 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004662
Douglas Gregore94866f2009-06-12 21:21:02 +00004663 continue;
Douglas Gregorbacb9492011-01-03 21:13:47 +00004664 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004665
Douglas Gregorbacb9492011-01-03 21:13:47 +00004666 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00004667 if (!ArgExpr) {
Douglas Gregore94866f2009-06-12 21:21:02 +00004668 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00004669 }
Douglas Gregore94866f2009-06-12 21:21:02 +00004670
Douglas Gregor7a21fd42011-01-03 21:37:45 +00004671 // We can have a pack expansion of any of the bullets below.
Douglas Gregorbacb9492011-01-03 21:13:47 +00004672 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
4673 ArgExpr = Expansion->getPattern();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00004674
4675 // Strip off any implicit casts we added as part of type checking.
4676 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
4677 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004678
Douglas Gregore94866f2009-06-12 21:21:02 +00004679 // C++ [temp.class.spec]p8:
4680 // A non-type argument is non-specialized if it is the name of a
4681 // non-type parameter. All other non-type arguments are
4682 // specialized.
4683 //
4684 // Below, we check the two conditions that only apply to
4685 // specialized non-type arguments, so skip any non-specialized
4686 // arguments.
4687 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregor54c53cc2011-01-04 23:35:54 +00004688 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregore94866f2009-06-12 21:21:02 +00004689 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004690
Douglas Gregore94866f2009-06-12 21:21:02 +00004691 // C++ [temp.class.spec]p9:
4692 // Within the argument list of a class template partial
4693 // specialization, the following restrictions apply:
4694 // -- A partially specialized non-type argument expression
4695 // shall not involve a template parameter of the partial
4696 // specialization except when the argument expression is a
4697 // simple identifier.
4698 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Douglas Gregorbacb9492011-01-03 21:13:47 +00004699 S.Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00004700 diag::err_dependent_non_type_arg_in_partial_spec)
4701 << ArgExpr->getSourceRange();
4702 return true;
4703 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004704
Douglas Gregore94866f2009-06-12 21:21:02 +00004705 // -- The type of a template parameter corresponding to a
4706 // specialized non-type argument shall not be dependent on a
4707 // parameter of the specialization.
4708 if (Param->getType()->isDependentType()) {
Douglas Gregorbacb9492011-01-03 21:13:47 +00004709 S.Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00004710 diag::err_dependent_typed_non_type_arg_in_partial_spec)
4711 << Param->getType()
4712 << ArgExpr->getSourceRange();
Douglas Gregorbacb9492011-01-03 21:13:47 +00004713 S.Diag(Param->getLocation(), diag::note_template_param_here);
Douglas Gregore94866f2009-06-12 21:21:02 +00004714 return true;
4715 }
4716 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004717
Douglas Gregorbacb9492011-01-03 21:13:47 +00004718 return false;
4719}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004720
Douglas Gregorbacb9492011-01-03 21:13:47 +00004721/// \brief Check the non-type template arguments of a class template
4722/// partial specialization according to C++ [temp.class.spec]p9.
4723///
4724/// \param TemplateParams the template parameters of the primary class
4725/// template.
4726///
4727/// \param TemplateArg the template arguments of the class template
4728/// partial specialization.
4729///
4730/// \returns true if there was an error, false otherwise.
4731static bool CheckClassTemplatePartialSpecializationArgs(Sema &S,
4732 TemplateParameterList *TemplateParams,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004733 SmallVectorImpl<TemplateArgument> &TemplateArgs) {
Douglas Gregorbacb9492011-01-03 21:13:47 +00004734 const TemplateArgument *ArgList = TemplateArgs.data();
4735
4736 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
4737 NonTypeTemplateParmDecl *Param
4738 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
4739 if (!Param)
4740 continue;
4741
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004742 if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param,
Douglas Gregorbacb9492011-01-03 21:13:47 +00004743 &ArgList[I], 1))
4744 return true;
4745 }
Douglas Gregore94866f2009-06-12 21:21:02 +00004746
4747 return false;
4748}
4749
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004750/// \brief Retrieve the previous declaration of the given declaration.
4751static NamedDecl *getPreviousDecl(NamedDecl *ND) {
4752 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4753 return VD->getPreviousDeclaration();
4754 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
4755 return FD->getPreviousDeclaration();
4756 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
4757 return TD->getPreviousDeclaration();
Richard Smith162e1c12011-04-15 14:24:37 +00004758 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004759 return TD->getPreviousDeclaration();
4760 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4761 return FTD->getPreviousDeclaration();
4762 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
4763 return CTD->getPreviousDeclaration();
4764 return 0;
4765}
4766
John McCalld226f652010-08-21 09:40:31 +00004767DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00004768Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
4769 TagUseKind TUK,
Mike Stump1eb44332009-09-09 15:08:12 +00004770 SourceLocation KWLoc,
Douglas Gregord023aec2011-09-09 20:53:38 +00004771 SourceLocation ModulePrivateLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004772 CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004773 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00004774 SourceLocation TemplateNameLoc,
4775 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00004776 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00004777 SourceLocation RAngleLoc,
4778 AttributeList *Attr,
4779 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004780 assert(TUK != TUK_Reference && "References are not specializations");
John McCallf1bbbb42009-09-04 01:14:41 +00004781
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00004782 // NOTE: KWLoc is the location of the tag keyword. This will instead
4783 // store the location of the outermost template keyword in the declaration.
4784 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
4785 ? TemplateParameterLists.get()[0]->getTemplateLoc() : SourceLocation();
4786
Douglas Gregorcc636682009-02-17 23:15:12 +00004787 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00004788 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00004789 ClassTemplateDecl *ClassTemplate
Douglas Gregor8b13c082009-11-12 00:46:20 +00004790 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
4791
4792 if (!ClassTemplate) {
4793 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004794 << (Name.getAsTemplateDecl() &&
Douglas Gregor8b13c082009-11-12 00:46:20 +00004795 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
4796 return true;
4797 }
Douglas Gregorcc636682009-02-17 23:15:12 +00004798
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004799 bool isExplicitSpecialization = false;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004800 bool isPartialSpecialization = false;
4801
Douglas Gregor88b70942009-02-25 22:02:03 +00004802 // Check the validity of the template headers that introduce this
4803 // template.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004804 // FIXME: We probably shouldn't complain about these headers for
4805 // friend declarations.
Douglas Gregor0167f3c2010-07-14 23:14:12 +00004806 bool Invalid = false;
Douglas Gregor05396e22009-08-25 17:23:04 +00004807 TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00004808 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc,
4809 TemplateNameLoc,
4810 SS,
Mike Stump1eb44332009-09-09 15:08:12 +00004811 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004812 TemplateParameterLists.size(),
John McCall77e8b112010-04-13 20:37:33 +00004813 TUK == TUK_Friend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00004814 isExplicitSpecialization,
4815 Invalid);
4816 if (Invalid)
4817 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004818
Douglas Gregor05396e22009-08-25 17:23:04 +00004819 if (TemplateParams && TemplateParams->size() > 0) {
4820 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00004821
Douglas Gregorb0ee93c2010-12-21 08:14:57 +00004822 if (TUK == TUK_Friend) {
4823 Diag(KWLoc, diag::err_partial_specialization_friend)
4824 << SourceRange(LAngleLoc, RAngleLoc);
4825 return true;
4826 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004827
Douglas Gregor05396e22009-08-25 17:23:04 +00004828 // C++ [temp.class.spec]p10:
4829 // The template parameter list of a specialization shall not
4830 // contain default template argument values.
4831 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
4832 Decl *Param = TemplateParams->getParam(I);
4833 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
4834 if (TTP->hasDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004835 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004836 diag::err_default_arg_in_partial_spec);
John McCall833ca992009-10-29 08:12:44 +00004837 TTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00004838 }
4839 } else if (NonTypeTemplateParmDecl *NTTP
4840 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4841 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004842 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004843 diag::err_default_arg_in_partial_spec)
4844 << DefArg->getSourceRange();
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00004845 NTTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00004846 }
4847 } else {
4848 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor788cd062009-11-11 01:00:40 +00004849 if (TTP->hasDefaultArgument()) {
4850 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004851 diag::err_default_arg_in_partial_spec)
Douglas Gregor788cd062009-11-11 01:00:40 +00004852 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00004853 TTP->removeDefaultArgument();
Douglas Gregorba1ecb52009-06-12 19:43:02 +00004854 }
4855 }
4856 }
Douglas Gregora735b202009-10-13 14:39:41 +00004857 } else if (TemplateParams) {
4858 if (TUK == TUK_Friend)
4859 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregor849b2432010-03-31 17:46:05 +00004860 << FixItHint::CreateRemoval(
Douglas Gregora735b202009-10-13 14:39:41 +00004861 SourceRange(TemplateParams->getTemplateLoc(),
4862 TemplateParams->getRAngleLoc()))
4863 << SourceRange(LAngleLoc, RAngleLoc);
4864 else
4865 isExplicitSpecialization = true;
4866 } else if (TUK != TUK_Friend) {
Douglas Gregor05396e22009-08-25 17:23:04 +00004867 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor849b2432010-03-31 17:46:05 +00004868 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004869 isExplicitSpecialization = true;
4870 }
Douglas Gregor88b70942009-02-25 22:02:03 +00004871
Douglas Gregorcc636682009-02-17 23:15:12 +00004872 // Check that the specialization uses the same tag kind as the
4873 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004874 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4875 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004876 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieubbf34c02011-06-10 03:11:26 +00004877 Kind, TUK == TUK_Definition, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004878 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004879 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00004880 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00004881 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +00004882 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00004883 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregorcc636682009-02-17 23:15:12 +00004884 diag::note_previous_use);
4885 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4886 }
4887
Douglas Gregor40808ce2009-03-09 23:48:35 +00004888 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00004889 TemplateArgumentListInfo TemplateArgs;
4890 TemplateArgs.setLAngleLoc(LAngleLoc);
4891 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00004892 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00004893
Douglas Gregor925910d2011-01-03 20:35:03 +00004894 // Check for unexpanded parameter packs in any of the template arguments.
4895 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004896 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor925910d2011-01-03 20:35:03 +00004897 UPPC_PartialSpecialization))
4898 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004899
Douglas Gregorcc636682009-02-17 23:15:12 +00004900 // Check that the template argument list is well-formed for this
4901 // template.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004902 SmallVector<TemplateArgument, 4> Converted;
John McCalld5532b62009-11-23 01:53:49 +00004903 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4904 TemplateArgs, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00004905 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00004906
Douglas Gregor910f8002010-11-07 23:05:16 +00004907 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) &&
Douglas Gregorcc636682009-02-17 23:15:12 +00004908 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00004909
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004910 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00004911 // corresponds to these arguments.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00004912 if (isPartialSpecialization) {
Douglas Gregorbacb9492011-01-03 21:13:47 +00004913 if (CheckClassTemplatePartialSpecializationArgs(*this,
Douglas Gregore94866f2009-06-12 21:21:02 +00004914 ClassTemplate->getTemplateParameters(),
Douglas Gregorb9c66312010-12-23 17:13:55 +00004915 Converted))
Douglas Gregore94866f2009-06-12 21:21:02 +00004916 return true;
4917
Douglas Gregor561f8122011-07-01 01:22:09 +00004918 bool InstantiationDependent;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004919 if (!Name.isDependent() &&
Douglas Gregorde090962010-02-09 00:37:32 +00004920 !TemplateSpecializationType::anyDependentTemplateArguments(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004921 TemplateArgs.getArgumentArray(),
Douglas Gregor561f8122011-07-01 01:22:09 +00004922 TemplateArgs.size(),
4923 InstantiationDependent)) {
Douglas Gregorde090962010-02-09 00:37:32 +00004924 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4925 << ClassTemplate->getDeclName();
4926 isPartialSpecialization = false;
Douglas Gregorde090962010-02-09 00:37:32 +00004927 }
4928 }
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004929
Douglas Gregorcc636682009-02-17 23:15:12 +00004930 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004931 ClassTemplateSpecializationDecl *PrevDecl = 0;
4932
4933 if (isPartialSpecialization)
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004934 // FIXME: Template parameter list matters, too
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004935 PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00004936 = ClassTemplate->findPartialSpecialization(Converted.data(),
4937 Converted.size(),
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004938 InsertPos);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004939 else
4940 PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00004941 = ClassTemplate->findSpecialization(Converted.data(),
4942 Converted.size(), InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00004943
4944 ClassTemplateSpecializationDecl *Specialization = 0;
4945
Douglas Gregor88b70942009-02-25 22:02:03 +00004946 // Check whether we can declare a class template specialization in
4947 // the current scope.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004948 if (TUK != TUK_Friend &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004949 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
4950 TemplateNameLoc,
Douglas Gregor9302da62009-10-14 23:50:59 +00004951 isPartialSpecialization))
Douglas Gregor212e81c2009-03-25 00:13:59 +00004952 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004953
Douglas Gregorb88e8882009-07-30 17:40:51 +00004954 // The canonical type
4955 QualType CanonType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004956 if (PrevDecl &&
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004957 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregorde090962010-02-09 00:37:32 +00004958 TUK == TUK_Friend)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00004959 // Since the only prior class template specialization with these
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004960 // arguments was referenced but not declared, or we're only
4961 // referencing this specialization as a friend, reuse that
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00004962 // declaration node as our own, updating its source location and
4963 // the list of outer template parameters to reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00004964 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00004965 Specialization->setLocation(TemplateNameLoc);
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00004966 if (TemplateParameterLists.size() > 0) {
4967 Specialization->setTemplateParameterListsInfo(Context,
4968 TemplateParameterLists.size(),
4969 (TemplateParameterList**) TemplateParameterLists.release());
4970 }
Douglas Gregorcc636682009-02-17 23:15:12 +00004971 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00004972 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004973 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00004974 // Build the canonical type that describes the converted template
4975 // arguments of the class template partial specialization.
Douglas Gregorde090962010-02-09 00:37:32 +00004976 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4977 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregorb9c66312010-12-23 17:13:55 +00004978 Converted.data(),
4979 Converted.size());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004980
4981 if (Context.hasSameType(CanonType,
Douglas Gregorb9c66312010-12-23 17:13:55 +00004982 ClassTemplate->getInjectedClassNameSpecialization())) {
4983 // C++ [temp.class.spec]p9b3:
4984 //
4985 // -- The argument list of the specialization shall not be identical
4986 // to the implicit argument list of the primary template.
4987 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Douglas Gregor8d267c52011-09-09 02:06:17 +00004988 << (TUK == TUK_Definition)
4989 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregorb9c66312010-12-23 17:13:55 +00004990 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
4991 ClassTemplate->getIdentifier(),
4992 TemplateNameLoc,
4993 Attr,
4994 TemplateParams,
Douglas Gregore7612302011-09-09 19:05:14 +00004995 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00004996 TemplateParameterLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00004997 (TemplateParameterList**) TemplateParameterLists.release());
Douglas Gregorb9c66312010-12-23 17:13:55 +00004998 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00004999
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005000 // Create a new class template partial specialization declaration node.
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005001 ClassTemplatePartialSpecializationDecl *PrevPartial
5002 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregordc60c1e2010-04-30 05:56:50 +00005003 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005004 : ClassTemplate->getNextPartialSpecSequenceNumber();
Mike Stump1eb44332009-09-09 15:08:12 +00005005 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregor13c85772010-05-06 00:28:52 +00005006 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005007 ClassTemplate->getDeclContext(),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00005008 KWLoc, TemplateNameLoc,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00005009 TemplateParams,
5010 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00005011 Converted.data(),
5012 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00005013 TemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00005014 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00005015 PrevPartial,
5016 SequenceNumber);
John McCallb6217662010-03-15 10:12:16 +00005017 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005018 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00005019 Partial->setTemplateParameterListsInfo(Context,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005020 TemplateParameterLists.size() - 1,
Abramo Bagnara9b934882010-06-12 08:15:14 +00005021 (TemplateParameterList**) TemplateParameterLists.release());
5022 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005023
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005024 if (!PrevPartial)
5025 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005026 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00005027
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005028 // If we are providing an explicit specialization of a member class
Douglas Gregored9c0f92009-10-29 00:04:11 +00005029 // template specialization, make a note of that.
5030 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
5031 PrevPartial->setMemberSpecialization();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005032
Douglas Gregor031a5882009-06-13 00:26:55 +00005033 // Check that all of the template parameters of the class template
5034 // partial specialization are deducible from the template
5035 // arguments. If not, this class template partial specialization
5036 // will never be used.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005037 SmallVector<bool, 8> DeducibleParams;
Douglas Gregor031a5882009-06-13 00:26:55 +00005038 DeducibleParams.resize(TemplateParams->size());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005039 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregored9c0f92009-10-29 00:04:11 +00005040 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00005041 DeducibleParams);
Douglas Gregor031a5882009-06-13 00:26:55 +00005042 unsigned NumNonDeducible = 0;
5043 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
5044 if (!DeducibleParams[I])
5045 ++NumNonDeducible;
5046
5047 if (NumNonDeducible) {
5048 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
5049 << (NumNonDeducible > 1)
5050 << SourceRange(TemplateNameLoc, RAngleLoc);
5051 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
5052 if (!DeducibleParams[I]) {
5053 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
5054 if (Param->getDeclName())
Mike Stump1eb44332009-09-09 15:08:12 +00005055 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00005056 diag::note_partial_spec_unused_parameter)
5057 << Param->getDeclName();
5058 else
Mike Stump1eb44332009-09-09 15:08:12 +00005059 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00005060 diag::note_partial_spec_unused_parameter)
Benjamin Kramer476d8b82010-08-11 14:47:12 +00005061 << "<anonymous>";
Douglas Gregor031a5882009-06-13 00:26:55 +00005062 }
5063 }
5064 }
Douglas Gregorcc636682009-02-17 23:15:12 +00005065 } else {
5066 // Create a new class template specialization declaration node for
Douglas Gregorfc9cd612009-09-26 20:57:03 +00005067 // this explicit specialization or friend declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00005068 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00005069 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregorcc636682009-02-17 23:15:12 +00005070 ClassTemplate->getDeclContext(),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00005071 KWLoc, TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005072 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00005073 Converted.data(),
5074 Converted.size(),
Douglas Gregorcc636682009-02-17 23:15:12 +00005075 PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00005076 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005077 if (TemplateParameterLists.size() > 0) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00005078 Specialization->setTemplateParameterListsInfo(Context,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005079 TemplateParameterLists.size(),
Abramo Bagnara9b934882010-06-12 08:15:14 +00005080 (TemplateParameterList**) TemplateParameterLists.release());
5081 }
Douglas Gregorcc636682009-02-17 23:15:12 +00005082
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005083 if (!PrevDecl)
5084 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregorb88e8882009-07-30 17:40:51 +00005085
5086 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00005087 }
5088
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005089 // C++ [temp.expl.spec]p6:
5090 // If a template, a member template or the member of a class template is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005091 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005092 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005093 // instantiation to take place, in every translation unit in which such a
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005094 // use occurs; no diagnostic is required.
5095 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregordc0a11c2010-02-26 06:03:23 +00005096 bool Okay = false;
5097 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
5098 // Is there any previous explicit specialization declaration?
5099 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
5100 Okay = true;
5101 break;
5102 }
5103 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005104
Douglas Gregordc0a11c2010-02-26 06:03:23 +00005105 if (!Okay) {
5106 SourceRange Range(TemplateNameLoc, RAngleLoc);
5107 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
5108 << Context.getTypeDeclType(Specialization) << Range;
5109
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005110 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregordc0a11c2010-02-26 06:03:23 +00005111 diag::note_instantiation_required_here)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005112 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005113 != TSK_ImplicitInstantiation);
Douglas Gregordc0a11c2010-02-26 06:03:23 +00005114 return true;
5115 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005116 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005117
Douglas Gregorfc9cd612009-09-26 20:57:03 +00005118 // If this is not a friend, note that this is an explicit specialization.
5119 if (TUK != TUK_Friend)
5120 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00005121
5122 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00005123 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +00005124 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregorcc636682009-02-17 23:15:12 +00005125 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005126 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005127 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00005128 Diag(Def->getLocation(), diag::note_previous_definition);
5129 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00005130 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00005131 }
5132 }
5133
John McCall7f1b9872010-12-18 03:30:47 +00005134 if (Attr)
5135 ProcessDeclAttributeList(S, Specialization, Attr);
5136
Douglas Gregord023aec2011-09-09 20:53:38 +00005137 if (ModulePrivateLoc.isValid())
5138 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
5139 << (isPartialSpecialization? 1 : 0)
5140 << FixItHint::CreateRemoval(ModulePrivateLoc);
5141
Douglas Gregorfc705b82009-02-26 22:19:44 +00005142 // Build the fully-sugared type for this class template
5143 // specialization as the user wrote in the specialization
5144 // itself. This means that we'll pretty-print the type retrieved
5145 // from the specialization's declaration the way that the user
5146 // actually wrote the specialization, rather than formatting the
5147 // name based on the "canonical" representation used to store the
5148 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00005149 TypeSourceInfo *WrittenTy
5150 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
5151 TemplateArgs, CanonType);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005152 if (TUK != TUK_Friend) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00005153 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005154 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005155 }
Douglas Gregor40808ce2009-03-09 23:48:35 +00005156 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00005157
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00005158 // C++ [temp.expl.spec]p9:
5159 // A template explicit specialization is in the scope of the
5160 // namespace in which the template was defined.
5161 //
5162 // We actually implement this paragraph where we set the semantic
5163 // context (in the creation of the ClassTemplateSpecializationDecl),
5164 // but we also maintain the lexical context where the actual
5165 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00005166 Specialization->setLexicalDeclContext(CurContext);
Mike Stump1eb44332009-09-09 15:08:12 +00005167
Douglas Gregorcc636682009-02-17 23:15:12 +00005168 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00005169 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00005170 Specialization->startDefinition();
5171
Douglas Gregorfc9cd612009-09-26 20:57:03 +00005172 if (TUK == TUK_Friend) {
5173 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
5174 TemplateNameLoc,
John McCall32f2fb52010-03-25 18:04:51 +00005175 WrittenTy,
Douglas Gregorfc9cd612009-09-26 20:57:03 +00005176 /*FIXME:*/KWLoc);
5177 Friend->setAccess(AS_public);
5178 CurContext->addDecl(Friend);
5179 } else {
5180 // Add the specialization into its lexical context, so that it can
5181 // be seen when iterating through the list of declarations in that
5182 // context. However, specializations are not found by name lookup.
5183 CurContext->addDecl(Specialization);
5184 }
John McCalld226f652010-08-21 09:40:31 +00005185 return Specialization;
Douglas Gregorcc636682009-02-17 23:15:12 +00005186}
Douglas Gregord57959a2009-03-27 23:10:48 +00005187
John McCalld226f652010-08-21 09:40:31 +00005188Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregore542c862009-06-23 23:11:28 +00005189 MultiTemplateParamsArg TemplateParameterLists,
John McCalld226f652010-08-21 09:40:31 +00005190 Declarator &D) {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005191 return HandleDeclarator(S, D, move(TemplateParameterLists));
Douglas Gregore542c862009-06-23 23:11:28 +00005192}
5193
John McCalld226f652010-08-21 09:40:31 +00005194Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor52591bf2009-06-24 00:54:41 +00005195 MultiTemplateParamsArg TemplateParameterLists,
John McCalld226f652010-08-21 09:40:31 +00005196 Declarator &D) {
Douglas Gregor52591bf2009-06-24 00:54:41 +00005197 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005198 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00005199
Douglas Gregor52591bf2009-06-24 00:54:41 +00005200 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00005201 // FIXME: Diagnose arguments without names in C.
Douglas Gregor52591bf2009-06-24 00:54:41 +00005202 }
Mike Stump1eb44332009-09-09 15:08:12 +00005203
Douglas Gregor52591bf2009-06-24 00:54:41 +00005204 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00005205
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005206 D.setFunctionDefinition(true);
John McCalld226f652010-08-21 09:40:31 +00005207 Decl *DP = HandleDeclarator(ParentScope, D,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005208 move(TemplateParameterLists));
Mike Stump1eb44332009-09-09 15:08:12 +00005209 if (FunctionTemplateDecl *FunctionTemplate
John McCalld226f652010-08-21 09:40:31 +00005210 = dyn_cast_or_null<FunctionTemplateDecl>(DP))
Mike Stump1eb44332009-09-09 15:08:12 +00005211 return ActOnStartOfFunctionDef(FnBodyScope,
John McCalld226f652010-08-21 09:40:31 +00005212 FunctionTemplate->getTemplatedDecl());
5213 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP))
5214 return ActOnStartOfFunctionDef(FnBodyScope, Function);
5215 return 0;
Douglas Gregor52591bf2009-06-24 00:54:41 +00005216}
5217
John McCall75042392010-02-11 01:33:53 +00005218/// \brief Strips various properties off an implicit instantiation
5219/// that has just been explicitly specialized.
5220static void StripImplicitInstantiation(NamedDecl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00005221 D->dropAttrs();
John McCall75042392010-02-11 01:33:53 +00005222
5223 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5224 FD->setInlineSpecified(false);
5225 }
5226}
5227
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005228/// \brief Diagnose cases where we have an explicit template specialization
Douglas Gregor454885e2009-10-15 15:54:05 +00005229/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005230/// for those cases where they are required and determining whether the
Douglas Gregor454885e2009-10-15 15:54:05 +00005231/// new specialization/instantiation will have any effect.
5232///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005233/// \param NewLoc the location of the new explicit specialization or
Douglas Gregor454885e2009-10-15 15:54:05 +00005234/// instantiation.
5235///
5236/// \param NewTSK the kind of the new explicit specialization or instantiation.
5237///
5238/// \param PrevDecl the previous declaration of the entity.
5239///
5240/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
5241///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005242/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregor454885e2009-10-15 15:54:05 +00005243/// declaration was instantiated (either implicitly or explicitly).
5244///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005245/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregor454885e2009-10-15 15:54:05 +00005246/// specialization or instantiation has no effect and should be ignored.
5247///
5248/// \returns true if there was an error that should prevent the introduction of
5249/// the new declaration into the AST, false otherwise.
Douglas Gregor0d035142009-10-27 18:42:08 +00005250bool
5251Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
5252 TemplateSpecializationKind NewTSK,
5253 NamedDecl *PrevDecl,
5254 TemplateSpecializationKind PrevTSK,
5255 SourceLocation PrevPointOfInstantiation,
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005256 bool &HasNoEffect) {
5257 HasNoEffect = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005258
Douglas Gregor454885e2009-10-15 15:54:05 +00005259 switch (NewTSK) {
5260 case TSK_Undeclared:
5261 case TSK_ImplicitInstantiation:
David Blaikieb219cfc2011-09-23 05:06:16 +00005262 llvm_unreachable("Don't check implicit instantiations here");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005263
Douglas Gregor454885e2009-10-15 15:54:05 +00005264 case TSK_ExplicitSpecialization:
5265 switch (PrevTSK) {
5266 case TSK_Undeclared:
5267 case TSK_ExplicitSpecialization:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005268 // Okay, we're just specializing something that is either already
Douglas Gregor454885e2009-10-15 15:54:05 +00005269 // explicitly specialized or has merely been mentioned without any
5270 // instantiation.
5271 return false;
5272
5273 case TSK_ImplicitInstantiation:
5274 if (PrevPointOfInstantiation.isInvalid()) {
5275 // The declaration itself has not actually been instantiated, so it is
5276 // still okay to specialize it.
John McCall75042392010-02-11 01:33:53 +00005277 StripImplicitInstantiation(PrevDecl);
Douglas Gregor454885e2009-10-15 15:54:05 +00005278 return false;
5279 }
5280 // Fall through
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005281
Douglas Gregor454885e2009-10-15 15:54:05 +00005282 case TSK_ExplicitInstantiationDeclaration:
5283 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005284 assert((PrevTSK == TSK_ImplicitInstantiation ||
5285 PrevPointOfInstantiation.isValid()) &&
Douglas Gregor454885e2009-10-15 15:54:05 +00005286 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005287
Douglas Gregor454885e2009-10-15 15:54:05 +00005288 // C++ [temp.expl.spec]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005289 // If a template, a member template or the member of a class template
Douglas Gregor454885e2009-10-15 15:54:05 +00005290 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005291 // before the first use of that specialization that would cause an
Douglas Gregor454885e2009-10-15 15:54:05 +00005292 // implicit instantiation to take place, in every translation unit in
5293 // which such a use occurs; no diagnostic is required.
Douglas Gregordc0a11c2010-02-26 06:03:23 +00005294 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
5295 // Is there any previous explicit specialization declaration?
5296 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
5297 return false;
5298 }
5299
Douglas Gregor0d035142009-10-27 18:42:08 +00005300 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregor454885e2009-10-15 15:54:05 +00005301 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00005302 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregor454885e2009-10-15 15:54:05 +00005303 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005304
Douglas Gregor454885e2009-10-15 15:54:05 +00005305 return true;
5306 }
5307 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005308
Douglas Gregor454885e2009-10-15 15:54:05 +00005309 case TSK_ExplicitInstantiationDeclaration:
5310 switch (PrevTSK) {
5311 case TSK_ExplicitInstantiationDeclaration:
5312 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005313 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00005314 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005315
Douglas Gregor454885e2009-10-15 15:54:05 +00005316 case TSK_Undeclared:
5317 case TSK_ImplicitInstantiation:
5318 // We're explicitly instantiating something that may have already been
5319 // implicitly instantiated; that's fine.
5320 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005321
Douglas Gregor454885e2009-10-15 15:54:05 +00005322 case TSK_ExplicitSpecialization:
5323 // C++0x [temp.explicit]p4:
5324 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005325 // of a template appears after a declaration of an explicit
Douglas Gregor454885e2009-10-15 15:54:05 +00005326 // specialization for that template, the explicit instantiation has no
5327 // effect.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005328 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00005329 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005330
Douglas Gregor454885e2009-10-15 15:54:05 +00005331 case TSK_ExplicitInstantiationDefinition:
5332 // C++0x [temp.explicit]p10:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005333 // If an entity is the subject of both an explicit instantiation
5334 // declaration and an explicit instantiation definition in the same
Douglas Gregor454885e2009-10-15 15:54:05 +00005335 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005336 Diag(NewLoc,
Douglas Gregor0d035142009-10-27 18:42:08 +00005337 diag::err_explicit_instantiation_declaration_after_definition);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005338 Diag(PrevPointOfInstantiation,
Douglas Gregor0d035142009-10-27 18:42:08 +00005339 diag::note_explicit_instantiation_definition_here);
Douglas Gregor454885e2009-10-15 15:54:05 +00005340 assert(PrevPointOfInstantiation.isValid() &&
5341 "Explicit instantiation without point of instantiation?");
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005342 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00005343 return false;
5344 }
5345 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005346
Douglas Gregor454885e2009-10-15 15:54:05 +00005347 case TSK_ExplicitInstantiationDefinition:
5348 switch (PrevTSK) {
5349 case TSK_Undeclared:
5350 case TSK_ImplicitInstantiation:
5351 // We're explicitly instantiating something that may have already been
5352 // implicitly instantiated; that's fine.
5353 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005354
Douglas Gregor454885e2009-10-15 15:54:05 +00005355 case TSK_ExplicitSpecialization:
5356 // C++ DR 259, C++0x [temp.explicit]p4:
5357 // For a given set of template parameters, if an explicit
5358 // instantiation of a template appears after a declaration of
5359 // an explicit specialization for that template, the explicit
5360 // instantiation has no effect.
5361 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005362 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregorc42b6522010-04-09 21:02:29 +00005363 // is not harmful to try to explicitly instantiate something that
Douglas Gregor454885e2009-10-15 15:54:05 +00005364 // has been explicitly specialized.
Richard Smithebaf0e62011-10-18 20:49:44 +00005365 Diag(NewLoc, getLangOptions().CPlusPlus0x ?
5366 diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
5367 diag::ext_explicit_instantiation_after_specialization)
5368 << PrevDecl;
5369 Diag(PrevDecl->getLocation(),
5370 diag::note_previous_template_specialization);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005371 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00005372 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005373
Douglas Gregor454885e2009-10-15 15:54:05 +00005374 case TSK_ExplicitInstantiationDeclaration:
5375 // We're explicity instantiating a definition for something for which we
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005376 // were previously asked to suppress instantiations. That's fine.
Douglas Gregor454885e2009-10-15 15:54:05 +00005377 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005378
Douglas Gregor454885e2009-10-15 15:54:05 +00005379 case TSK_ExplicitInstantiationDefinition:
5380 // C++0x [temp.spec]p5:
5381 // For a given template and a given set of template-arguments,
5382 // - an explicit instantiation definition shall appear at most once
5383 // in a program,
Douglas Gregor0d035142009-10-27 18:42:08 +00005384 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregor454885e2009-10-15 15:54:05 +00005385 << PrevDecl;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005386 Diag(PrevPointOfInstantiation,
Douglas Gregor0d035142009-10-27 18:42:08 +00005387 diag::note_previous_explicit_instantiation);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005388 HasNoEffect = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005389 return false;
Douglas Gregor454885e2009-10-15 15:54:05 +00005390 }
5391 break;
5392 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005393
David Blaikieb219cfc2011-09-23 05:06:16 +00005394 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregor454885e2009-10-15 15:54:05 +00005395}
5396
John McCallaf2094e2010-04-08 09:05:18 +00005397/// \brief Perform semantic analysis for the given dependent function
5398/// template specialization. The only possible way to get a dependent
5399/// function template specialization is with a friend declaration,
5400/// like so:
5401///
5402/// template <class T> void foo(T);
5403/// template <class T> class A {
5404/// friend void foo<>(T);
5405/// };
5406///
5407/// There really isn't any useful analysis we can do here, so we
5408/// just store the information.
5409bool
5410Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
5411 const TemplateArgumentListInfo &ExplicitTemplateArgs,
5412 LookupResult &Previous) {
5413 // Remove anything from Previous that isn't a function template in
5414 // the correct context.
Sebastian Redl7a126a42010-08-31 00:36:30 +00005415 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallaf2094e2010-04-08 09:05:18 +00005416 LookupResult::Filter F = Previous.makeFilter();
5417 while (F.hasNext()) {
5418 NamedDecl *D = F.next()->getUnderlyingDecl();
5419 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl7a126a42010-08-31 00:36:30 +00005420 !FDLookupContext->InEnclosingNamespaceSetOf(
5421 D->getDeclContext()->getRedeclContext()))
John McCallaf2094e2010-04-08 09:05:18 +00005422 F.erase();
5423 }
5424 F.done();
5425
5426 // Should this be diagnosed here?
5427 if (Previous.empty()) return true;
5428
5429 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
5430 ExplicitTemplateArgs);
5431 return false;
5432}
5433
Abramo Bagnarae03db982010-05-20 15:32:11 +00005434/// \brief Perform semantic analysis for the given function template
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005435/// specialization.
5436///
Abramo Bagnarae03db982010-05-20 15:32:11 +00005437/// This routine performs all of the semantic analysis required for an
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005438/// explicit function template specialization. On successful completion,
5439/// the function declaration \p FD will become a function template
5440/// specialization.
5441///
5442/// \param FD the function declaration, which will be updated to become a
5443/// function template specialization.
5444///
Abramo Bagnarae03db982010-05-20 15:32:11 +00005445/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
5446/// if any. Note that this may be valid info even when 0 arguments are
5447/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
5448/// as it anyway contains info on the angle brackets locations.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005449///
Francois Pichet59e7c562011-07-08 06:21:47 +00005450/// \param Previous the set of declarations that may be specialized by
Abramo Bagnarae03db982010-05-20 15:32:11 +00005451/// this function specialization.
5452bool
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005453Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
Douglas Gregor67714232011-03-03 02:41:12 +00005454 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall68263142009-11-18 22:49:29 +00005455 LookupResult &Previous) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005456 // The set of function template specializations that could match this
5457 // explicit function template specialization.
John McCallc373d482010-01-27 01:50:18 +00005458 UnresolvedSet<8> Candidates;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005459
Sebastian Redl7a126a42010-08-31 00:36:30 +00005460 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall68263142009-11-18 22:49:29 +00005461 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5462 I != E; ++I) {
5463 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
5464 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005465 // Only consider templates found within the same semantic lookup scope as
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005466 // FD.
Sebastian Redl7a126a42010-08-31 00:36:30 +00005467 if (!FDLookupContext->InEnclosingNamespaceSetOf(
5468 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005469 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005470
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005471 // C++ [temp.expl.spec]p11:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005472 // A trailing template-argument can be left unspecified in the
5473 // template-id naming an explicit function template specialization
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005474 // provided it can be deduced from the function argument type.
5475 // Perform template argument deduction to determine whether we may be
5476 // specializing this template.
5477 // FIXME: It is somewhat wasteful to build
John McCall5769d612010-02-08 23:07:23 +00005478 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005479 FunctionDecl *Specialization = 0;
5480 if (TemplateDeductionResult TDK
John McCalld5532b62009-11-23 01:53:49 +00005481 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005482 FD->getType(),
5483 Specialization,
5484 Info)) {
5485 // FIXME: Template argument deduction failed; record why it failed, so
5486 // that we can provide nifty diagnostics.
5487 (void)TDK;
5488 continue;
5489 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005490
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005491 // Record this candidate.
John McCallc373d482010-01-27 01:50:18 +00005492 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005493 }
5494 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005495
Douglas Gregorc5df30f2009-09-26 03:41:46 +00005496 // Find the most specialized function template.
John McCallc373d482010-01-27 01:50:18 +00005497 UnresolvedSetIterator Result
5498 = getMostSpecialized(Candidates.begin(), Candidates.end(),
Douglas Gregor5c7bf422011-01-11 17:34:58 +00005499 TPOC_Other, 0, FD->getLocation(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005500 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregorc5df30f2009-09-26 03:41:46 +00005501 << FD->getDeclName(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005502 PDiag(diag::err_function_template_spec_ambiguous)
John McCalld5532b62009-11-23 01:53:49 +00005503 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005504 PDiag(diag::note_function_template_spec_matched));
John McCallc373d482010-01-27 01:50:18 +00005505 if (Result == Candidates.end())
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005506 return true;
John McCallc373d482010-01-27 01:50:18 +00005507
5508 // Ignore access information; it doesn't figure into redeclaration checking.
5509 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnaraabfb4052011-03-04 17:20:30 +00005510
5511 FunctionTemplateSpecializationInfo *SpecInfo
5512 = Specialization->getTemplateSpecializationInfo();
5513 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet59e7c562011-07-08 06:21:47 +00005514
5515 // Note: do not overwrite location info if previous template
5516 // specialization kind was explicit.
5517 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
5518 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation)
5519 Specialization->setLocation(FD->getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005520
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005521 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005522 // If so, we have run afoul of .
John McCall7ad650f2010-03-24 07:46:06 +00005523
5524 // If this is a friend declaration, then we're not really declaring
5525 // an explicit specialization.
5526 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005527
Douglas Gregord5cb8762009-10-07 00:13:32 +00005528 // Check the scope of this explicit specialization.
John McCall7ad650f2010-03-24 07:46:06 +00005529 if (!isFriend &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005530 CheckTemplateSpecializationScope(*this,
Douglas Gregord5cb8762009-10-07 00:13:32 +00005531 Specialization->getPrimaryTemplate(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005532 Specialization, FD->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00005533 false))
Douglas Gregord5cb8762009-10-07 00:13:32 +00005534 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005535
5536 // C++ [temp.expl.spec]p6:
5537 // If a template, a member template or the member of a class template is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005538 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005539 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005540 // instantiation to take place, in every translation unit in which such a
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005541 // use occurs; no diagnostic is required.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005542 bool HasNoEffect = false;
John McCall7ad650f2010-03-24 07:46:06 +00005543 if (!isFriend &&
5544 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall75042392010-02-11 01:33:53 +00005545 TSK_ExplicitSpecialization,
5546 Specialization,
5547 SpecInfo->getTemplateSpecializationKind(),
5548 SpecInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005549 HasNoEffect))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005550 return true;
Douglas Gregore885e182011-05-21 18:53:30 +00005551
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005552 // Mark the prior declaration as an explicit specialization, so that later
5553 // clients know that this is an explicit specialization.
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00005554 if (!isFriend) {
John McCall7ad650f2010-03-24 07:46:06 +00005555 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00005556 MarkUnusedFileScopedDecl(Specialization);
5557 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005558
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005559 // Turn the given function declaration into a function template
5560 // specialization, with the template arguments from the previous
5561 // specialization.
Abramo Bagnarae03db982010-05-20 15:32:11 +00005562 // Take copies of (semantic and syntactic) template argument lists.
5563 const TemplateArgumentList* TemplArgs = new (Context)
5564 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Douglas Gregor838db382010-02-11 01:19:42 +00005565 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnarae03db982010-05-20 15:32:11 +00005566 TemplArgs, /*InsertPos=*/0,
5567 SpecInfo->getTemplateSpecializationKind(),
Argyrios Kyrtzidis71a76052011-09-22 20:07:09 +00005568 ExplicitTemplateArgs);
Douglas Gregore885e182011-05-21 18:53:30 +00005569 FD->setStorageClass(Specialization->getStorageClass());
5570
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005571 // The "previous declaration" for this function template specialization is
5572 // the prior function template specialization.
John McCall68263142009-11-18 22:49:29 +00005573 Previous.clear();
5574 Previous.addDecl(Specialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005575 return false;
5576}
5577
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005578/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005579/// specialization.
5580///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005581/// This routine performs all of the semantic analysis required for an
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005582/// explicit member function specialization. On successful completion,
5583/// the function declaration \p FD will become a member function
5584/// specialization.
5585///
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005586/// \param Member the member declaration, which will be updated to become a
5587/// specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005588///
John McCall68263142009-11-18 22:49:29 +00005589/// \param Previous the set of declarations, one of which may be specialized
5590/// by this function specialization; the set will be modified to contain the
5591/// redeclared member.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005592bool
John McCall68263142009-11-18 22:49:29 +00005593Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005594 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCall77e8b112010-04-13 20:37:33 +00005595
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005596 // Try to find the member we are instantiating.
5597 NamedDecl *Instantiation = 0;
5598 NamedDecl *InstantiatedFrom = 0;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005599 MemberSpecializationInfo *MSInfo = 0;
5600
John McCall68263142009-11-18 22:49:29 +00005601 if (Previous.empty()) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005602 // Nowhere to look anyway.
5603 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00005604 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5605 I != E; ++I) {
5606 NamedDecl *D = (*I)->getUnderlyingDecl();
5607 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005608 if (Context.hasSameType(Function->getType(), Method->getType())) {
5609 Instantiation = Method;
5610 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005611 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005612 break;
5613 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005614 }
5615 }
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005616 } else if (isa<VarDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00005617 VarDecl *PrevVar;
5618 if (Previous.isSingleResult() &&
5619 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005620 if (PrevVar->isStaticDataMember()) {
John McCall68263142009-11-18 22:49:29 +00005621 Instantiation = PrevVar;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005622 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005623 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005624 }
5625 } else if (isa<RecordDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00005626 CXXRecordDecl *PrevRecord;
5627 if (Previous.isSingleResult() &&
5628 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
5629 Instantiation = PrevRecord;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005630 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005631 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005632 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005633 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005634
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005635 if (!Instantiation) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005636 // There is no previous declaration that matches. Since member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005637 // specializations are always out-of-line, the caller will complain about
5638 // this mismatch later.
5639 return false;
5640 }
John McCall77e8b112010-04-13 20:37:33 +00005641
5642 // If this is a friend, just bail out here before we start turning
5643 // things into explicit specializations.
5644 if (Member->getFriendObjectKind() != Decl::FOK_None) {
5645 // Preserve instantiation information.
5646 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
5647 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
5648 cast<CXXMethodDecl>(InstantiatedFrom),
5649 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
5650 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
5651 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
5652 cast<CXXRecordDecl>(InstantiatedFrom),
5653 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
5654 }
5655
5656 Previous.clear();
5657 Previous.addDecl(Instantiation);
5658 return false;
5659 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005660
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005661 // Make sure that this is a specialization of a member.
5662 if (!InstantiatedFrom) {
5663 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
5664 << Member;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005665 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
5666 return true;
5667 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005668
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005669 // C++ [temp.expl.spec]p6:
5670 // If a template, a member template or the member of a class template is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005671 // explicitly specialized then that spe- cialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005672 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005673 // instantiation to take place, in every translation unit in which such a
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005674 // use occurs; no diagnostic is required.
5675 assert(MSInfo && "Member specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00005676
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005677 bool HasNoEffect = false;
John McCall75042392010-02-11 01:33:53 +00005678 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
5679 TSK_ExplicitSpecialization,
5680 Instantiation,
5681 MSInfo->getTemplateSpecializationKind(),
5682 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005683 HasNoEffect))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005684 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005685
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005686 // Check the scope of this explicit specialization.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005687 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005688 InstantiatedFrom,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005689 Instantiation, Member->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00005690 false))
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005691 return true;
Douglas Gregor2db32322009-10-07 23:56:10 +00005692
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005693 // Note that this is an explicit instantiation of a member.
Douglas Gregorf6b11852009-10-08 15:14:33 +00005694 // the original declaration to note that it is an explicit specialization
5695 // (if it was previously an implicit instantiation). This latter step
5696 // makes bookkeeping easier.
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005697 if (isa<FunctionDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00005698 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
5699 if (InstantiationFunction->getTemplateSpecializationKind() ==
5700 TSK_ImplicitInstantiation) {
5701 InstantiationFunction->setTemplateSpecializationKind(
5702 TSK_ExplicitSpecialization);
5703 InstantiationFunction->setLocation(Member->getLocation());
5704 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005705
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005706 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
5707 cast<CXXMethodDecl>(InstantiatedFrom),
5708 TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00005709 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005710 } else if (isa<VarDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00005711 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
5712 if (InstantiationVar->getTemplateSpecializationKind() ==
5713 TSK_ImplicitInstantiation) {
5714 InstantiationVar->setTemplateSpecializationKind(
5715 TSK_ExplicitSpecialization);
5716 InstantiationVar->setLocation(Member->getLocation());
5717 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005718
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005719 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
5720 cast<VarDecl>(InstantiatedFrom),
5721 TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00005722 MarkUnusedFileScopedDecl(InstantiationVar);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005723 } else {
5724 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorf6b11852009-10-08 15:14:33 +00005725 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
5726 if (InstantiationClass->getTemplateSpecializationKind() ==
5727 TSK_ImplicitInstantiation) {
5728 InstantiationClass->setTemplateSpecializationKind(
5729 TSK_ExplicitSpecialization);
5730 InstantiationClass->setLocation(Member->getLocation());
5731 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005732
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005733 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorf6b11852009-10-08 15:14:33 +00005734 cast<CXXRecordDecl>(InstantiatedFrom),
5735 TSK_ExplicitSpecialization);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005736 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005737
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005738 // Save the caller the trouble of having to figure out which declaration
5739 // this specialization matches.
John McCall68263142009-11-18 22:49:29 +00005740 Previous.clear();
5741 Previous.addDecl(Instantiation);
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005742 return false;
5743}
5744
Douglas Gregor558c0322009-10-14 23:41:34 +00005745/// \brief Check the scope of an explicit instantiation.
Douglas Gregor669eed82010-07-13 00:10:04 +00005746///
5747/// \returns true if a serious error occurs, false otherwise.
5748static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregor558c0322009-10-14 23:41:34 +00005749 SourceLocation InstLoc,
5750 bool WasQualifiedName) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00005751 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
5752 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005753
Douglas Gregor669eed82010-07-13 00:10:04 +00005754 if (CurContext->isRecord()) {
5755 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
5756 << D;
5757 return true;
5758 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005759
Richard Smith3e2e91e2011-10-18 02:28:33 +00005760 // C++11 [temp.explicit]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005761 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith3e2e91e2011-10-18 02:28:33 +00005762 // template. If the name declared in the explicit instantiation is an
5763 // unqualified name, the explicit instantiation shall appear in the
5764 // namespace where its template is declared or, if that namespace is inline
5765 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregor558c0322009-10-14 23:41:34 +00005766 //
5767 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith3e2e91e2011-10-18 02:28:33 +00005768 if (WasQualifiedName) {
5769 if (CurContext->Encloses(OrigContext))
5770 return false;
5771 } else {
5772 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
5773 return false;
5774 }
5775
5776 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
5777 if (WasQualifiedName)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005778 S.Diag(InstLoc,
5779 S.getLangOptions().CPlusPlus0x?
Richard Smith3e2e91e2011-10-18 02:28:33 +00005780 diag::err_explicit_instantiation_out_of_scope :
5781 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00005782 << D << NS;
5783 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005784 S.Diag(InstLoc,
Douglas Gregor2166beb2010-05-11 17:39:34 +00005785 S.getLangOptions().CPlusPlus0x?
Richard Smith3e2e91e2011-10-18 02:28:33 +00005786 diag::err_explicit_instantiation_unqualified_wrong_namespace :
5787 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
5788 << D << NS;
5789 } else
5790 S.Diag(InstLoc,
5791 S.getLangOptions().CPlusPlus0x?
5792 diag::err_explicit_instantiation_must_be_global :
5793 diag::warn_explicit_instantiation_must_be_global_0x)
5794 << D;
Douglas Gregor558c0322009-10-14 23:41:34 +00005795 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor669eed82010-07-13 00:10:04 +00005796 return false;
Douglas Gregor558c0322009-10-14 23:41:34 +00005797}
5798
5799/// \brief Determine whether the given scope specifier has a template-id in it.
5800static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
5801 if (!SS.isSet())
5802 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005803
Richard Smith3e2e91e2011-10-18 02:28:33 +00005804 // C++11 [temp.explicit]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005805 // If the explicit instantiation is for a member function, a member class
Douglas Gregor558c0322009-10-14 23:41:34 +00005806 // or a static data member of a class template specialization, the name of
5807 // the class template specialization in the qualified-id for the member
5808 // name shall be a simple-template-id.
5809 //
5810 // C++98 has the same restriction, just worded differently.
5811 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
5812 NNS; NNS = NNS->getPrefix())
John McCallf4c73712011-01-19 06:33:43 +00005813 if (const Type *T = NNS->getAsType())
Douglas Gregor558c0322009-10-14 23:41:34 +00005814 if (isa<TemplateSpecializationType>(T))
5815 return true;
5816
5817 return false;
5818}
5819
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005820// Explicit instantiation of a class template specialization
John McCallf312b1e2010-08-26 23:41:50 +00005821DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00005822Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00005823 SourceLocation ExternLoc,
5824 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005825 unsigned TagSpec,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005826 SourceLocation KWLoc,
5827 const CXXScopeSpec &SS,
5828 TemplateTy TemplateD,
5829 SourceLocation TemplateNameLoc,
5830 SourceLocation LAngleLoc,
5831 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005832 SourceLocation RAngleLoc,
5833 AttributeList *Attr) {
5834 // Find the class template we're specializing
5835 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00005836 ClassTemplateDecl *ClassTemplate
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005837 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
5838
5839 // Check that the specialization uses the same tag kind as the
5840 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005841 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
5842 assert(Kind != TTK_Enum &&
5843 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005844 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieubbf34c02011-06-10 03:11:26 +00005845 Kind, /*isDefinition*/false, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005846 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00005847 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005848 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00005849 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005850 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00005851 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005852 diag::note_previous_use);
5853 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
5854 }
5855
Douglas Gregor558c0322009-10-14 23:41:34 +00005856 // C++0x [temp.explicit]p2:
5857 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005858 // definition and an explicit instantiation declaration. An explicit
5859 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5cb8762009-10-07 00:13:32 +00005860 TemplateSpecializationKind TSK
5861 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5862 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005863
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005864 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00005865 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00005866 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005867
5868 // Check that the template argument list is well-formed for this
5869 // template.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005870 SmallVector<TemplateArgument, 4> Converted;
John McCalld5532b62009-11-23 01:53:49 +00005871 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
5872 TemplateArgs, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005873 return true;
5874
Douglas Gregor910f8002010-11-07 23:05:16 +00005875 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) &&
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005876 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00005877
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005878 // Find the class template specialization declaration that
5879 // corresponds to these arguments.
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005880 void *InsertPos = 0;
5881 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00005882 = ClassTemplate->findSpecialization(Converted.data(),
5883 Converted.size(), InsertPos);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005884
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005885 TemplateSpecializationKind PrevDecl_TSK
5886 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
5887
Douglas Gregord5cb8762009-10-07 00:13:32 +00005888 // C++0x [temp.explicit]p2:
5889 // [...] An explicit instantiation shall appear in an enclosing
5890 // namespace of its template. [...]
5891 //
5892 // This is C++ DR 275.
Douglas Gregor669eed82010-07-13 00:10:04 +00005893 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
5894 SS.isSet()))
5895 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005896
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005897 ClassTemplateSpecializationDecl *Specialization = 0;
5898
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005899 bool HasNoEffect = false;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005900 if (PrevDecl) {
Douglas Gregor0d035142009-10-27 18:42:08 +00005901 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005902 PrevDecl, PrevDecl_TSK,
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005903 PrevDecl->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005904 HasNoEffect))
John McCalld226f652010-08-21 09:40:31 +00005905 return PrevDecl;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005906
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005907 // Even though HasNoEffect == true means that this explicit instantiation
5908 // has no effect on semantics, we go on to put its syntax in the AST.
5909
5910 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
5911 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor52604ab2009-09-11 21:19:12 +00005912 // Since the only prior class template specialization with these
5913 // arguments was referenced but not declared, reuse that
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005914 // declaration node as our own, updating the source location
5915 // for the template name to reflect our new declaration.
5916 // (Other source locations will be updated later.)
Douglas Gregor52604ab2009-09-11 21:19:12 +00005917 Specialization = PrevDecl;
5918 Specialization->setLocation(TemplateNameLoc);
5919 PrevDecl = 0;
5920 }
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005921 }
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005922
Douglas Gregor52604ab2009-09-11 21:19:12 +00005923 if (!Specialization) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005924 // Create a new class template specialization declaration node for
5925 // this explicit specialization.
5926 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00005927 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005928 ClassTemplate->getDeclContext(),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00005929 KWLoc, TemplateNameLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005930 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00005931 Converted.data(),
5932 Converted.size(),
5933 PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00005934 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005935
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005936 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005937 // Insert the new specialization.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005938 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005939 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005940 }
5941
5942 // Build the fully-sugared type for this explicit instantiation as
5943 // the user wrote in the explicit instantiation itself. This means
5944 // that we'll pretty-print the type retrieved from the
5945 // specialization's declaration the way that the user actually wrote
5946 // the explicit instantiation, rather than formatting the name based
5947 // on the "canonical" representation used to store the template
5948 // arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00005949 TypeSourceInfo *WrittenTy
5950 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
5951 TemplateArgs,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005952 Context.getTypeDeclType(Specialization));
5953 Specialization->setTypeAsWritten(WrittenTy);
5954 TemplateArgsIn.release();
5955
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005956 // Set source locations for keywords.
5957 Specialization->setExternLoc(ExternLoc);
5958 Specialization->setTemplateKeywordLoc(TemplateLoc);
5959
5960 // Add the explicit instantiation into its lexical context. However,
5961 // since explicit instantiations are never found by name lookup, we
5962 // just put it into the declaration context directly.
5963 Specialization->setLexicalDeclContext(CurContext);
5964 CurContext->addDecl(Specialization);
5965
5966 // Syntax is now OK, so return if it has no other effect on semantics.
5967 if (HasNoEffect) {
5968 // Set the template specialization kind.
5969 Specialization->setTemplateSpecializationKind(TSK);
John McCalld226f652010-08-21 09:40:31 +00005970 return Specialization;
Douglas Gregord78f5982009-11-25 06:01:46 +00005971 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005972
5973 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005974 // A definition of a class template or class member template
5975 // shall be in scope at the point of the explicit instantiation of
5976 // the class template or class member template.
5977 //
5978 // This check comes when we actually try to perform the
5979 // instantiation.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005980 ClassTemplateSpecializationDecl *Def
5981 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00005982 Specialization->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005983 if (!Def)
Douglas Gregor972e6ce2009-10-27 06:26:26 +00005984 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005985 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005986 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005987 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
5988 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005989
Douglas Gregor0d035142009-10-27 18:42:08 +00005990 // Instantiate the members of this class template specialization.
5991 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00005992 Specialization->getDefinition());
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00005993 if (Def) {
Rafael Espindolaf075b222010-03-23 19:55:22 +00005994 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
5995
5996 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
5997 // TSK_ExplicitInstantiationDefinition
5998 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
5999 TSK == TSK_ExplicitInstantiationDefinition)
6000 Def->setTemplateSpecializationKind(TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00006001
Douglas Gregor89a5bea2009-10-15 22:53:21 +00006002 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00006003 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006004
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006005 // Set the template specialization kind.
6006 Specialization->setTemplateSpecializationKind(TSK);
John McCalld226f652010-08-21 09:40:31 +00006007 return Specialization;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006008}
6009
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006010// Explicit instantiation of a member class of a class template.
John McCalld226f652010-08-21 09:40:31 +00006011DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00006012Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00006013 SourceLocation ExternLoc,
6014 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00006015 unsigned TagSpec,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006016 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006017 CXXScopeSpec &SS,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006018 IdentifierInfo *Name,
6019 SourceLocation NameLoc,
6020 AttributeList *Attr) {
6021
Douglas Gregor402abb52009-05-28 23:31:59 +00006022 bool Owned = false;
John McCallc4e70192009-09-11 04:59:25 +00006023 bool IsDependent = false;
John McCallf312b1e2010-08-26 23:41:50 +00006024 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCalld226f652010-08-21 09:40:31 +00006025 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregore7612302011-09-09 19:05:14 +00006026 /*ModulePrivateLoc=*/SourceLocation(),
John McCalld226f652010-08-21 09:40:31 +00006027 MultiTemplateParamsArg(*this, 0, 0),
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +00006028 Owned, IsDependent, false, false,
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006029 TypeResult());
John McCallc4e70192009-09-11 04:59:25 +00006030 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
6031
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006032 if (!TagD)
6033 return true;
6034
John McCalld226f652010-08-21 09:40:31 +00006035 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006036 if (Tag->isEnum()) {
6037 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
6038 << Context.getTypeDeclType(Tag);
6039 return true;
6040 }
6041
Douglas Gregord0c87372009-05-27 17:30:49 +00006042 if (Tag->isInvalidDecl())
6043 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006044
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006045 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
6046 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
6047 if (!Pattern) {
6048 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
6049 << Context.getTypeDeclType(Record);
6050 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
6051 return true;
6052 }
6053
Douglas Gregor558c0322009-10-14 23:41:34 +00006054 // C++0x [temp.explicit]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006055 // If the explicit instantiation is for a class or member class, the
6056 // elaborated-type-specifier in the declaration shall include a
Douglas Gregor558c0322009-10-14 23:41:34 +00006057 // simple-template-id.
6058 //
6059 // C++98 has the same restriction, just worded differently.
6060 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregora2dd8282010-06-16 16:26:47 +00006061 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00006062 << Record << SS.getRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006063
Douglas Gregor558c0322009-10-14 23:41:34 +00006064 // C++0x [temp.explicit]p2:
6065 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006066 // definition and an explicit instantiation declaration. An explicit
Douglas Gregor558c0322009-10-14 23:41:34 +00006067 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregora74bbe22009-10-14 21:46:58 +00006068 TemplateSpecializationKind TSK
6069 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
6070 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006071
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006072 // C++0x [temp.explicit]p2:
6073 // [...] An explicit instantiation shall appear in an enclosing
6074 // namespace of its template. [...]
6075 //
6076 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00006077 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006078
Douglas Gregor454885e2009-10-15 15:54:05 +00006079 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006080 CXXRecordDecl *PrevDecl
Douglas Gregor583f33b2009-10-15 18:07:02 +00006081 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor952b0172010-02-11 01:04:33 +00006082 if (!PrevDecl && Record->getDefinition())
Douglas Gregor583f33b2009-10-15 18:07:02 +00006083 PrevDecl = Record;
6084 if (PrevDecl) {
Douglas Gregor454885e2009-10-15 15:54:05 +00006085 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006086 bool HasNoEffect = false;
Douglas Gregor454885e2009-10-15 15:54:05 +00006087 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006088 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregor454885e2009-10-15 15:54:05 +00006089 PrevDecl,
6090 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006091 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006092 HasNoEffect))
Douglas Gregor454885e2009-10-15 15:54:05 +00006093 return true;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006094 if (HasNoEffect)
Douglas Gregor454885e2009-10-15 15:54:05 +00006095 return TagD;
6096 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006097
Douglas Gregor89a5bea2009-10-15 22:53:21 +00006098 CXXRecordDecl *RecordDef
Douglas Gregor952b0172010-02-11 01:04:33 +00006099 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00006100 if (!RecordDef) {
Douglas Gregorbf7643e2009-10-15 12:53:22 +00006101 // C++ [temp.explicit]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006102 // A definition of a member class of a class template shall be in scope
Douglas Gregorbf7643e2009-10-15 12:53:22 +00006103 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006104 CXXRecordDecl *Def
Douglas Gregor952b0172010-02-11 01:04:33 +00006105 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregorbf7643e2009-10-15 12:53:22 +00006106 if (!Def) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00006107 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
6108 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregorbf7643e2009-10-15 12:53:22 +00006109 Diag(Pattern->getLocation(), diag::note_forward_declaration)
6110 << Pattern;
6111 return true;
Douglas Gregor0d035142009-10-27 18:42:08 +00006112 } else {
6113 if (InstantiateClass(NameLoc, Record, Def,
6114 getTemplateInstantiationArgs(Record),
6115 TSK))
6116 return true;
6117
Douglas Gregor952b0172010-02-11 01:04:33 +00006118 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00006119 if (!RecordDef)
6120 return true;
6121 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006122 }
6123
Douglas Gregor0d035142009-10-27 18:42:08 +00006124 // Instantiate all of the members of the class.
6125 InstantiateClassMembers(NameLoc, RecordDef,
6126 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006127
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006128 if (TSK == TSK_ExplicitInstantiationDefinition)
6129 MarkVTableUsed(NameLoc, RecordDef, true);
6130
Mike Stump390b4cc2009-05-16 07:39:55 +00006131 // FIXME: We don't have any representation for explicit instantiations of
6132 // member classes. Such a representation is not needed for compilation, but it
6133 // should be available for clients that want to see all of the declarations in
6134 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006135 return TagD;
6136}
6137
John McCallf312b1e2010-08-26 23:41:50 +00006138DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
6139 SourceLocation ExternLoc,
6140 SourceLocation TemplateLoc,
6141 Declarator &D) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00006142 // Explicit instantiations always require a name.
Abramo Bagnara25777432010-08-11 22:01:17 +00006143 // TODO: check if/when DNInfo should replace Name.
6144 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6145 DeclarationName Name = NameInfo.getName();
Douglas Gregord5a423b2009-09-25 18:43:00 +00006146 if (!Name) {
6147 if (!D.isInvalidType())
6148 Diag(D.getDeclSpec().getSourceRange().getBegin(),
6149 diag::err_explicit_instantiation_requires_name)
6150 << D.getDeclSpec().getSourceRange()
6151 << D.getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006152
Douglas Gregord5a423b2009-09-25 18:43:00 +00006153 return true;
6154 }
6155
6156 // The scope passed in may not be a decl scope. Zip up the scope tree until
6157 // we find one that is.
6158 while ((S->getFlags() & Scope::DeclScope) == 0 ||
6159 (S->getFlags() & Scope::TemplateParamScope) != 0)
6160 S = S->getParent();
6161
6162 // Determine the type of the declaration.
John McCallbf1a0282010-06-04 23:28:52 +00006163 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
6164 QualType R = T->getType();
Douglas Gregord5a423b2009-09-25 18:43:00 +00006165 if (R.isNull())
6166 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006167
Douglas Gregore885e182011-05-21 18:53:30 +00006168 // C++ [dcl.stc]p1:
6169 // A storage-class-specifier shall not be specified in [...] an explicit
6170 // instantiation (14.7.2) directive.
Douglas Gregord5a423b2009-09-25 18:43:00 +00006171 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00006172 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
6173 << Name;
6174 return true;
Douglas Gregore885e182011-05-21 18:53:30 +00006175 } else if (D.getDeclSpec().getStorageClassSpec()
6176 != DeclSpec::SCS_unspecified) {
6177 // Complain about then remove the storage class specifier.
6178 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
6179 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6180
6181 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregord5a423b2009-09-25 18:43:00 +00006182 }
6183
Douglas Gregor663b5a02009-10-14 20:14:33 +00006184 // C++0x [temp.explicit]p1:
6185 // [...] An explicit instantiation of a function template shall not use the
6186 // inline or constexpr specifiers.
6187 // Presumably, this also applies to member functions of class templates as
6188 // well.
Richard Smith2dc7ece2011-10-18 03:44:03 +00006189 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006190 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2dc7ece2011-10-18 03:44:03 +00006191 getLangOptions().CPlusPlus0x ?
6192 diag::err_explicit_instantiation_inline :
6193 diag::warn_explicit_instantiation_inline_0x)
Richard Smithfe6f6482011-10-14 19:58:02 +00006194 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6195 if (D.getDeclSpec().isConstexprSpecified())
6196 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
6197 // not already specified.
6198 Diag(D.getDeclSpec().getConstexprSpecLoc(),
6199 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006200
Douglas Gregor558c0322009-10-14 23:41:34 +00006201 // C++0x [temp.explicit]p2:
6202 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006203 // definition and an explicit instantiation declaration. An explicit
6204 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5a423b2009-09-25 18:43:00 +00006205 TemplateSpecializationKind TSK
6206 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
6207 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006208
Abramo Bagnara25777432010-08-11 22:01:17 +00006209 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCalla24dc2e2009-11-17 02:14:36 +00006210 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregord5a423b2009-09-25 18:43:00 +00006211
6212 if (!R->isFunctionType()) {
6213 // C++ [temp.explicit]p1:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006214 // A [...] static data member of a class template can be explicitly
6215 // instantiated from the member definition associated with its class
Douglas Gregord5a423b2009-09-25 18:43:00 +00006216 // template.
John McCalla24dc2e2009-11-17 02:14:36 +00006217 if (Previous.isAmbiguous())
6218 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006219
John McCall1bcee0a2009-12-02 08:25:40 +00006220 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregord5a423b2009-09-25 18:43:00 +00006221 if (!Prev || !Prev->isStaticDataMember()) {
6222 // We expect to see a data data member here.
6223 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
6224 << Name;
6225 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
6226 P != PEnd; ++P)
John McCallf36e02d2009-10-09 21:13:30 +00006227 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregord5a423b2009-09-25 18:43:00 +00006228 return true;
6229 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006230
Douglas Gregord5a423b2009-09-25 18:43:00 +00006231 if (!Prev->getInstantiatedFromStaticDataMember()) {
6232 // FIXME: Check for explicit specialization?
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006233 Diag(D.getIdentifierLoc(),
Douglas Gregord5a423b2009-09-25 18:43:00 +00006234 diag::err_explicit_instantiation_data_member_not_instantiated)
6235 << Prev;
6236 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
6237 // FIXME: Can we provide a note showing where this was declared?
6238 return true;
6239 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006240
Douglas Gregor558c0322009-10-14 23:41:34 +00006241 // C++0x [temp.explicit]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006242 // If the explicit instantiation is for a member function, a member class
Douglas Gregor558c0322009-10-14 23:41:34 +00006243 // or a static data member of a class template specialization, the name of
6244 // the class template specialization in the qualified-id for the member
6245 // name shall be a simple-template-id.
6246 //
6247 // C++98 has the same restriction, just worded differently.
6248 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006249 Diag(D.getIdentifierLoc(),
Douglas Gregora2dd8282010-06-16 16:26:47 +00006250 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00006251 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006252
Douglas Gregor558c0322009-10-14 23:41:34 +00006253 // Check the scope of this explicit instantiation.
6254 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006255
Douglas Gregor454885e2009-10-15 15:54:05 +00006256 // Verify that it is okay to explicitly instantiate here.
6257 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
6258 assert(MSInfo && "Missing static data member specialization info?");
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006259 bool HasNoEffect = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00006260 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregor454885e2009-10-15 15:54:05 +00006261 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006262 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006263 HasNoEffect))
Douglas Gregor454885e2009-10-15 15:54:05 +00006264 return true;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006265 if (HasNoEffect)
John McCalld226f652010-08-21 09:40:31 +00006266 return (Decl*) 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006267
Douglas Gregord5a423b2009-09-25 18:43:00 +00006268 // Instantiate static data member.
Douglas Gregor0a897e32009-10-15 17:21:20 +00006269 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00006270 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruth58e390e2010-08-25 08:27:02 +00006271 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006272
Douglas Gregord5a423b2009-09-25 18:43:00 +00006273 // FIXME: Create an ExplicitInstantiation node?
John McCalld226f652010-08-21 09:40:31 +00006274 return (Decl*) 0;
Douglas Gregord5a423b2009-09-25 18:43:00 +00006275 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006276
6277 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00006278 // argument list into our AST format.
Douglas Gregordb422df2009-09-25 21:45:23 +00006279 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00006280 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006281 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6282 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCalld5532b62009-11-23 01:53:49 +00006283 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
6284 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregordb422df2009-09-25 21:45:23 +00006285 ASTTemplateArgsPtr TemplateArgsPtr(*this,
6286 TemplateId->getTemplateArgs(),
Douglas Gregordb422df2009-09-25 21:45:23 +00006287 TemplateId->NumArgs);
John McCalld5532b62009-11-23 01:53:49 +00006288 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregordb422df2009-09-25 21:45:23 +00006289 HasExplicitTemplateArgs = true;
Douglas Gregorb2f81cf2009-10-01 23:51:25 +00006290 TemplateArgsPtr.release();
Douglas Gregordb422df2009-09-25 21:45:23 +00006291 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006292
Douglas Gregord5a423b2009-09-25 18:43:00 +00006293 // C++ [temp.explicit]p1:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006294 // A [...] function [...] can be explicitly instantiated from its template.
6295 // A member function [...] of a class template can be explicitly
6296 // instantiated from the member definition associated with its class
Douglas Gregord5a423b2009-09-25 18:43:00 +00006297 // template.
John McCallc373d482010-01-27 01:50:18 +00006298 UnresolvedSet<8> Matches;
Douglas Gregord5a423b2009-09-25 18:43:00 +00006299 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
6300 P != PEnd; ++P) {
6301 NamedDecl *Prev = *P;
Douglas Gregordb422df2009-09-25 21:45:23 +00006302 if (!HasExplicitTemplateArgs) {
6303 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
6304 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
6305 Matches.clear();
Douglas Gregor48026d22010-01-11 18:40:55 +00006306
John McCallc373d482010-01-27 01:50:18 +00006307 Matches.addDecl(Method, P.getAccess());
Douglas Gregor48026d22010-01-11 18:40:55 +00006308 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
6309 break;
Douglas Gregordb422df2009-09-25 21:45:23 +00006310 }
Douglas Gregord5a423b2009-09-25 18:43:00 +00006311 }
6312 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006313
Douglas Gregord5a423b2009-09-25 18:43:00 +00006314 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
6315 if (!FunTmpl)
6316 continue;
6317
John McCall5769d612010-02-08 23:07:23 +00006318 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00006319 FunctionDecl *Specialization = 0;
6320 if (TemplateDeductionResult TDK
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006321 = DeduceTemplateArguments(FunTmpl,
John McCalld5532b62009-11-23 01:53:49 +00006322 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregord5a423b2009-09-25 18:43:00 +00006323 R, Specialization, Info)) {
6324 // FIXME: Keep track of almost-matches?
6325 (void)TDK;
6326 continue;
6327 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006328
John McCallc373d482010-01-27 01:50:18 +00006329 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregord5a423b2009-09-25 18:43:00 +00006330 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006331
Douglas Gregord5a423b2009-09-25 18:43:00 +00006332 // Find the most specialized function template specialization.
John McCallc373d482010-01-27 01:50:18 +00006333 UnresolvedSetIterator Result
Douglas Gregor5c7bf422011-01-11 17:34:58 +00006334 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other, 0,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006335 D.getIdentifierLoc(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006336 PDiag(diag::err_explicit_instantiation_not_known) << Name,
6337 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
6338 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregord5a423b2009-09-25 18:43:00 +00006339
John McCallc373d482010-01-27 01:50:18 +00006340 if (Result == Matches.end())
Douglas Gregord5a423b2009-09-25 18:43:00 +00006341 return true;
John McCallc373d482010-01-27 01:50:18 +00006342
6343 // Ignore access control bits, we don't need them for redeclaration checking.
6344 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006345
Douglas Gregor0a897e32009-10-15 17:21:20 +00006346 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006347 Diag(D.getIdentifierLoc(),
Douglas Gregord5a423b2009-09-25 18:43:00 +00006348 diag::err_explicit_instantiation_member_function_not_instantiated)
6349 << Specialization
6350 << (Specialization->getTemplateSpecializationKind() ==
6351 TSK_ExplicitSpecialization);
6352 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
6353 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006354 }
6355
Douglas Gregor0a897e32009-10-15 17:21:20 +00006356 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor583f33b2009-10-15 18:07:02 +00006357 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
6358 PrevDecl = Specialization;
6359
Douglas Gregor0a897e32009-10-15 17:21:20 +00006360 if (PrevDecl) {
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006361 bool HasNoEffect = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00006362 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006363 PrevDecl,
6364 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor0a897e32009-10-15 17:21:20 +00006365 PrevDecl->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006366 HasNoEffect))
Douglas Gregor0a897e32009-10-15 17:21:20 +00006367 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006368
Douglas Gregor0a897e32009-10-15 17:21:20 +00006369 // FIXME: We may still want to build some representation of this
6370 // explicit specialization.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006371 if (HasNoEffect)
John McCalld226f652010-08-21 09:40:31 +00006372 return (Decl*) 0;
Douglas Gregor0a897e32009-10-15 17:21:20 +00006373 }
Anders Carlsson26d6e9d2009-11-24 05:34:41 +00006374
6375 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006376
Douglas Gregor0a897e32009-10-15 17:21:20 +00006377 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruth58e390e2010-08-25 08:27:02 +00006378 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006379
Douglas Gregor558c0322009-10-14 23:41:34 +00006380 // C++0x [temp.explicit]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006381 // If the explicit instantiation is for a member function, a member class
Douglas Gregor558c0322009-10-14 23:41:34 +00006382 // or a static data member of a class template specialization, the name of
6383 // the class template specialization in the qualified-id for the member
6384 // name shall be a simple-template-id.
6385 //
6386 // C++98 has the same restriction, just worded differently.
Douglas Gregor0a897e32009-10-15 17:21:20 +00006387 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006388 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006389 D.getCXXScopeSpec().isSet() &&
Douglas Gregor558c0322009-10-14 23:41:34 +00006390 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006391 Diag(D.getIdentifierLoc(),
Douglas Gregora2dd8282010-06-16 16:26:47 +00006392 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00006393 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006394
Douglas Gregor558c0322009-10-14 23:41:34 +00006395 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006396 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregor558c0322009-10-14 23:41:34 +00006397 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006398 D.getIdentifierLoc(),
Douglas Gregor558c0322009-10-14 23:41:34 +00006399 D.getCXXScopeSpec().isSet());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006400
Douglas Gregord5a423b2009-09-25 18:43:00 +00006401 // FIXME: Create some kind of ExplicitInstantiationDecl here.
John McCalld226f652010-08-21 09:40:31 +00006402 return (Decl*) 0;
Douglas Gregord5a423b2009-09-25 18:43:00 +00006403}
6404
John McCallf312b1e2010-08-26 23:41:50 +00006405TypeResult
John McCallc4e70192009-09-11 04:59:25 +00006406Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
6407 const CXXScopeSpec &SS, IdentifierInfo *Name,
6408 SourceLocation TagLoc, SourceLocation NameLoc) {
6409 // This has to hold, because SS is expected to be defined.
6410 assert(Name && "Expected a name in a dependent tag");
6411
6412 NestedNameSpecifier *NNS
6413 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6414 if (!NNS)
6415 return true;
6416
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006417 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbar12c0ade2010-04-01 16:50:48 +00006418
Douglas Gregor48c89f42010-04-24 16:38:41 +00006419 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
6420 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006421 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregor48c89f42010-04-24 16:38:41 +00006422 return true;
6423 }
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006424
Douglas Gregor059101f2011-03-02 00:47:37 +00006425 // Create the resulting type.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006426 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor059101f2011-03-02 00:47:37 +00006427 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
6428
6429 // Create type-source location information for this type.
6430 TypeLocBuilder TLB;
6431 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
6432 TL.setKeywordLoc(TagLoc);
6433 TL.setQualifierLoc(SS.getWithLocInContext(Context));
6434 TL.setNameLoc(NameLoc);
6435 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCallc4e70192009-09-11 04:59:25 +00006436}
6437
John McCallf312b1e2010-08-26 23:41:50 +00006438TypeResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006439Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6440 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregor1a15dae2010-06-16 22:31:08 +00006441 SourceLocation IdLoc) {
Douglas Gregore29425b2011-02-28 22:42:13 +00006442 if (SS.isInvalid())
Douglas Gregord57959a2009-03-27 23:10:48 +00006443 return true;
Douglas Gregore29425b2011-02-28 22:42:13 +00006444
Richard Smithebaf0e62011-10-18 20:49:44 +00006445 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
6446 Diag(TypenameLoc,
6447 getLangOptions().CPlusPlus0x ?
6448 diag::warn_cxx98_compat_typename_outside_of_template :
6449 diag::ext_typename_outside_of_template)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006450 << FixItHint::CreateRemoval(TypenameLoc);
6451
Douglas Gregor2494dd02011-03-01 01:34:45 +00006452 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor9e876872011-03-01 18:12:44 +00006453 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
6454 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregor31a19b62009-04-01 21:51:26 +00006455 if (T.isNull())
6456 return true;
John McCall63b43852010-04-29 23:50:39 +00006457
6458 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6459 if (isa<DependentNameType>(T)) {
6460 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCall4e449832010-05-28 23:32:21 +00006461 TL.setKeywordLoc(TypenameLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00006462 TL.setQualifierLoc(QualifierLoc);
John McCall4e449832010-05-28 23:32:21 +00006463 TL.setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00006464 } else {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006465 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCall4e449832010-05-28 23:32:21 +00006466 TL.setKeywordLoc(TypenameLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00006467 TL.setQualifierLoc(QualifierLoc);
John McCall4e449832010-05-28 23:32:21 +00006468 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00006469 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006470
John McCallb3d87482010-08-24 05:47:05 +00006471 return CreateParsedType(T, TSI);
Douglas Gregord57959a2009-03-27 23:10:48 +00006472}
6473
John McCallf312b1e2010-08-26 23:41:50 +00006474TypeResult
Douglas Gregora02411e2011-02-27 22:46:49 +00006475Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6476 const CXXScopeSpec &SS,
6477 SourceLocation TemplateLoc,
6478 TemplateTy TemplateIn,
6479 SourceLocation TemplateNameLoc,
6480 SourceLocation LAngleLoc,
6481 ASTTemplateArgsPtr TemplateArgsIn,
6482 SourceLocation RAngleLoc) {
Richard Smithebaf0e62011-10-18 20:49:44 +00006483 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
6484 Diag(TypenameLoc,
6485 getLangOptions().CPlusPlus0x ?
6486 diag::warn_cxx98_compat_typename_outside_of_template :
6487 diag::ext_typename_outside_of_template)
6488 << FixItHint::CreateRemoval(TypenameLoc);
Douglas Gregora02411e2011-02-27 22:46:49 +00006489
6490 // Translate the parser's template argument list in our AST format.
6491 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
6492 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
6493
6494 TemplateName Template = TemplateIn.get();
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006495 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
6496 // Construct a dependent template specialization type.
6497 assert(DTN && "dependent template has non-dependent name?");
6498 assert(DTN->getQualifier()
6499 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
6500 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
6501 DTN->getQualifier(),
6502 DTN->getIdentifier(),
6503 TemplateArgs);
Douglas Gregora02411e2011-02-27 22:46:49 +00006504
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006505 // Create source-location information for this type.
John McCall4e449832010-05-28 23:32:21 +00006506 TypeLocBuilder Builder;
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006507 DependentTemplateSpecializationTypeLoc SpecTL
6508 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Douglas Gregora02411e2011-02-27 22:46:49 +00006509 SpecTL.setLAngleLoc(LAngleLoc);
6510 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006511 SpecTL.setKeywordLoc(TypenameLoc);
Douglas Gregor94fdffa2011-03-01 20:11:18 +00006512 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006513 SpecTL.setNameLoc(TemplateNameLoc);
Douglas Gregora02411e2011-02-27 22:46:49 +00006514 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
6515 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006516 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor6946baf2009-09-02 13:05:45 +00006517 }
Douglas Gregora02411e2011-02-27 22:46:49 +00006518
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006519 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
6520 if (T.isNull())
6521 return true;
Douglas Gregora02411e2011-02-27 22:46:49 +00006522
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006523 // Provide source-location information for the template specialization
6524 // type.
Douglas Gregora02411e2011-02-27 22:46:49 +00006525 TypeLocBuilder Builder;
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006526 TemplateSpecializationTypeLoc SpecTL
6527 = Builder.push<TemplateSpecializationTypeLoc>(T);
6528
6529 // FIXME: No place to set the location of the 'template' keyword!
Douglas Gregora02411e2011-02-27 22:46:49 +00006530 SpecTL.setLAngleLoc(LAngleLoc);
6531 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006532 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregora02411e2011-02-27 22:46:49 +00006533 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
6534 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
6535
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006536 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
6537 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
6538 TL.setKeywordLoc(TypenameLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00006539 TL.setQualifierLoc(SS.getWithLocInContext(Context));
6540
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006541 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
6542 return CreateParsedType(T, TSI);
Douglas Gregor17343172009-04-01 00:28:59 +00006543}
6544
Douglas Gregora02411e2011-02-27 22:46:49 +00006545
Douglas Gregord57959a2009-03-27 23:10:48 +00006546/// \brief Build the type that describes a C++ typename specifier,
6547/// e.g., "typename T::type".
6548QualType
Douglas Gregore29425b2011-02-28 22:42:13 +00006549Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
6550 SourceLocation KeywordLoc,
6551 NestedNameSpecifierLoc QualifierLoc,
6552 const IdentifierInfo &II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00006553 SourceLocation IILoc) {
John McCall77bb1aa2010-05-01 00:40:08 +00006554 CXXScopeSpec SS;
Douglas Gregore29425b2011-02-28 22:42:13 +00006555 SS.Adopt(QualifierLoc);
Douglas Gregord57959a2009-03-27 23:10:48 +00006556
John McCall77bb1aa2010-05-01 00:40:08 +00006557 DeclContext *Ctx = computeDeclContext(SS);
6558 if (!Ctx) {
6559 // If the nested-name-specifier is dependent and couldn't be
6560 // resolved to a type, build a typename type.
Douglas Gregore29425b2011-02-28 22:42:13 +00006561 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
6562 return Context.getDependentNameType(Keyword,
6563 QualifierLoc.getNestedNameSpecifier(),
6564 &II);
Douglas Gregor42af25f2009-05-11 19:58:34 +00006565 }
Douglas Gregord57959a2009-03-27 23:10:48 +00006566
John McCall77bb1aa2010-05-01 00:40:08 +00006567 // If the nested-name-specifier refers to the current instantiation,
6568 // the "typename" keyword itself is superfluous. In C++03, the
6569 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
6570 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregor732281d2010-06-14 22:07:54 +00006571 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregor42af25f2009-05-11 19:58:34 +00006572
John McCall77bb1aa2010-05-01 00:40:08 +00006573 if (RequireCompleteDeclContext(SS, Ctx))
6574 return QualType();
Douglas Gregord57959a2009-03-27 23:10:48 +00006575
6576 DeclarationName Name(&II);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00006577 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCalla24dc2e2009-11-17 02:14:36 +00006578 LookupQualifiedName(Result, Ctx);
Douglas Gregord57959a2009-03-27 23:10:48 +00006579 unsigned DiagID = 0;
6580 Decl *Referenced = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006581 switch (Result.getResultKind()) {
Douglas Gregord57959a2009-03-27 23:10:48 +00006582 case LookupResult::NotFound:
Douglas Gregor3f093272009-10-13 21:16:44 +00006583 DiagID = diag::err_typename_nested_not_found;
Douglas Gregord57959a2009-03-27 23:10:48 +00006584 break;
Douglas Gregord9545042010-12-09 00:06:27 +00006585
6586 case LookupResult::FoundUnresolvedValue: {
6587 // We found a using declaration that is a value. Most likely, the using
6588 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregore29425b2011-02-28 22:42:13 +00006589 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregord9545042010-12-09 00:06:27 +00006590 IILoc);
6591 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
6592 << Name << Ctx << FullRange;
6593 if (UnresolvedUsingValueDecl *Using
6594 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregordc355712011-02-25 00:36:19 +00006595 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregord9545042010-12-09 00:06:27 +00006596 Diag(Loc, diag::note_using_value_decl_missing_typename)
6597 << FixItHint::CreateInsertion(Loc, "typename ");
6598 }
6599 }
6600 // Fall through to create a dependent typename type, from which we can recover
6601 // better.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006602
Douglas Gregor7d3f5762010-01-15 01:44:47 +00006603 case LookupResult::NotFoundInCurrentInstantiation:
6604 // Okay, it's a member of an unknown instantiation.
Douglas Gregore29425b2011-02-28 22:42:13 +00006605 return Context.getDependentNameType(Keyword,
6606 QualifierLoc.getNestedNameSpecifier(),
6607 &II);
Douglas Gregord57959a2009-03-27 23:10:48 +00006608
6609 case LookupResult::Found:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006610 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006611 // We found a type. Build an ElaboratedType, since the
6612 // typename-specifier was just sugar.
Douglas Gregore29425b2011-02-28 22:42:13 +00006613 return Context.getElaboratedType(ETK_Typename,
6614 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006615 Context.getTypeDeclType(Type));
Douglas Gregord57959a2009-03-27 23:10:48 +00006616 }
6617
6618 DiagID = diag::err_typename_nested_not_type;
John McCallf36e02d2009-10-09 21:13:30 +00006619 Referenced = Result.getFoundDecl();
Douglas Gregord57959a2009-03-27 23:10:48 +00006620 break;
6621
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006622
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00006623 llvm_unreachable("unresolved using decl in non-dependent context");
John McCall7ba107a2009-11-18 02:36:19 +00006624 return QualType();
6625
Douglas Gregord57959a2009-03-27 23:10:48 +00006626 case LookupResult::FoundOverloaded:
6627 DiagID = diag::err_typename_nested_not_type;
6628 Referenced = *Result.begin();
6629 break;
6630
John McCall6e247262009-10-10 05:48:19 +00006631 case LookupResult::Ambiguous:
Douglas Gregord57959a2009-03-27 23:10:48 +00006632 return QualType();
6633 }
6634
6635 // If we get here, it's because name lookup did not find a
6636 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregore29425b2011-02-28 22:42:13 +00006637 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00006638 IILoc);
6639 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregord57959a2009-03-27 23:10:48 +00006640 if (Referenced)
6641 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
6642 << Name;
6643 return QualType();
6644}
Douglas Gregor4a959d82009-08-06 16:20:37 +00006645
6646namespace {
6647 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer85b45212009-11-28 19:45:26 +00006648 class CurrentInstantiationRebuilder
Mike Stump1eb44332009-09-09 15:08:12 +00006649 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor4a959d82009-08-06 16:20:37 +00006650 SourceLocation Loc;
6651 DeclarationName Entity;
Mike Stump1eb44332009-09-09 15:08:12 +00006652
Douglas Gregor4a959d82009-08-06 16:20:37 +00006653 public:
Douglas Gregor895162d2010-04-30 18:55:50 +00006654 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006655
Mike Stump1eb44332009-09-09 15:08:12 +00006656 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor4a959d82009-08-06 16:20:37 +00006657 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00006658 DeclarationName Entity)
6659 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor4a959d82009-08-06 16:20:37 +00006660 Loc(Loc), Entity(Entity) { }
Mike Stump1eb44332009-09-09 15:08:12 +00006661
6662 /// \brief Determine whether the given type \p T has already been
Douglas Gregor4a959d82009-08-06 16:20:37 +00006663 /// transformed.
6664 ///
6665 /// For the purposes of type reconstruction, a type has already been
6666 /// transformed if it is NULL or if it is not dependent.
6667 bool AlreadyTransformed(QualType T) {
6668 return T.isNull() || !T->isDependentType();
6669 }
Mike Stump1eb44332009-09-09 15:08:12 +00006670
6671 /// \brief Returns the location of the entity whose type is being
Douglas Gregor4a959d82009-08-06 16:20:37 +00006672 /// rebuilt.
6673 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +00006674
Douglas Gregor4a959d82009-08-06 16:20:37 +00006675 /// \brief Returns the name of the entity whose type is being rebuilt.
6676 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +00006677
Douglas Gregor972e6ce2009-10-27 06:26:26 +00006678 /// \brief Sets the "base" location and entity when that
6679 /// information is known based on another transformation.
6680 void setBase(SourceLocation Loc, DeclarationName Entity) {
6681 this->Loc = Loc;
6682 this->Entity = Entity;
6683 }
Douglas Gregor4a959d82009-08-06 16:20:37 +00006684 };
6685}
6686
Douglas Gregor4a959d82009-08-06 16:20:37 +00006687/// \brief Rebuilds a type within the context of the current instantiation.
6688///
Mike Stump1eb44332009-09-09 15:08:12 +00006689/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor4a959d82009-08-06 16:20:37 +00006690/// a class template (or class template partial specialization) that was parsed
Mike Stump1eb44332009-09-09 15:08:12 +00006691/// and constructed before we entered the scope of the class template (or
Douglas Gregor4a959d82009-08-06 16:20:37 +00006692/// partial specialization thereof). This routine will rebuild that type now
6693/// that we have entered the declarator's scope, which may produce different
6694/// canonical types, e.g.,
6695///
6696/// \code
6697/// template<typename T>
6698/// struct X {
6699/// typedef T* pointer;
6700/// pointer data();
6701/// };
6702///
6703/// template<typename T>
6704/// typename X<T>::pointer X<T>::data() { ... }
6705/// \endcode
6706///
Douglas Gregor4714c122010-03-31 17:34:00 +00006707/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor4a959d82009-08-06 16:20:37 +00006708/// since we do not know that we can look into X<T> when we parsed the type.
6709/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006710/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor4a959d82009-08-06 16:20:37 +00006711/// as the canonical type of T*, allowing the return types of the out-of-line
6712/// definition and the declaration to match.
John McCall63b43852010-04-29 23:50:39 +00006713TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
6714 SourceLocation Loc,
6715 DeclarationName Name) {
6716 if (!T || !T->getType()->isDependentType())
Douglas Gregor4a959d82009-08-06 16:20:37 +00006717 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00006718
Douglas Gregor4a959d82009-08-06 16:20:37 +00006719 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
6720 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00006721}
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006722
John McCall60d7b3a2010-08-24 06:29:42 +00006723ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallb3d87482010-08-24 05:47:05 +00006724 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
6725 DeclarationName());
6726 return Rebuilder.TransformExpr(E);
6727}
6728
John McCall63b43852010-04-29 23:50:39 +00006729bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Douglas Gregor7e384942011-02-25 16:07:42 +00006730 if (SS.isInvalid())
6731 return true;
John McCall31f17ec2010-04-27 00:57:59 +00006732
Douglas Gregor7e384942011-02-25 16:07:42 +00006733 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall31f17ec2010-04-27 00:57:59 +00006734 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
6735 DeclarationName());
Douglas Gregor7e384942011-02-25 16:07:42 +00006736 NestedNameSpecifierLoc Rebuilt
6737 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
6738 if (!Rebuilt)
6739 return true;
John McCall63b43852010-04-29 23:50:39 +00006740
Douglas Gregor7e384942011-02-25 16:07:42 +00006741 SS.Adopt(Rebuilt);
John McCall63b43852010-04-29 23:50:39 +00006742 return false;
John McCall31f17ec2010-04-27 00:57:59 +00006743}
6744
Douglas Gregor20606502011-10-14 15:31:12 +00006745/// \brief Rebuild the template parameters now that we know we're in a current
6746/// instantiation.
6747bool Sema::RebuildTemplateParamsInCurrentInstantiation(
6748 TemplateParameterList *Params) {
6749 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
6750 Decl *Param = Params->getParam(I);
6751
6752 // There is nothing to rebuild in a type parameter.
6753 if (isa<TemplateTypeParmDecl>(Param))
6754 continue;
6755
6756 // Rebuild the template parameter list of a template template parameter.
6757 if (TemplateTemplateParmDecl *TTP
6758 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
6759 if (RebuildTemplateParamsInCurrentInstantiation(
6760 TTP->getTemplateParameters()))
6761 return true;
6762
6763 continue;
6764 }
6765
6766 // Rebuild the type of a non-type template parameter.
6767 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
6768 TypeSourceInfo *NewTSI
6769 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
6770 NTTP->getLocation(),
6771 NTTP->getDeclName());
6772 if (!NewTSI)
6773 return true;
6774
6775 if (NewTSI != NTTP->getTypeSourceInfo()) {
6776 NTTP->setTypeSourceInfo(NewTSI);
6777 NTTP->setType(NewTSI->getType());
6778 }
6779 }
6780
6781 return false;
6782}
6783
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006784/// \brief Produces a formatted string that describes the binding of
6785/// template parameters to template arguments.
6786std::string
6787Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6788 const TemplateArgumentList &Args) {
Douglas Gregor910f8002010-11-07 23:05:16 +00006789 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregor9148c3f2009-11-11 19:13:48 +00006790}
6791
6792std::string
6793Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6794 const TemplateArgument *Args,
6795 unsigned NumArgs) {
Douglas Gregor87dd6972010-12-20 16:52:59 +00006796 llvm::SmallString<128> Str;
6797 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006798
Douglas Gregor9148c3f2009-11-11 19:13:48 +00006799 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor87dd6972010-12-20 16:52:59 +00006800 return std::string();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006801
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006802 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00006803 if (I >= NumArgs)
6804 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006805
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006806 if (I == 0)
Douglas Gregor87dd6972010-12-20 16:52:59 +00006807 Out << "[with ";
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006808 else
Douglas Gregor87dd6972010-12-20 16:52:59 +00006809 Out << ", ";
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006810
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006811 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor87dd6972010-12-20 16:52:59 +00006812 Out << Id->getName();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006813 } else {
Douglas Gregor87dd6972010-12-20 16:52:59 +00006814 Out << '$' << I;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006815 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006816
Douglas Gregor87dd6972010-12-20 16:52:59 +00006817 Out << " = ";
Douglas Gregor8987b232011-09-27 23:30:47 +00006818 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006819 }
Douglas Gregor87dd6972010-12-20 16:52:59 +00006820
6821 Out << ']';
6822 return Out.str();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006823}
Francois Pichet8387e2a2011-04-22 22:18:13 +00006824
6825void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, bool Flag) {
6826 if (!FD)
6827 return;
6828 FD->setLateTemplateParsed(Flag);
6829}
6830
6831bool Sema::IsInsideALocalClassWithinATemplateFunction() {
6832 DeclContext *DC = CurContext;
6833
6834 while (DC) {
6835 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
6836 const FunctionDecl *FD = RD->isLocalClass();
6837 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
6838 } else if (DC->isTranslationUnit() || DC->isNamespace())
6839 return false;
6840
6841 DC = DC->getParent();
6842 }
6843 return false;
6844}