blob: 5df84d66a4a7f85ea9379f30fd70fb8a2f50b4bc [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
John McCallf7a1a742009-11-24 19:00:30 +000079static void FilterAcceptableTemplateNames(ASTContext &C, 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();
John McCallad00b772010-06-16 08:42:20 +000085 NamedDecl *Repl = isAcceptableTemplateName(C, 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:
91 // A lookup that finds an injected-class-name (10.2) can result in an
92 // ambiguity in certain cases (for example, if it is found in more than
93 // 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
95 // is followed by a template-argument-list, the reference refers to the
96 // class template itself and not a specialization thereof, and is not
97 // ambiguous.
98 //
99 // FIXME: Will we eventually have to do the same for alias templates?
100 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
101 if (!ClassTemplates.insert(ClassTmpl)) {
102 filter.erase();
103 continue;
104 }
John McCall8ba66912010-08-13 07:02:08 +0000105
106 // FIXME: we promote access to public here as a workaround to
107 // the fact that LookupResult doesn't let us remember that we
108 // found this template through a particular injected class name,
109 // which means we end up doing nasty things to the invariants.
110 // Pretending that access is public is *much* safer.
111 filter.replace(Repl, AS_public);
Douglas Gregor01e56ae2010-04-12 20:54:26 +0000112 }
John McCallf7a1a742009-11-24 19:00:30 +0000113 }
114 filter.done();
115}
116
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000117TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000118 CXXScopeSpec &SS,
Abramo Bagnara7c153532010-08-06 12:11:11 +0000119 bool hasTemplateKeyword,
Douglas Gregor014e88d2009-11-03 23:16:33 +0000120 UnqualifiedId &Name,
John McCallb3d87482010-08-24 05:47:05 +0000121 ParsedType ObjectTypePtr,
Douglas Gregor495c35d2009-08-25 22:51:20 +0000122 bool EnteringContext,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000123 TemplateTy &TemplateResult,
124 bool &MemberOfUnknownSpecialization) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000125 assert(getLangOptions().CPlusPlus && "No template names in C!");
126
Douglas Gregor014e88d2009-11-03 23:16:33 +0000127 DeclarationName TName;
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000128 MemberOfUnknownSpecialization = false;
Douglas Gregor014e88d2009-11-03 23:16:33 +0000129
130 switch (Name.getKind()) {
131 case UnqualifiedId::IK_Identifier:
132 TName = DeclarationName(Name.Identifier);
133 break;
134
135 case UnqualifiedId::IK_OperatorFunctionId:
136 TName = Context.DeclarationNames.getCXXOperatorName(
137 Name.OperatorFunctionId.Operator);
138 break;
139
Sean Hunte6252d12009-11-28 08:58:14 +0000140 case UnqualifiedId::IK_LiteralOperatorId:
Sean Hunt3e518bd2009-11-29 07:34:05 +0000141 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
142 break;
Sean Hunte6252d12009-11-28 08:58:14 +0000143
Douglas Gregor014e88d2009-11-03 23:16:33 +0000144 default:
145 return TNK_Non_template;
146 }
Mike Stump1eb44332009-09-09 15:08:12 +0000147
John McCallb3d87482010-08-24 05:47:05 +0000148 QualType ObjectType = ObjectTypePtr.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000149
Douglas Gregorbfea2392009-12-31 08:11:17 +0000150 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
151 LookupOrdinaryName);
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000152 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
153 MemberOfUnknownSpecialization);
John McCall67d22fb2010-08-28 20:17:00 +0000154 if (R.empty()) return TNK_Non_template;
155 if (R.isAmbiguous()) {
156 // Suppress diagnostics; we'll redo this lookup later.
John McCallb8592062010-08-13 02:23:42 +0000157 R.suppressDiagnostics();
John McCall67d22fb2010-08-28 20:17:00 +0000158
159 // FIXME: we might have ambiguous templates, in which case we
160 // should at least parse them properly!
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000161 return TNK_Non_template;
John McCallb8592062010-08-13 02:23:42 +0000162 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000163
John McCall0bd6feb2009-12-02 08:04:21 +0000164 TemplateName Template;
165 TemplateNameKind TemplateKind;
Mike Stump1eb44332009-09-09 15:08:12 +0000166
John McCall0bd6feb2009-12-02 08:04:21 +0000167 unsigned ResultCount = R.end() - R.begin();
168 if (ResultCount > 1) {
169 // We assume that we'll preserve the qualifier from a function
170 // template name in other ways.
171 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
172 TemplateKind = TNK_Function_template;
John McCallb8592062010-08-13 02:23:42 +0000173
174 // We'll do this lookup again later.
175 R.suppressDiagnostics();
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000176 } else {
John McCall0bd6feb2009-12-02 08:04:21 +0000177 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
178
179 if (SS.isSet() && !SS.isInvalid()) {
180 NestedNameSpecifier *Qualifier
181 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Abramo Bagnara7c153532010-08-06 12:11:11 +0000182 Template = Context.getQualifiedTemplateName(Qualifier,
183 hasTemplateKeyword, TD);
John McCall0bd6feb2009-12-02 08:04:21 +0000184 } else {
185 Template = TemplateName(TD);
186 }
187
John McCallb8592062010-08-13 02:23:42 +0000188 if (isa<FunctionTemplateDecl>(TD)) {
John McCall0bd6feb2009-12-02 08:04:21 +0000189 TemplateKind = TNK_Function_template;
John McCallb8592062010-08-13 02:23:42 +0000190
191 // We'll do this lookup again later.
192 R.suppressDiagnostics();
193 } else {
John McCall0bd6feb2009-12-02 08:04:21 +0000194 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
195 TemplateKind = TNK_Type_template;
196 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000197 }
Mike Stump1eb44332009-09-09 15:08:12 +0000198
John McCall0bd6feb2009-12-02 08:04:21 +0000199 TemplateResult = TemplateTy::make(Template);
200 return TemplateKind;
John McCallf7a1a742009-11-24 19:00:30 +0000201}
202
Douglas Gregor84d0a192010-01-12 21:28:44 +0000203bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
204 SourceLocation IILoc,
205 Scope *S,
206 const CXXScopeSpec *SS,
207 TemplateTy &SuggestedTemplate,
208 TemplateNameKind &SuggestedKind) {
209 // We can't recover unless there's a dependent scope specifier preceding the
210 // template name.
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000211 // FIXME: Typo correction?
Douglas Gregor84d0a192010-01-12 21:28:44 +0000212 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
213 computeDeclContext(*SS))
214 return false;
215
216 // The code is missing a 'template' keyword prior to the dependent template
217 // name.
218 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
219 Diag(IILoc, diag::err_template_kw_missing)
220 << Qualifier << II.getName()
Douglas Gregor849b2432010-03-31 17:46:05 +0000221 << FixItHint::CreateInsertion(IILoc, "template ");
Douglas Gregor84d0a192010-01-12 21:28:44 +0000222 SuggestedTemplate
223 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
224 SuggestedKind = TNK_Dependent_template_name;
225 return true;
226}
227
John McCallf7a1a742009-11-24 19:00:30 +0000228void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000229 Scope *S, CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +0000230 QualType ObjectType,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000231 bool EnteringContext,
232 bool &MemberOfUnknownSpecialization) {
John McCallf7a1a742009-11-24 19:00:30 +0000233 // Determine where to perform name lookup
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000234 MemberOfUnknownSpecialization = false;
John McCallf7a1a742009-11-24 19:00:30 +0000235 DeclContext *LookupCtx = 0;
236 bool isDependent = false;
237 if (!ObjectType.isNull()) {
238 // This nested-name-specifier occurs in a member access expression, e.g.,
239 // x->B::f, and we are looking into the type of the object.
240 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
241 LookupCtx = computeDeclContext(ObjectType);
242 isDependent = ObjectType->isDependentType();
243 assert((isDependent || !ObjectType->isIncompleteType()) &&
244 "Caller should have completed object type");
245 } else if (SS.isSet()) {
246 // This nested-name-specifier occurs after another nested-name-specifier,
247 // so long into the context associated with the prior nested-name-specifier.
248 LookupCtx = computeDeclContext(SS, EnteringContext);
249 isDependent = isDependentScopeSpecifier(SS);
250
251 // The declaration context must be complete.
John McCall77bb1aa2010-05-01 00:40:08 +0000252 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCallf7a1a742009-11-24 19:00:30 +0000253 return;
254 }
255
256 bool ObjectTypeSearchedInScope = false;
257 if (LookupCtx) {
258 // Perform "qualified" name lookup into the declaration context we
259 // computed, which is either the type of the base of a member access
260 // expression or the declaration context associated with a prior
261 // nested-name-specifier.
262 LookupQualifiedName(Found, LookupCtx);
263
264 if (!ObjectType.isNull() && Found.empty()) {
265 // C++ [basic.lookup.classref]p1:
266 // In a class member access expression (5.2.5), if the . or -> token is
267 // immediately followed by an identifier followed by a <, the
268 // identifier must be looked up to determine whether the < is the
269 // beginning of a template argument list (14.2) or a less-than operator.
270 // The identifier is first looked up in the class of the object
271 // expression. If the identifier is not found, it is then looked up in
272 // the context of the entire postfix-expression and shall name a class
273 // or function template.
John McCallf7a1a742009-11-24 19:00:30 +0000274 if (S) LookupName(Found, S);
275 ObjectTypeSearchedInScope = true;
276 }
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000277 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregor2e933882010-01-12 17:06:20 +0000278 // We cannot look into a dependent object type or nested nme
279 // specifier.
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000280 MemberOfUnknownSpecialization = true;
John McCallf7a1a742009-11-24 19:00:30 +0000281 return;
282 } else {
283 // Perform unqualified name lookup in the current scope.
284 LookupName(Found, S);
285 }
286
Douglas Gregor2e933882010-01-12 17:06:20 +0000287 if (Found.empty() && !isDependent) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000288 // If we did not find any names, attempt to correct any typos.
289 DeclarationName Name = Found.getLookupName();
Douglas Gregoraaf87162010-04-14 20:04:41 +0000290 if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx,
Douglas Gregor12eb5d62010-06-29 19:27:42 +0000291 false, CTC_CXXCasts)) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000292 FilterAcceptableTemplateNames(Context, Found);
John McCallad00b772010-06-16 08:42:20 +0000293 if (!Found.empty()) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000294 if (LookupCtx)
295 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
296 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000297 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorbfea2392009-12-31 08:11:17 +0000298 Found.getLookupName().getAsString());
299 else
300 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
301 << Name << Found.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +0000302 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorbfea2392009-12-31 08:11:17 +0000303 Found.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +0000304 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
305 Diag(Template->getLocation(), diag::note_previous_decl)
306 << Template->getDeclName();
John McCallad00b772010-06-16 08:42:20 +0000307 }
Douglas Gregorbfea2392009-12-31 08:11:17 +0000308 } else {
309 Found.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +0000310 Found.setLookupName(Name);
Douglas Gregorbfea2392009-12-31 08:11:17 +0000311 }
312 }
313
John McCallf7a1a742009-11-24 19:00:30 +0000314 FilterAcceptableTemplateNames(Context, Found);
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000315 if (Found.empty()) {
316 if (isDependent)
317 MemberOfUnknownSpecialization = true;
John McCallf7a1a742009-11-24 19:00:30 +0000318 return;
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000319 }
John McCallf7a1a742009-11-24 19:00:30 +0000320
321 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
322 // C++ [basic.lookup.classref]p1:
323 // [...] If the lookup in the class of the object expression finds a
324 // template, the name is also looked up in the context of the entire
325 // postfix-expression and [...]
326 //
327 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
328 LookupOrdinaryName);
329 LookupName(FoundOuter, S);
330 FilterAcceptableTemplateNames(Context, FoundOuter);
Douglas Gregor01e56ae2010-04-12 20:54:26 +0000331
John McCallf7a1a742009-11-24 19:00:30 +0000332 if (FoundOuter.empty()) {
333 // - if the name is not found, the name found in the class of the
334 // object expression is used, otherwise
335 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
336 // - if the name is found in the context of the entire
337 // postfix-expression and does not name a class template, the name
338 // found in the class of the object expression is used, otherwise
John McCallad00b772010-06-16 08:42:20 +0000339 } else if (!Found.isSuppressingDiagnostics()) {
John McCallf7a1a742009-11-24 19:00:30 +0000340 // - if the name found is a class template, it must refer to the same
341 // entity as the one found in the class of the object expression,
342 // otherwise the program is ill-formed.
343 if (!Found.isSingleResult() ||
344 Found.getFoundDecl()->getCanonicalDecl()
345 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
346 Diag(Found.getNameLoc(),
Jeffrey Yasskin21d07e42010-06-05 01:39:57 +0000347 diag::ext_nested_name_member_ref_lookup_ambiguous)
348 << Found.getLookupName()
349 << ObjectType;
John McCallf7a1a742009-11-24 19:00:30 +0000350 Diag(Found.getRepresentativeDecl()->getLocation(),
351 diag::note_ambig_member_ref_object_type)
352 << ObjectType;
353 Diag(FoundOuter.getFoundDecl()->getLocation(),
354 diag::note_ambig_member_ref_scope);
355
356 // Recover by taking the template that we found in the object
357 // expression's type.
358 }
359 }
360 }
361}
362
John McCall2f841ba2009-12-02 03:53:29 +0000363/// ActOnDependentIdExpression - Handle a dependent id-expression that
364/// was just parsed. This is only possible with an explicit scope
365/// specifier naming a dependent type.
John McCall60d7b3a2010-08-24 06:29:42 +0000366ExprResult
John McCallf7a1a742009-11-24 19:00:30 +0000367Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +0000368 const DeclarationNameInfo &NameInfo,
John McCall2f841ba2009-12-02 03:53:29 +0000369 bool isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +0000370 const TemplateArgumentListInfo *TemplateArgs) {
371 NestedNameSpecifier *Qualifier
372 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallea1471e2010-05-20 01:18:31 +0000373
374 DeclContext *DC = getFunctionLevelDeclContext();
John McCallf7a1a742009-11-24 19:00:30 +0000375
John McCall2f841ba2009-12-02 03:53:29 +0000376 if (!isAddressOfOperand &&
John McCallea1471e2010-05-20 01:18:31 +0000377 isa<CXXMethodDecl>(DC) &&
378 cast<CXXMethodDecl>(DC)->isInstance()) {
379 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCall2f841ba2009-12-02 03:53:29 +0000380
John McCallf7a1a742009-11-24 19:00:30 +0000381 // Since the 'this' expression is synthesized, we don't need to
382 // perform the double-lookup check.
383 NamedDecl *FirstQualifierInScope = 0;
384
John McCallaa81e162009-12-01 22:10:20 +0000385 return Owned(CXXDependentScopeMemberExpr::Create(Context,
386 /*This*/ 0, ThisType,
387 /*IsArrow*/ true,
John McCallf7a1a742009-11-24 19:00:30 +0000388 /*Op*/ SourceLocation(),
389 Qualifier, SS.getRange(),
390 FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +0000391 NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000392 TemplateArgs));
393 }
394
Abramo Bagnara25777432010-08-11 22:01:17 +0000395 return BuildDependentDeclRefExpr(SS, NameInfo, TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +0000396}
397
John McCall60d7b3a2010-08-24 06:29:42 +0000398ExprResult
John McCallf7a1a742009-11-24 19:00:30 +0000399Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +0000400 const DeclarationNameInfo &NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000401 const TemplateArgumentListInfo *TemplateArgs) {
402 return Owned(DependentScopeDeclRefExpr::Create(Context,
403 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
404 SS.getRange(),
Abramo Bagnara25777432010-08-11 22:01:17 +0000405 NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000406 TemplateArgs));
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000407}
408
Douglas Gregor72c3f312008-12-05 18:15:24 +0000409/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
410/// that the template parameter 'PrevDecl' is being shadowed by a new
411/// declaration at location Loc. Returns true to indicate that this is
412/// an error, and false otherwise.
413bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +0000414 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000415
416 // Microsoft Visual C++ permits template parameters to be shadowed.
417 if (getLangOptions().Microsoft)
418 return false;
419
420 // C++ [temp.local]p4:
421 // A template-parameter shall not be redeclared within its
422 // scope (including nested scopes).
Mike Stump1eb44332009-09-09 15:08:12 +0000423 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor72c3f312008-12-05 18:15:24 +0000424 << cast<NamedDecl>(PrevDecl)->getDeclName();
425 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
426 return true;
427}
428
Douglas Gregor2943aed2009-03-03 04:44:36 +0000429/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000430/// the parameter D to reference the templated declaration and return a pointer
431/// to the template declaration. Otherwise, do nothing to D and return null.
John McCalld226f652010-08-21 09:40:31 +0000432TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
433 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
434 D = Temp->getTemplatedDecl();
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000435 return Temp;
436 }
437 return 0;
438}
439
Douglas Gregor788cd062009-11-11 01:00:40 +0000440static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
441 const ParsedTemplateArgument &Arg) {
442
443 switch (Arg.getKind()) {
444 case ParsedTemplateArgument::Type: {
John McCalla93c9342009-12-07 02:54:59 +0000445 TypeSourceInfo *DI;
Douglas Gregor788cd062009-11-11 01:00:40 +0000446 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
447 if (!DI)
John McCalla93c9342009-12-07 02:54:59 +0000448 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor788cd062009-11-11 01:00:40 +0000449 return TemplateArgumentLoc(TemplateArgument(T), DI);
450 }
451
452 case ParsedTemplateArgument::NonType: {
453 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
454 return TemplateArgumentLoc(TemplateArgument(E), E);
455 }
456
457 case ParsedTemplateArgument::Template: {
John McCall2b5289b2010-08-23 07:28:44 +0000458 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregor788cd062009-11-11 01:00:40 +0000459 return TemplateArgumentLoc(TemplateArgument(Template),
460 Arg.getScopeSpec().getRange(),
461 Arg.getLocation());
462 }
463 }
464
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +0000465 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +0000466 return TemplateArgumentLoc();
467}
468
469/// \brief Translates template arguments as provided by the parser
470/// into template arguments used by semantic analysis.
John McCalld5532b62009-11-23 01:53:49 +0000471void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
472 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor788cd062009-11-11 01:00:40 +0000473 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCalld5532b62009-11-23 01:53:49 +0000474 TemplateArgs.addArgument(translateTemplateArgument(*this,
475 TemplateArgsIn[I]));
Douglas Gregor788cd062009-11-11 01:00:40 +0000476}
477
Douglas Gregor72c3f312008-12-05 18:15:24 +0000478/// ActOnTypeParameter - Called when a C++ template type parameter
479/// (e.g., "typename T") has been parsed. Typename specifies whether
480/// the keyword "typename" was used to declare the type parameter
481/// (otherwise, "class" was used), and KeyLoc is the location of the
482/// "class" or "typename" keyword. ParamName is the name of the
483/// parameter (NULL indicates an unnamed template parameter) and
Douglas Gregorefed5c82010-06-16 15:23:05 +0000484/// ParamName is the location of the parameter name (if any).
Douglas Gregor72c3f312008-12-05 18:15:24 +0000485/// If the type parameter has a default argument, it will be added
486/// later via ActOnTypeParameterDefault.
John McCalld226f652010-08-21 09:40:31 +0000487Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
488 SourceLocation EllipsisLoc,
489 SourceLocation KeyLoc,
490 IdentifierInfo *ParamName,
491 SourceLocation ParamNameLoc,
492 unsigned Depth, unsigned Position,
493 SourceLocation EqualLoc,
John McCallb3d87482010-08-24 05:47:05 +0000494 ParsedType DefaultArg) {
Mike Stump1eb44332009-09-09 15:08:12 +0000495 assert(S->isTemplateParamScope() &&
496 "Template type parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000497 bool Invalid = false;
498
499 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000500 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
Douglas Gregorc0b39642010-04-15 23:40:53 +0000501 LookupOrdinaryName,
502 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000503 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000504 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000505 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000506 }
507
Douglas Gregorddc29e12009-02-06 22:42:48 +0000508 SourceLocation Loc = ParamNameLoc;
509 if (!ParamName)
510 Loc = KeyLoc;
511
Douglas Gregor72c3f312008-12-05 18:15:24 +0000512 TemplateTypeParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000513 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
514 Loc, Depth, Position, ParamName, Typename,
Anders Carlsson6d845ae2009-06-12 22:23:22 +0000515 Ellipsis);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000516 if (Invalid)
517 Param->setInvalidDecl();
518
519 if (ParamName) {
520 // Add the template parameter into the current scope.
John McCalld226f652010-08-21 09:40:31 +0000521 S->AddDecl(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000522 IdResolver.AddDecl(Param);
523 }
524
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000525 // Handle the default argument, if provided.
526 if (DefaultArg) {
527 TypeSourceInfo *DefaultTInfo;
528 GetTypeFromParser(DefaultArg, &DefaultTInfo);
529
530 assert(DefaultTInfo && "expected source information for type");
531
532 // C++0x [temp.param]p9:
533 // A default template-argument may be specified for any kind of
534 // template-parameter that is not a template parameter pack.
535 if (Ellipsis) {
536 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
John McCalld226f652010-08-21 09:40:31 +0000537 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000538 }
Douglas Gregor6f526752010-12-16 08:48:57 +0000539
540 // Check for unexpanded parameter packs.
541 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
542 UPPC_DefaultArgument))
543 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000544
545 // Check the template argument itself.
546 if (CheckTemplateArgument(Param, DefaultTInfo)) {
547 Param->setInvalidDecl();
John McCalld226f652010-08-21 09:40:31 +0000548 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000549 }
550
551 Param->setDefaultArgument(DefaultTInfo, false);
552 }
553
John McCalld226f652010-08-21 09:40:31 +0000554 return Param;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000555}
556
Douglas Gregor2943aed2009-03-03 04:44:36 +0000557/// \brief Check that the type of a non-type template parameter is
558/// well-formed.
559///
560/// \returns the (possibly-promoted) parameter type if valid;
561/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump1eb44332009-09-09 15:08:12 +0000562QualType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000563Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora481ec42010-05-23 19:57:01 +0000564 // We don't allow variably-modified types as the type of non-type template
565 // parameters.
566 if (T->isVariablyModifiedType()) {
567 Diag(Loc, diag::err_variably_modified_nontype_template_param)
568 << T;
569 return QualType();
570 }
571
Douglas Gregor2943aed2009-03-03 04:44:36 +0000572 // C++ [temp.param]p4:
573 //
574 // A non-type template-parameter shall have one of the following
575 // (optionally cv-qualified) types:
576 //
577 // -- integral or enumeration type,
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000578 if (T->isIntegralOrEnumerationType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000579 // -- pointer to object or pointer to function,
Eli Friedman13578692010-08-05 02:49:48 +0000580 T->isPointerType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000581 // -- reference to object or reference to function,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000582 T->isReferenceType() ||
583 // -- pointer to member.
584 T->isMemberPointerType() ||
585 // If T is a dependent type, we can't do the check now, so we
586 // assume that it is well-formed.
587 T->isDependentType())
588 return T;
589 // C++ [temp.param]p8:
590 //
591 // A non-type template-parameter of type "array of T" or
592 // "function returning T" is adjusted to be of type "pointer to
593 // T" or "pointer to function returning T", respectively.
594 else if (T->isArrayType())
595 // FIXME: Keep the type prior to promotion?
596 return Context.getArrayDecayedType(T);
597 else if (T->isFunctionType())
598 // FIXME: Keep the type prior to promotion?
599 return Context.getPointerType(T);
Douglas Gregor0fddb972010-05-22 16:17:30 +0000600
Douglas Gregor2943aed2009-03-03 04:44:36 +0000601 Diag(Loc, diag::err_template_nontype_parm_bad_type)
602 << T;
603
604 return QualType();
605}
606
John McCalld226f652010-08-21 09:40:31 +0000607Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
608 unsigned Depth,
609 unsigned Position,
610 SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000611 Expr *Default) {
John McCallbf1a0282010-06-04 23:28:52 +0000612 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
613 QualType T = TInfo->getType();
Douglas Gregor72c3f312008-12-05 18:15:24 +0000614
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000615 assert(S->isTemplateParamScope() &&
616 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000617 bool Invalid = false;
618
619 IdentifierInfo *ParamName = D.getIdentifier();
620 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000621 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +0000622 LookupOrdinaryName,
623 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000624 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000625 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000626 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000627 }
628
Douglas Gregor4d2abba2010-12-16 15:36:43 +0000629 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
630 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000631 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000632 Invalid = true;
633 }
Douglas Gregor781def02010-12-16 08:56:23 +0000634
Douglas Gregor72c3f312008-12-05 18:15:24 +0000635 NonTypeTemplateParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000636 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
637 D.getIdentifierLoc(),
John McCalla93c9342009-12-07 02:54:59 +0000638 Depth, Position, ParamName, T, TInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000639 if (Invalid)
640 Param->setInvalidDecl();
641
642 if (D.getIdentifier()) {
643 // Add the template parameter into the current scope.
John McCalld226f652010-08-21 09:40:31 +0000644 S->AddDecl(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000645 IdResolver.AddDecl(Param);
646 }
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000647
648 // Check the well-formedness of the default template argument, if provided.
John McCall9ae2f072010-08-23 23:25:46 +0000649 if (Default) {
Douglas Gregor6f526752010-12-16 08:48:57 +0000650 // Check for unexpanded parameter packs.
651 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
652 return Param;
653
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000654 TemplateArgument Converted;
655 if (CheckTemplateArgument(Param, Param->getType(), Default, Converted)) {
656 Param->setInvalidDecl();
John McCalld226f652010-08-21 09:40:31 +0000657 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000658 }
659
John McCall9ae2f072010-08-23 23:25:46 +0000660 Param->setDefaultArgument(Default, false);
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000661 }
662
John McCalld226f652010-08-21 09:40:31 +0000663 return Param;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000664}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000665
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000666/// ActOnTemplateTemplateParameter - Called when a C++ template template
667/// parameter (e.g. T in template <template <typename> class T> class array)
668/// has been parsed. S is the current scope.
John McCalld226f652010-08-21 09:40:31 +0000669Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
670 SourceLocation TmpLoc,
671 TemplateParamsTy *Params,
672 IdentifierInfo *Name,
673 SourceLocation NameLoc,
674 unsigned Depth,
675 unsigned Position,
676 SourceLocation EqualLoc,
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000677 const ParsedTemplateArgument &Default) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000678 assert(S->isTemplateParamScope() &&
679 "Template template parameter not in template parameter scope!");
680
681 // Construct the parameter object.
682 TemplateTemplateParmDecl *Param =
John McCall7a9813c2010-01-22 00:28:27 +0000683 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000684 NameLoc.isInvalid()? TmpLoc : NameLoc,
685 Depth, Position, Name,
Douglas Gregor369ea272010-10-21 17:26:49 +0000686 Params);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000687
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000688 // If the template template parameter has a name, then link the identifier
689 // into the scope and lookup mechanisms.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000690 if (Name) {
John McCalld226f652010-08-21 09:40:31 +0000691 S->AddDecl(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000692 IdResolver.AddDecl(Param);
693 }
694
Douglas Gregor6f526752010-12-16 08:48:57 +0000695 if (Params->size() == 0) {
696 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
697 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
698 Param->setInvalidDecl();
699 }
700
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000701 if (!Default.isInvalid()) {
702 // Check only that we have a template template argument. We don't want to
703 // try to check well-formedness now, because our template template parameter
704 // might have dependent types in its template parameters, which we wouldn't
705 // be able to match now.
706 //
707 // If none of the template template parameter's template arguments mention
708 // other template parameters, we could actually perform more checking here.
709 // However, it isn't worth doing.
710 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
711 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
712 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
713 << DefaultArg.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +0000714 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000715 }
716
Douglas Gregor6f526752010-12-16 08:48:57 +0000717 // Check for unexpanded parameter packs.
718 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
719 DefaultArg.getArgument().getAsTemplate(),
720 UPPC_DefaultArgument))
721 return Param;
722
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000723 Param->setDefaultArgument(DefaultArg, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000724 }
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000725
John McCalld226f652010-08-21 09:40:31 +0000726 return Param;
Douglas Gregord684b002009-02-10 19:49:53 +0000727}
728
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000729/// ActOnTemplateParameterList - Builds a TemplateParameterList that
730/// contains the template parameters in Params/NumParams.
731Sema::TemplateParamsTy *
732Sema::ActOnTemplateParameterList(unsigned Depth,
733 SourceLocation ExportLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000734 SourceLocation TemplateLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000735 SourceLocation LAngleLoc,
John McCalld226f652010-08-21 09:40:31 +0000736 Decl **Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000737 SourceLocation RAngleLoc) {
738 if (ExportLoc.isValid())
Douglas Gregor51ffb0c2009-11-25 18:55:14 +0000739 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000740
Douglas Gregorddc29e12009-02-06 22:42:48 +0000741 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbf4ea562009-09-15 16:23:51 +0000742 (NamedDecl**)Params, NumParams,
743 RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000744}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000745
John McCallb6217662010-03-15 10:12:16 +0000746static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
747 if (SS.isSet())
748 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
749 SS.getRange());
750}
751
John McCallf312b1e2010-08-26 23:41:50 +0000752DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000753Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000754 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000755 IdentifierInfo *Name, SourceLocation NameLoc,
756 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000757 TemplateParameterList *TemplateParams,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000758 AccessSpecifier AS) {
Mike Stump1eb44332009-09-09 15:08:12 +0000759 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor05396e22009-08-25 17:23:04 +0000760 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000761 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000762 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000763
764 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000765 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000766 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000767
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000768 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
769 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorddc29e12009-02-06 22:42:48 +0000770
771 // There is no such thing as an unnamed class template.
772 if (!Name) {
773 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000774 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000775 }
776
777 // Find any previous declaration with this name.
Douglas Gregor05396e22009-08-25 17:23:04 +0000778 DeclContext *SemanticContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000779 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +0000780 ForRedeclaration);
Douglas Gregor05396e22009-08-25 17:23:04 +0000781 if (SS.isNotEmpty() && !SS.isInvalid()) {
782 SemanticContext = computeDeclContext(SS, true);
783 if (!SemanticContext) {
784 // FIXME: Produce a reasonable diagnostic here
785 return true;
786 }
Mike Stump1eb44332009-09-09 15:08:12 +0000787
John McCall77bb1aa2010-05-01 00:40:08 +0000788 if (RequireCompleteDeclContext(SS, SemanticContext))
789 return true;
790
John McCalla24dc2e2009-11-17 02:14:36 +0000791 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor05396e22009-08-25 17:23:04 +0000792 } else {
793 SemanticContext = CurContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000794 LookupName(Previous, S);
Douglas Gregor05396e22009-08-25 17:23:04 +0000795 }
Mike Stump1eb44332009-09-09 15:08:12 +0000796
Douglas Gregor57265e32010-04-12 16:00:01 +0000797 if (Previous.isAmbiguous())
798 return true;
799
Douglas Gregorddc29e12009-02-06 22:42:48 +0000800 NamedDecl *PrevDecl = 0;
801 if (Previous.begin() != Previous.end())
Douglas Gregor57265e32010-04-12 16:00:01 +0000802 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000803
Douglas Gregorddc29e12009-02-06 22:42:48 +0000804 // If there is a previous declaration with the same name, check
805 // whether this is a valid redeclaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000806 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorddc29e12009-02-06 22:42:48 +0000807 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000808
809 // We may have found the injected-class-name of a class template,
810 // class template partial specialization, or class template specialization.
811 // In these cases, grab the template that is being defined or specialized.
812 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
813 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
814 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
815 PrevClassTemplate
816 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
817 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
818 PrevClassTemplate
819 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
820 ->getSpecializedTemplate();
821 }
822 }
823
John McCall65c49462009-12-18 11:25:59 +0000824 if (TUK == TUK_Friend) {
John McCalle129d442009-12-17 23:21:11 +0000825 // C++ [namespace.memdef]p3:
826 // [...] When looking for a prior declaration of a class or a function
827 // declared as a friend, and when the name of the friend class or
828 // function is neither a qualified name nor a template-id, scopes outside
829 // the innermost enclosing namespace scope are not considered.
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000830 if (!SS.isSet()) {
831 DeclContext *OutermostContext = CurContext;
832 while (!OutermostContext->isFileContext())
833 OutermostContext = OutermostContext->getLookupParent();
John McCall65c49462009-12-18 11:25:59 +0000834
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000835 if (PrevDecl &&
836 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
837 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
838 SemanticContext = PrevDecl->getDeclContext();
839 } else {
840 // Declarations in outer scopes don't matter. However, the outermost
841 // context we computed is the semantic context for our new
842 // declaration.
843 PrevDecl = PrevClassTemplate = 0;
844 SemanticContext = OutermostContext;
845 }
John McCalle129d442009-12-17 23:21:11 +0000846 }
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000847
John McCalle129d442009-12-17 23:21:11 +0000848 if (CurContext->isDependentContext()) {
849 // If this is a dependent context, we don't want to link the friend
850 // class template to the template in scope, because that would perform
851 // checking of the template parameter lists that can't be performed
852 // until the outer context is instantiated.
853 PrevDecl = PrevClassTemplate = 0;
854 }
855 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
856 PrevDecl = PrevClassTemplate = 0;
Douglas Gregor57265e32010-04-12 16:00:01 +0000857
Douglas Gregorddc29e12009-02-06 22:42:48 +0000858 if (PrevClassTemplate) {
859 // Ensure that the template parameter lists are compatible.
860 if (!TemplateParameterListsAreEqual(TemplateParams,
861 PrevClassTemplate->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +0000862 /*Complain=*/true,
863 TPL_TemplateMatch))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000864 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000865
866 // C++ [temp.class]p4:
867 // In a redeclaration, partial specialization, explicit
868 // specialization or explicit instantiation of a class template,
869 // the class-key shall agree in kind with the original class
870 // template declaration (7.1.5.3).
871 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000872 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000873 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +0000874 << Name
Douglas Gregor849b2432010-03-31 17:46:05 +0000875 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000876 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000877 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000878 }
879
Douglas Gregorddc29e12009-02-06 22:42:48 +0000880 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000881 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +0000882 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000883 Diag(NameLoc, diag::err_redefinition) << Name;
884 Diag(Def->getLocation(), diag::note_previous_definition);
885 // FIXME: Would it make sense to try to "forget" the previous
886 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000887 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000888 }
889 }
890 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
891 // Maybe we will complain about the shadowed template parameter.
892 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
893 // Just pretend that we didn't see the previous declaration.
894 PrevDecl = 0;
895 } else if (PrevDecl) {
896 // C++ [temp]p5:
897 // A class template shall not have the same name as any other
898 // template, class, function, object, enumeration, enumerator,
899 // namespace, or type in the same scope (3.3), except as specified
900 // in (14.5.4).
901 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
902 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000903 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000904 }
905
Douglas Gregord684b002009-02-10 19:49:53 +0000906 // Check the template parameter list of this declaration, possibly
907 // merging in the template parameter list from the previous class
908 // template declaration.
909 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000910 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
911 TPC_ClassTemplate))
Douglas Gregord684b002009-02-10 19:49:53 +0000912 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000913
Douglas Gregor57265e32010-04-12 16:00:01 +0000914 if (SS.isSet()) {
915 // If the name of the template was qualified, we must be defining the
916 // template out-of-line.
917 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
918 !(TUK == TUK_Friend && CurContext->isDependentContext()))
919 Diag(NameLoc, diag::err_member_def_does_not_match)
920 << Name << SemanticContext << SS.getRange();
921 }
922
Mike Stump1eb44332009-09-09 15:08:12 +0000923 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000924 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000925 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000926 PrevClassTemplate->getTemplatedDecl() : 0,
927 /*DelayTypeCreation=*/true);
John McCallb6217662010-03-15 10:12:16 +0000928 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000929
930 ClassTemplateDecl *NewTemplate
931 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
932 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000933 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000934 NewClass->setDescribedClassTemplate(NewTemplate);
935
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000936 // Build the type for the class template declaration now.
Douglas Gregor24bae922010-07-08 18:37:38 +0000937 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCall3cb0ebd2010-03-10 03:28:59 +0000938 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000939 assert(T->isDependentType() && "Class template type is not dependent?");
940 (void)T;
941
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000942 // If we are providing an explicit specialization of a member that is a
943 // class template, make a note of that.
944 if (PrevClassTemplate &&
945 PrevClassTemplate->getInstantiatedFromMemberTemplate())
946 PrevClassTemplate->setMemberSpecialization();
947
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000948 // Set the access specifier.
Douglas Gregord85bea22009-09-26 06:47:28 +0000949 if (!Invalid && TUK != TUK_Friend)
John McCall05b23ea2009-09-14 21:59:20 +0000950 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000951
Douglas Gregorddc29e12009-02-06 22:42:48 +0000952 // Set the lexical context of these templates
953 NewClass->setLexicalDeclContext(CurContext);
954 NewTemplate->setLexicalDeclContext(CurContext);
955
John McCall0f434ec2009-07-31 02:45:11 +0000956 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000957 NewClass->startDefinition();
958
959 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000960 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000961
John McCall05b23ea2009-09-14 21:59:20 +0000962 if (TUK != TUK_Friend)
963 PushOnScopeChains(NewTemplate, S);
964 else {
Douglas Gregord85bea22009-09-26 06:47:28 +0000965 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall05b23ea2009-09-14 21:59:20 +0000966 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregord85bea22009-09-26 06:47:28 +0000967 NewClass->setAccess(PrevClassTemplate->getAccess());
968 }
John McCall05b23ea2009-09-14 21:59:20 +0000969
Douglas Gregord85bea22009-09-26 06:47:28 +0000970 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
971 PrevClassTemplate != NULL);
972
John McCall05b23ea2009-09-14 21:59:20 +0000973 // Friend templates are visible in fairly strange ways.
974 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +0000975 DeclContext *DC = SemanticContext->getRedeclContext();
John McCall05b23ea2009-09-14 21:59:20 +0000976 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
977 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
978 PushOnScopeChains(NewTemplate, EnclosingScope,
979 /* AddToContext = */ false);
980 }
Douglas Gregord85bea22009-09-26 06:47:28 +0000981
982 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
983 NewClass->getLocation(),
984 NewTemplate,
985 /*FIXME:*/NewClass->getLocation());
986 Friend->setAccess(AS_public);
987 CurContext->addDecl(Friend);
John McCall05b23ea2009-09-14 21:59:20 +0000988 }
Douglas Gregorddc29e12009-02-06 22:42:48 +0000989
Douglas Gregord684b002009-02-10 19:49:53 +0000990 if (Invalid) {
991 NewTemplate->setInvalidDecl();
992 NewClass->setInvalidDecl();
993 }
John McCalld226f652010-08-21 09:40:31 +0000994 return NewTemplate;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000995}
996
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000997/// \brief Diagnose the presence of a default template argument on a
998/// template parameter, which is ill-formed in certain contexts.
999///
1000/// \returns true if the default template argument should be dropped.
1001static bool DiagnoseDefaultTemplateArgument(Sema &S,
1002 Sema::TemplateParamListContext TPC,
1003 SourceLocation ParamLoc,
1004 SourceRange DefArgRange) {
1005 switch (TPC) {
1006 case Sema::TPC_ClassTemplate:
1007 return false;
1008
1009 case Sema::TPC_FunctionTemplate:
1010 // C++ [temp.param]p9:
1011 // A default template-argument shall not be specified in a
1012 // function template declaration or a function template
1013 // definition [...]
1014 // (This sentence is not in C++0x, per DR226).
1015 if (!S.getLangOptions().CPlusPlus0x)
1016 S.Diag(ParamLoc,
1017 diag::err_template_parameter_default_in_function_template)
1018 << DefArgRange;
1019 return false;
1020
1021 case Sema::TPC_ClassTemplateMember:
1022 // C++0x [temp.param]p9:
1023 // A default template-argument shall not be specified in the
1024 // template-parameter-lists of the definition of a member of a
1025 // class template that appears outside of the member's class.
1026 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1027 << DefArgRange;
1028 return true;
1029
1030 case Sema::TPC_FriendFunctionTemplate:
1031 // C++ [temp.param]p9:
1032 // A default template-argument shall not be specified in a
1033 // friend template declaration.
1034 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1035 << DefArgRange;
1036 return true;
1037
1038 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1039 // for friend function templates if there is only a single
1040 // declaration (and it is a definition). Strange!
1041 }
1042
1043 return false;
1044}
1045
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001046/// \brief Check for unexpanded parameter packs within the template parameters
1047/// of a template template parameter, recursively.
1048bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP){
1049 TemplateParameterList *Params = TTP->getTemplateParameters();
1050 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1051 NamedDecl *P = Params->getParam(I);
1052 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
1053 if (S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
1054 NTTP->getTypeSourceInfo(),
1055 Sema::UPPC_NonTypeTemplateParameterType))
1056 return true;
1057
1058 continue;
1059 }
1060
1061 if (TemplateTemplateParmDecl *InnerTTP
1062 = dyn_cast<TemplateTemplateParmDecl>(P))
1063 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1064 return true;
1065 }
1066
1067 return false;
1068}
1069
Douglas Gregord684b002009-02-10 19:49:53 +00001070/// \brief Checks the validity of a template parameter list, possibly
1071/// considering the template parameter list from a previous
1072/// declaration.
1073///
1074/// If an "old" template parameter list is provided, it must be
1075/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1076/// template parameter list.
1077///
1078/// \param NewParams Template parameter list for a new template
1079/// declaration. This template parameter list will be updated with any
1080/// default arguments that are carried through from the previous
1081/// template parameter list.
1082///
1083/// \param OldParams If provided, template parameter list from a
1084/// previous declaration of the same template. Default template
1085/// arguments will be merged from the old template parameter list to
1086/// the new template parameter list.
1087///
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001088/// \param TPC Describes the context in which we are checking the given
1089/// template parameter list.
1090///
Douglas Gregord684b002009-02-10 19:49:53 +00001091/// \returns true if an error occurred, false otherwise.
1092bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001093 TemplateParameterList *OldParams,
1094 TemplateParamListContext TPC) {
Douglas Gregord684b002009-02-10 19:49:53 +00001095 bool Invalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001096
Douglas Gregord684b002009-02-10 19:49:53 +00001097 // C++ [temp.param]p10:
1098 // The set of default template-arguments available for use with a
1099 // template declaration or definition is obtained by merging the
1100 // default arguments from the definition (if in scope) and all
1101 // declarations in scope in the same way default function
1102 // arguments are (8.3.6).
1103 bool SawDefaultArgument = false;
1104 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001105
Anders Carlsson49d25572009-06-12 23:20:15 +00001106 bool SawParameterPack = false;
1107 SourceLocation ParameterPackLoc;
1108
Mike Stump1a35fde2009-02-11 23:03:27 +00001109 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +00001110 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +00001111 if (OldParams)
1112 OldParam = OldParams->begin();
1113
1114 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1115 NewParamEnd = NewParams->end();
1116 NewParam != NewParamEnd; ++NewParam) {
1117 // Variables used to diagnose redundant default arguments
1118 bool RedundantDefaultArg = false;
1119 SourceLocation OldDefaultLoc;
1120 SourceLocation NewDefaultLoc;
1121
1122 // Variables used to diagnose missing default arguments
1123 bool MissingDefaultArg = false;
1124
Anders Carlsson49d25572009-06-12 23:20:15 +00001125 // C++0x [temp.param]p11:
1126 // If a template parameter of a class template is a template parameter pack,
1127 // it must be the last template parameter.
1128 if (SawParameterPack) {
Mike Stump1eb44332009-09-09 15:08:12 +00001129 Diag(ParameterPackLoc,
Anders Carlsson49d25572009-06-12 23:20:15 +00001130 diag::err_template_param_pack_must_be_last_template_parameter);
1131 Invalid = true;
1132 }
1133
Douglas Gregord684b002009-02-10 19:49:53 +00001134 if (TemplateTypeParmDecl *NewTypeParm
1135 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001136 // Check the presence of a default argument here.
1137 if (NewTypeParm->hasDefaultArgument() &&
1138 DiagnoseDefaultTemplateArgument(*this, TPC,
1139 NewTypeParm->getLocation(),
1140 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001141 .getSourceRange()))
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001142 NewTypeParm->removeDefaultArgument();
1143
1144 // Merge default arguments for template type parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00001145 TemplateTypeParmDecl *OldTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001146 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001147
Anders Carlsson49d25572009-06-12 23:20:15 +00001148 if (NewTypeParm->isParameterPack()) {
1149 assert(!NewTypeParm->hasDefaultArgument() &&
1150 "Parameter packs can't have a default argument!");
1151 SawParameterPack = true;
1152 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001153 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall833ca992009-10-29 08:12:44 +00001154 NewTypeParm->hasDefaultArgument()) {
Douglas Gregord684b002009-02-10 19:49:53 +00001155 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1156 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1157 SawDefaultArgument = true;
1158 RedundantDefaultArg = true;
1159 PreviousDefaultArgLoc = NewDefaultLoc;
1160 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1161 // Merge the default argument from the old declaration to the
1162 // new declaration.
1163 SawDefaultArgument = true;
John McCall833ca992009-10-29 08:12:44 +00001164 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregord684b002009-02-10 19:49:53 +00001165 true);
1166 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1167 } else if (NewTypeParm->hasDefaultArgument()) {
1168 SawDefaultArgument = true;
1169 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1170 } else if (SawDefaultArgument)
1171 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001172 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001173 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001174 // Check for unexpanded parameter packs.
1175 if (DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
1176 NewNonTypeParm->getTypeSourceInfo(),
1177 UPPC_NonTypeTemplateParameterType)) {
1178 Invalid = true;
1179 continue;
1180 }
1181
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001182 // Check the presence of a default argument here.
1183 if (NewNonTypeParm->hasDefaultArgument() &&
1184 DiagnoseDefaultTemplateArgument(*this, TPC,
1185 NewNonTypeParm->getLocation(),
1186 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001187 NewNonTypeParm->removeDefaultArgument();
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001188 }
1189
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001190 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001191 NonTypeTemplateParmDecl *OldNonTypeParm
1192 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001193 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001194 NewNonTypeParm->hasDefaultArgument()) {
1195 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1196 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1197 SawDefaultArgument = true;
1198 RedundantDefaultArg = true;
1199 PreviousDefaultArgLoc = NewDefaultLoc;
1200 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1201 // Merge the default argument from the old declaration to the
1202 // new declaration.
1203 SawDefaultArgument = true;
1204 // FIXME: We need to create a new kind of "default argument"
1205 // expression that points to a previous template template
1206 // parameter.
1207 NewNonTypeParm->setDefaultArgument(
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001208 OldNonTypeParm->getDefaultArgument(),
1209 /*Inherited=*/ true);
Douglas Gregord684b002009-02-10 19:49:53 +00001210 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1211 } else if (NewNonTypeParm->hasDefaultArgument()) {
1212 SawDefaultArgument = true;
1213 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1214 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001215 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001216 } else {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001217 // Check the presence of a default argument here.
Douglas Gregord684b002009-02-10 19:49:53 +00001218 TemplateTemplateParmDecl *NewTemplateParm
1219 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001220
1221 // Check for unexpanded parameter packs, recursively.
1222 if (DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
1223 Invalid = true;
1224 continue;
1225 }
1226
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001227 if (NewTemplateParm->hasDefaultArgument() &&
1228 DiagnoseDefaultTemplateArgument(*this, TPC,
1229 NewTemplateParm->getLocation(),
1230 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001231 NewTemplateParm->removeDefaultArgument();
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001232
1233 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001234 TemplateTemplateParmDecl *OldTemplateParm
1235 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001236 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001237 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor788cd062009-11-11 01:00:40 +00001238 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1239 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001240 SawDefaultArgument = true;
1241 RedundantDefaultArg = true;
1242 PreviousDefaultArgLoc = NewDefaultLoc;
1243 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1244 // Merge the default argument from the old declaration to the
1245 // new declaration.
1246 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +00001247 // FIXME: We need to create a new kind of "default argument" expression
1248 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +00001249 NewTemplateParm->setDefaultArgument(
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001250 OldTemplateParm->getDefaultArgument(),
1251 /*Inherited=*/ true);
Douglas Gregor788cd062009-11-11 01:00:40 +00001252 PreviousDefaultArgLoc
1253 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001254 } else if (NewTemplateParm->hasDefaultArgument()) {
1255 SawDefaultArgument = true;
Douglas Gregor788cd062009-11-11 01:00:40 +00001256 PreviousDefaultArgLoc
1257 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001258 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001259 MissingDefaultArg = true;
Douglas Gregord684b002009-02-10 19:49:53 +00001260 }
1261
1262 if (RedundantDefaultArg) {
1263 // C++ [temp.param]p12:
1264 // A template-parameter shall not be given default arguments
1265 // by two different declarations in the same scope.
1266 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1267 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1268 Invalid = true;
1269 } else if (MissingDefaultArg) {
1270 // C++ [temp.param]p11:
1271 // If a template-parameter has a default template-argument,
1272 // all subsequent template-parameters shall have a default
1273 // template-argument supplied.
Mike Stump1eb44332009-09-09 15:08:12 +00001274 Diag((*NewParam)->getLocation(),
Douglas Gregord684b002009-02-10 19:49:53 +00001275 diag::err_template_param_default_arg_missing);
1276 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1277 Invalid = true;
1278 }
1279
1280 // If we have an old template parameter list that we're merging
1281 // in, move on to the next parameter.
1282 if (OldParams)
1283 ++OldParam;
1284 }
1285
1286 return Invalid;
1287}
Douglas Gregorc15cb382009-02-09 23:23:08 +00001288
John McCall4e2cbb22010-10-20 05:44:58 +00001289namespace {
1290
1291/// A class which looks for a use of a certain level of template
1292/// parameter.
1293struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1294 typedef RecursiveASTVisitor<DependencyChecker> super;
1295
1296 unsigned Depth;
1297 bool Match;
1298
1299 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1300 NamedDecl *ND = Params->getParam(0);
1301 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1302 Depth = PD->getDepth();
1303 } else if (NonTypeTemplateParmDecl *PD =
1304 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1305 Depth = PD->getDepth();
1306 } else {
1307 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1308 }
1309 }
1310
1311 bool Matches(unsigned ParmDepth) {
1312 if (ParmDepth >= Depth) {
1313 Match = true;
1314 return true;
1315 }
1316 return false;
1317 }
1318
1319 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1320 return !Matches(T->getDepth());
1321 }
1322
1323 bool TraverseTemplateName(TemplateName N) {
1324 if (TemplateTemplateParmDecl *PD =
1325 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
1326 if (Matches(PD->getDepth())) return false;
1327 return super::TraverseTemplateName(N);
1328 }
1329
1330 bool VisitDeclRefExpr(DeclRefExpr *E) {
1331 if (NonTypeTemplateParmDecl *PD =
1332 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) {
1333 if (PD->getDepth() == Depth) {
1334 Match = true;
1335 return false;
1336 }
1337 }
1338 return super::VisitDeclRefExpr(E);
1339 }
1340};
1341}
1342
1343/// Determines whether a template-id depends on the given parameter
1344/// list.
1345static bool
1346DependsOnTemplateParameters(const TemplateSpecializationType *TemplateId,
1347 TemplateParameterList *Params) {
1348 DependencyChecker Checker(Params);
1349 Checker.TraverseType(QualType(TemplateId, 0));
1350 return Checker.Match;
1351}
1352
Mike Stump1eb44332009-09-09 15:08:12 +00001353/// \brief Match the given template parameter lists to the given scope
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001354/// specifier, returning the template parameter list that applies to the
1355/// name.
1356///
1357/// \param DeclStartLoc the start of the declaration that has a scope
1358/// specifier or a template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +00001359///
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001360/// \param SS the scope specifier that will be matched to the given template
1361/// parameter lists. This scope specifier precedes a qualified name that is
1362/// being declared.
1363///
1364/// \param ParamLists the template parameter lists, from the outermost to the
1365/// innermost template parameter lists.
1366///
1367/// \param NumParamLists the number of template parameter lists in ParamLists.
1368///
John McCall77e8b112010-04-13 20:37:33 +00001369/// \param IsFriend Whether to apply the slightly different rules for
1370/// matching template parameters to scope specifiers in friend
1371/// declarations.
1372///
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001373/// \param IsExplicitSpecialization will be set true if the entity being
1374/// declared is an explicit specialization, false otherwise.
1375///
Mike Stump1eb44332009-09-09 15:08:12 +00001376/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001377/// name that is preceded by the scope specifier @p SS. This template
1378/// parameter list may be have template parameters (if we're declaring a
Mike Stump1eb44332009-09-09 15:08:12 +00001379/// template) or may have no template parameters (if we're declaring a
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001380/// template specialization), or may be NULL (if we were's declaring isn't
1381/// itself a template).
1382TemplateParameterList *
1383Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1384 const CXXScopeSpec &SS,
1385 TemplateParameterList **ParamLists,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001386 unsigned NumParamLists,
John McCall77e8b112010-04-13 20:37:33 +00001387 bool IsFriend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001388 bool &IsExplicitSpecialization,
1389 bool &Invalid) {
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001390 IsExplicitSpecialization = false;
1391
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001392 // Find the template-ids that occur within the nested-name-specifier. These
1393 // template-ids will match up with the template parameter lists.
1394 llvm::SmallVector<const TemplateSpecializationType *, 4>
1395 TemplateIdsInSpecifier;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001396 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1397 ExplicitSpecializationsInSpecifier;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001398 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1399 NNS; NNS = NNS->getPrefix()) {
John McCall4b2b02b2009-12-15 02:19:47 +00001400 const Type *T = NNS->getAsType();
1401 if (!T) break;
1402
1403 // C++0x [temp.expl.spec]p17:
1404 // A member or a member template may be nested within many
1405 // enclosing class templates. In an explicit specialization for
1406 // such a member, the member declaration shall be preceded by a
1407 // template<> for each enclosing class template that is
1408 // explicitly specialized.
Douglas Gregorfe331062010-02-13 05:23:25 +00001409 //
1410 // Following the existing practice of GNU and EDG, we allow a typedef of a
1411 // template specialization type.
John McCall49f4e1c2010-12-10 11:01:00 +00001412 while (const TypedefType *TT = dyn_cast<TypedefType>(T))
1413 T = TT->getDecl()->getUnderlyingType().getTypePtr();
John McCall4b2b02b2009-12-15 02:19:47 +00001414
Mike Stump1eb44332009-09-09 15:08:12 +00001415 if (const TemplateSpecializationType *SpecType
Douglas Gregorfe331062010-02-13 05:23:25 +00001416 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001417 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1418 if (!Template)
1419 continue; // FIXME: should this be an error? probably...
Mike Stump1eb44332009-09-09 15:08:12 +00001420
Ted Kremenek6217b802009-07-29 21:53:49 +00001421 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001422 ClassTemplateSpecializationDecl *SpecDecl
1423 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1424 // If the nested name specifier refers to an explicit specialization,
1425 // we don't need a template<> header.
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001426 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1427 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001428 continue;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001429 }
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001430 }
Mike Stump1eb44332009-09-09 15:08:12 +00001431
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001432 TemplateIdsInSpecifier.push_back(SpecType);
1433 }
1434 }
Mike Stump1eb44332009-09-09 15:08:12 +00001435
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001436 // Reverse the list of template-ids in the scope specifier, so that we can
1437 // more easily match up the template-ids and the template parameter lists.
1438 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001439
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001440 SourceLocation FirstTemplateLoc = DeclStartLoc;
1441 if (NumParamLists)
1442 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001443
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001444 // Match the template-ids found in the specifier to the template parameter
1445 // lists.
John McCall4e2cbb22010-10-20 05:44:58 +00001446 unsigned ParamIdx = 0, TemplateIdx = 0;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001447 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
John McCall4e2cbb22010-10-20 05:44:58 +00001448 TemplateIdx != NumTemplateIds; ++TemplateIdx) {
1449 const TemplateSpecializationType *TemplateId
1450 = TemplateIdsInSpecifier[TemplateIdx];
Douglas Gregorb88e8882009-07-30 17:40:51 +00001451 bool DependentTemplateId = TemplateId->isDependentType();
John McCall4e2cbb22010-10-20 05:44:58 +00001452
1453 // In friend declarations we can have template-ids which don't
1454 // depend on the corresponding template parameter lists. But
1455 // assume that empty parameter lists are supposed to match this
1456 // template-id.
1457 if (IsFriend && ParamIdx < NumParamLists && ParamLists[ParamIdx]->size()) {
1458 if (!DependentTemplateId ||
1459 !DependsOnTemplateParameters(TemplateId, ParamLists[ParamIdx]))
1460 continue;
1461 }
1462
1463 if (ParamIdx >= NumParamLists) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001464 // We have a template-id without a corresponding template parameter
1465 // list.
John McCall77e8b112010-04-13 20:37:33 +00001466
1467 // ...which is fine if this is a friend declaration.
1468 if (IsFriend) {
1469 IsExplicitSpecialization = true;
1470 break;
1471 }
1472
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001473 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001474 // FIXME: the location information here isn't great.
1475 Diag(SS.getRange().getBegin(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001476 diag::err_template_spec_needs_template_parameters)
John McCall4e2cbb22010-10-20 05:44:58 +00001477 << QualType(TemplateId, 0)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001478 << SS.getRange();
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001479 Invalid = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001480 } else {
1481 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1482 << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00001483 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001484 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001485 }
1486 return 0;
1487 }
Mike Stump1eb44332009-09-09 15:08:12 +00001488
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001489 // Check the template parameter list against its corresponding template-id.
Douglas Gregorb88e8882009-07-30 17:40:51 +00001490 if (DependentTemplateId) {
John McCall31f17ec2010-04-27 00:57:59 +00001491 TemplateParameterList *ExpectedTemplateParams = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00001492
John McCall31f17ec2010-04-27 00:57:59 +00001493 // Are there cases in (e.g.) friends where this won't match?
1494 if (const InjectedClassNameType *Injected
1495 = TemplateId->getAs<InjectedClassNameType>()) {
1496 CXXRecordDecl *Record = Injected->getDecl();
1497 if (ClassTemplatePartialSpecializationDecl *Partial =
1498 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1499 ExpectedTemplateParams = Partial->getTemplateParameters();
1500 else
1501 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1502 ->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00001503 }
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001504
John McCall31f17ec2010-04-27 00:57:59 +00001505 if (ExpectedTemplateParams)
John McCall4e2cbb22010-10-20 05:44:58 +00001506 TemplateParameterListsAreEqual(ParamLists[ParamIdx],
John McCall31f17ec2010-04-27 00:57:59 +00001507 ExpectedTemplateParams,
1508 true, TPL_TemplateMatch);
1509
John McCall4e2cbb22010-10-20 05:44:58 +00001510 CheckTemplateParameterList(ParamLists[ParamIdx], 0,
1511 TPC_ClassTemplateMember);
1512 } else if (ParamLists[ParamIdx]->size() > 0)
1513 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00001514 diag::err_template_param_list_matches_nontemplate)
1515 << TemplateId
John McCall4e2cbb22010-10-20 05:44:58 +00001516 << ParamLists[ParamIdx]->getSourceRange();
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001517 else
1518 IsExplicitSpecialization = true;
John McCall4e2cbb22010-10-20 05:44:58 +00001519
1520 ++ParamIdx;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001521 }
Mike Stump1eb44332009-09-09 15:08:12 +00001522
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001523 // If there were at least as many template-ids as there were template
1524 // parameter lists, then there are no template parameter lists remaining for
1525 // the declaration itself.
John McCall4e2cbb22010-10-20 05:44:58 +00001526 if (ParamIdx >= NumParamLists)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001527 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001528
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001529 // If there were too many template parameter lists, complain about that now.
John McCall4e2cbb22010-10-20 05:44:58 +00001530 if (ParamIdx != NumParamLists - 1) {
1531 while (ParamIdx < NumParamLists - 1) {
1532 bool isExplicitSpecHeader = ParamLists[ParamIdx]->size() == 0;
1533 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001534 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1535 : diag::err_template_spec_extra_headers)
John McCall4e2cbb22010-10-20 05:44:58 +00001536 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1537 ParamLists[ParamIdx]->getRAngleLoc());
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001538
1539 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1540 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1541 diag::note_explicit_template_spec_does_not_need_header)
1542 << ExplicitSpecializationsInSpecifier.back();
1543 ExplicitSpecializationsInSpecifier.pop_back();
1544 }
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001545
1546 // We have a template parameter list with no corresponding scope, which
1547 // means that the resulting template declaration can't be instantiated
1548 // properly (we'll end up with dependent nodes when we shouldn't).
1549 if (!isExplicitSpecHeader)
1550 Invalid = true;
1551
John McCall4e2cbb22010-10-20 05:44:58 +00001552 ++ParamIdx;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001553 }
1554 }
Mike Stump1eb44332009-09-09 15:08:12 +00001555
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001556 // Return the last template parameter list, which corresponds to the
1557 // entity being declared.
1558 return ParamLists[NumParamLists - 1];
1559}
1560
Douglas Gregor7532dc62009-03-30 22:58:21 +00001561QualType Sema::CheckTemplateIdType(TemplateName Name,
1562 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00001563 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001564 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001565 if (!Template) {
1566 // The template name does not resolve to a template, so we just
1567 // build a dependent template-id type.
John McCalld5532b62009-11-23 01:53:49 +00001568 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001569 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001570
Douglas Gregor40808ce2009-03-09 23:48:35 +00001571 // Check that the template argument list is well-formed for this
1572 // template.
Douglas Gregor910f8002010-11-07 23:05:16 +00001573 llvm::SmallVector<TemplateArgument, 4> Converted;
John McCalld5532b62009-11-23 01:53:49 +00001574 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00001575 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001576 return QualType();
1577
Douglas Gregor910f8002010-11-07 23:05:16 +00001578 assert((Converted.size() == Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +00001579 "Converted template argument list is too short!");
1580
1581 QualType CanonType;
1582
Douglas Gregorcaddba02009-11-12 18:38:13 +00001583 if (Name.isDependent() ||
1584 TemplateSpecializationType::anyDependentTemplateArguments(
John McCalld5532b62009-11-23 01:53:49 +00001585 TemplateArgs)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001586 // This class template specialization is a dependent
1587 // type. Therefore, its canonical type is another class template
1588 // specialization type that contains all of the converted
1589 // arguments in canonical form. This ensures that, e.g., A<T> and
1590 // A<T, T> have identical types when A is declared as:
1591 //
1592 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001593 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00001594 CanonType = Context.getTemplateSpecializationType(CanonName,
Douglas Gregor910f8002010-11-07 23:05:16 +00001595 Converted.data(),
1596 Converted.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001597
Douglas Gregor1275ae02009-07-28 23:00:59 +00001598 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall833ca992009-10-29 08:12:44 +00001599 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001600 // In the future, we need to teach getTemplateSpecializationType to only
1601 // build the canonical type and return that to us.
1602 CanonType = Context.getCanonicalType(CanonType);
John McCall31f17ec2010-04-27 00:57:59 +00001603
1604 // This might work out to be a current instantiation, in which
1605 // case the canonical type needs to be the InjectedClassNameType.
1606 //
1607 // TODO: in theory this could be a simple hashtable lookup; most
1608 // changes to CurContext don't change the set of current
1609 // instantiations.
1610 if (isa<ClassTemplateDecl>(Template)) {
1611 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1612 // If we get out to a namespace, we're done.
1613 if (Ctx->isFileContext()) break;
1614
1615 // If this isn't a record, keep looking.
1616 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1617 if (!Record) continue;
1618
1619 // Look for one of the two cases with InjectedClassNameTypes
1620 // and check whether it's the same template.
1621 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1622 !Record->getDescribedClassTemplate())
1623 continue;
1624
1625 // Fetch the injected class name type and check whether its
1626 // injected type is equal to the type we just built.
1627 QualType ICNT = Context.getTypeDeclType(Record);
1628 QualType Injected = cast<InjectedClassNameType>(ICNT)
1629 ->getInjectedSpecializationType();
1630
1631 if (CanonType != Injected->getCanonicalTypeInternal())
1632 continue;
1633
1634 // If so, the canonical type of this TST is the injected
1635 // class name type of the record we just found.
1636 assert(ICNT.isCanonical());
1637 CanonType = ICNT;
John McCall31f17ec2010-04-27 00:57:59 +00001638 break;
1639 }
1640 }
Mike Stump1eb44332009-09-09 15:08:12 +00001641 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00001642 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001643 // Find the class template specialization declaration that
1644 // corresponds to these arguments.
Douglas Gregor40808ce2009-03-09 23:48:35 +00001645 void *InsertPos = 0;
1646 ClassTemplateSpecializationDecl *Decl
Douglas Gregor910f8002010-11-07 23:05:16 +00001647 = ClassTemplate->findSpecialization(Converted.data(), Converted.size(),
1648 InsertPos);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001649 if (!Decl) {
1650 // This is the first time we have referenced this class template
1651 // specialization. Create the canonical declaration and add it to
1652 // the set of specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00001653 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor13c85772010-05-06 00:28:52 +00001654 ClassTemplate->getTemplatedDecl()->getTagKind(),
1655 ClassTemplate->getDeclContext(),
1656 ClassTemplate->getLocation(),
Douglas Gregor910f8002010-11-07 23:05:16 +00001657 ClassTemplate,
1658 Converted.data(),
1659 Converted.size(), 0);
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001660 ClassTemplate->AddSpecialization(Decl, InsertPos);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001661 Decl->setLexicalDeclContext(CurContext);
1662 }
1663
1664 CanonType = Context.getTypeDeclType(Decl);
John McCall3cb0ebd2010-03-10 03:28:59 +00001665 assert(isa<RecordType>(CanonType) &&
1666 "type of non-dependent specialization is not a RecordType");
Douglas Gregor40808ce2009-03-09 23:48:35 +00001667 }
Mike Stump1eb44332009-09-09 15:08:12 +00001668
Douglas Gregor40808ce2009-03-09 23:48:35 +00001669 // Build the fully-sugared type for this class template
1670 // specialization, which refers back to the class template
1671 // specialization we created or found.
John McCall71d74bc2010-06-13 09:25:03 +00001672 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001673}
1674
John McCallf312b1e2010-08-26 23:41:50 +00001675TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +00001676Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001677 SourceLocation LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001678 ASTTemplateArgsPtr TemplateArgsIn,
John McCall6b2becf2009-09-08 17:47:29 +00001679 SourceLocation RAngleLoc) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001680 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001681
Douglas Gregor40808ce2009-03-09 23:48:35 +00001682 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00001683 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00001684 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001685
John McCalld5532b62009-11-23 01:53:49 +00001686 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001687 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00001688
1689 if (Result.isNull())
1690 return true;
1691
John McCalla93c9342009-12-07 02:54:59 +00001692 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall833ca992009-10-29 08:12:44 +00001693 TemplateSpecializationTypeLoc TL
1694 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1695 TL.setTemplateNameLoc(TemplateLoc);
1696 TL.setLAngleLoc(LAngleLoc);
1697 TL.setRAngleLoc(RAngleLoc);
1698 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1699 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1700
John McCallb3d87482010-08-24 05:47:05 +00001701 return CreateParsedType(Result, DI);
John McCall6b2becf2009-09-08 17:47:29 +00001702}
John McCallf1bbbb42009-09-04 01:14:41 +00001703
Craig Silverstein45ab4b52010-11-18 08:32:02 +00001704TypeResult Sema::ActOnTagTemplateIdType(CXXScopeSpec &SS,
1705 TypeResult TypeResult,
John McCallf312b1e2010-08-26 23:41:50 +00001706 TagUseKind TUK,
1707 TypeSpecifierType TagSpec,
1708 SourceLocation TagLoc) {
John McCall6b2becf2009-09-08 17:47:29 +00001709 if (TypeResult.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00001710 return ::TypeResult();
John McCallf1bbbb42009-09-04 01:14:41 +00001711
John McCalla93c9342009-12-07 02:54:59 +00001712 TypeSourceInfo *DI;
John McCall833ca992009-10-29 08:12:44 +00001713 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCallf1bbbb42009-09-04 01:14:41 +00001714
John McCall6b2becf2009-09-08 17:47:29 +00001715 // Verify the tag specifier.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001716 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump1eb44332009-09-09 15:08:12 +00001717
John McCall6b2becf2009-09-08 17:47:29 +00001718 if (const RecordType *RT = Type->getAs<RecordType>()) {
1719 RecordDecl *D = RT->getDecl();
1720
1721 IdentifierInfo *Id = D->getIdentifier();
1722 assert(Id && "templated class must have an identifier");
1723
1724 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1725 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCallc4e70192009-09-11 04:59:25 +00001726 << Type
Douglas Gregor849b2432010-03-31 17:46:05 +00001727 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCallc4e70192009-09-11 04:59:25 +00001728 Diag(D->getLocation(), diag::note_previous_use);
John McCallf1bbbb42009-09-04 01:14:41 +00001729 }
1730 }
1731
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001732 ElaboratedTypeKeyword Keyword
1733 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1734 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
John McCall6b2becf2009-09-08 17:47:29 +00001735
Craig Silverstein45ab4b52010-11-18 08:32:02 +00001736 TypeSourceInfo *ElabDI = Context.CreateTypeSourceInfo(ElabType);
1737 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(ElabDI->getTypeLoc());
1738 TL.setKeywordLoc(TagLoc);
1739 TL.setQualifierRange(SS.getRange());
1740 TL.getNamedTypeLoc().initializeFullCopy(DI->getTypeLoc());
1741 return CreateParsedType(ElabType, ElabDI);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001742}
1743
John McCall60d7b3a2010-08-24 06:29:42 +00001744ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +00001745 LookupResult &R,
1746 bool RequiresADL,
John McCalld5532b62009-11-23 01:53:49 +00001747 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001748 // FIXME: Can we do any checking at this point? I guess we could check the
1749 // template arguments that we have against the template name, if the template
Mike Stump1eb44332009-09-09 15:08:12 +00001750 // name refers to a single template. That's not a terribly common case,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001751 // though.
John McCallf7a1a742009-11-24 19:00:30 +00001752
1753 // These should be filtered out by our callers.
1754 assert(!R.empty() && "empty lookup results when building templateid");
1755 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1756
1757 NestedNameSpecifier *Qualifier = 0;
1758 SourceRange QualifierRange;
1759 if (SS.isSet()) {
1760 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1761 QualifierRange = SS.getRange();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001762 }
John McCallc373d482010-01-27 01:50:18 +00001763
1764 // We don't want lookup warnings at this point.
1765 R.suppressDiagnostics();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001766
John McCallf7a1a742009-11-24 19:00:30 +00001767 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00001768 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
John McCallf7a1a742009-11-24 19:00:30 +00001769 Qualifier, QualifierRange,
Abramo Bagnara25777432010-08-11 22:01:17 +00001770 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00001771 RequiresADL, TemplateArgs,
1772 R.begin(), R.end());
John McCallf7a1a742009-11-24 19:00:30 +00001773
1774 return Owned(ULE);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001775}
1776
John McCallf7a1a742009-11-24 19:00:30 +00001777// We actually only call this from template instantiation.
John McCall60d7b3a2010-08-24 06:29:42 +00001778ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001779Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001780 const DeclarationNameInfo &NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +00001781 const TemplateArgumentListInfo &TemplateArgs) {
1782 DeclContext *DC;
1783 if (!(DC = computeDeclContext(SS, false)) ||
1784 DC->isDependentContext() ||
John McCall77bb1aa2010-05-01 00:40:08 +00001785 RequireCompleteDeclContext(SS, DC))
Abramo Bagnara25777432010-08-11 22:01:17 +00001786 return BuildDependentDeclRefExpr(SS, NameInfo, &TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001787
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001788 bool MemberOfUnknownSpecialization;
Abramo Bagnara25777432010-08-11 22:01:17 +00001789 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001790 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1791 MemberOfUnknownSpecialization);
Mike Stump1eb44332009-09-09 15:08:12 +00001792
John McCallf7a1a742009-11-24 19:00:30 +00001793 if (R.isAmbiguous())
1794 return ExprError();
1795
1796 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001797 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
1798 << NameInfo.getName() << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001799 return ExprError();
1800 }
1801
1802 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001803 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
1804 << (NestedNameSpecifier*) SS.getScopeRep()
1805 << NameInfo.getName() << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001806 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1807 return ExprError();
1808 }
1809
1810 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001811}
1812
Douglas Gregorc45c2322009-03-31 00:43:58 +00001813/// \brief Form a dependent template name.
1814///
1815/// This action forms a dependent template name given the template
1816/// name and its (presumably dependent) scope specifier. For
1817/// example, given "MetaFun::template apply", the scope specifier \p
1818/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1819/// of the "template" keyword, and "apply" is the \p Name.
Douglas Gregord6ab2322010-06-16 23:00:59 +00001820TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
1821 SourceLocation TemplateKWLoc,
1822 CXXScopeSpec &SS,
1823 UnqualifiedId &Name,
John McCallb3d87482010-08-24 05:47:05 +00001824 ParsedType ObjectType,
Douglas Gregord6ab2322010-06-16 23:00:59 +00001825 bool EnteringContext,
1826 TemplateTy &Result) {
Douglas Gregor1a15dae2010-06-16 22:31:08 +00001827 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent() &&
1828 !getLangOptions().CPlusPlus0x)
1829 Diag(TemplateKWLoc, diag::ext_template_outside_of_template)
1830 << FixItHint::CreateRemoval(TemplateKWLoc);
1831
Douglas Gregor0707bc52010-01-19 16:01:07 +00001832 DeclContext *LookupCtx = 0;
1833 if (SS.isSet())
1834 LookupCtx = computeDeclContext(SS, EnteringContext);
1835 if (!LookupCtx && ObjectType)
John McCallb3d87482010-08-24 05:47:05 +00001836 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor0707bc52010-01-19 16:01:07 +00001837 if (LookupCtx) {
Douglas Gregorc45c2322009-03-31 00:43:58 +00001838 // C++0x [temp.names]p5:
1839 // If a name prefixed by the keyword template is not the name of
1840 // a template, the program is ill-formed. [Note: the keyword
1841 // template may not be applied to non-template members of class
1842 // templates. -end note ] [ Note: as is the case with the
1843 // typename prefix, the template prefix is allowed in cases
1844 // where it is not strictly necessary; i.e., when the
1845 // nested-name-specifier or the expression on the left of the ->
1846 // or . is not dependent on a template-parameter, or the use
1847 // does not appear in the scope of a template. -end note]
1848 //
1849 // Note: C++03 was more strict here, because it banned the use of
1850 // the "template" keyword prior to a template-name that was not a
1851 // dependent name. C++ DR468 relaxed this requirement (the
1852 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregor732281d2010-06-14 22:07:54 +00001853 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001854 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c153532010-08-06 12:11:11 +00001855 TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name,
1856 ObjectType, EnteringContext, Result,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001857 MemberOfUnknownSpecialization);
Douglas Gregor0707bc52010-01-19 16:01:07 +00001858 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1859 isa<CXXRecordDecl>(LookupCtx) &&
1860 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregord6ab2322010-06-16 23:00:59 +00001861 // This is a dependent template. Handle it below.
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001862 } else if (TNK == TNK_Non_template) {
Douglas Gregor014e88d2009-11-03 23:16:33 +00001863 Diag(Name.getSourceRange().getBegin(),
1864 diag::err_template_kw_refers_to_non_template)
Abramo Bagnara25777432010-08-11 22:01:17 +00001865 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregor0278e122010-05-05 05:58:24 +00001866 << Name.getSourceRange()
1867 << TemplateKWLoc;
Douglas Gregord6ab2322010-06-16 23:00:59 +00001868 return TNK_Non_template;
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001869 } else {
1870 // We found something; return it.
Douglas Gregord6ab2322010-06-16 23:00:59 +00001871 return TNK;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001872 }
Douglas Gregorc45c2322009-03-31 00:43:58 +00001873 }
1874
Mike Stump1eb44332009-09-09 15:08:12 +00001875 NestedNameSpecifier *Qualifier
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001876 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor014e88d2009-11-03 23:16:33 +00001877
1878 switch (Name.getKind()) {
1879 case UnqualifiedId::IK_Identifier:
Douglas Gregord6ab2322010-06-16 23:00:59 +00001880 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1881 Name.Identifier));
1882 return TNK_Dependent_template_name;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001883
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001884 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregord6ab2322010-06-16 23:00:59 +00001885 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001886 Name.OperatorFunctionId.Operator));
Douglas Gregord6ab2322010-06-16 23:00:59 +00001887 return TNK_Dependent_template_name;
Sean Hunte6252d12009-11-28 08:58:14 +00001888
1889 case UnqualifiedId::IK_LiteralOperatorId:
1890 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1891
Douglas Gregor014e88d2009-11-03 23:16:33 +00001892 default:
1893 break;
1894 }
1895
1896 Diag(Name.getSourceRange().getBegin(),
1897 diag::err_template_kw_refers_to_non_template)
Abramo Bagnara25777432010-08-11 22:01:17 +00001898 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregor0278e122010-05-05 05:58:24 +00001899 << Name.getSourceRange()
1900 << TemplateKWLoc;
Douglas Gregord6ab2322010-06-16 23:00:59 +00001901 return TNK_Non_template;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001902}
1903
Mike Stump1eb44332009-09-09 15:08:12 +00001904bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00001905 const TemplateArgumentLoc &AL,
Douglas Gregor910f8002010-11-07 23:05:16 +00001906 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
John McCall833ca992009-10-29 08:12:44 +00001907 const TemplateArgument &Arg = AL.getArgument();
1908
Anders Carlsson436b1562009-06-13 00:33:33 +00001909 // Check template type parameter.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001910 switch(Arg.getKind()) {
1911 case TemplateArgument::Type:
Anders Carlsson436b1562009-06-13 00:33:33 +00001912 // C++ [temp.arg.type]p1:
1913 // A template-argument for a template-parameter which is a
1914 // type shall be a type-id.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001915 break;
1916 case TemplateArgument::Template: {
1917 // We have a template type parameter but the template argument
1918 // is a template without any arguments.
1919 SourceRange SR = AL.getSourceRange();
1920 TemplateName Name = Arg.getAsTemplate();
1921 Diag(SR.getBegin(), diag::err_template_missing_args)
1922 << Name << SR;
1923 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1924 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlsson436b1562009-06-13 00:33:33 +00001925
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001926 return true;
1927 }
1928 default: {
Anders Carlsson436b1562009-06-13 00:33:33 +00001929 // We have a template type parameter but the template argument
1930 // is not a type.
John McCall828bff22009-10-29 18:45:58 +00001931 SourceRange SR = AL.getSourceRange();
1932 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlsson436b1562009-06-13 00:33:33 +00001933 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00001934
Anders Carlsson436b1562009-06-13 00:33:33 +00001935 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001936 }
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001937 }
Anders Carlsson436b1562009-06-13 00:33:33 +00001938
John McCalla93c9342009-12-07 02:54:59 +00001939 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlsson436b1562009-06-13 00:33:33 +00001940 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001941
Anders Carlsson436b1562009-06-13 00:33:33 +00001942 // Add the converted template type argument.
Douglas Gregor910f8002010-11-07 23:05:16 +00001943 Converted.push_back(
John McCall833ca992009-10-29 08:12:44 +00001944 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlsson436b1562009-06-13 00:33:33 +00001945 return false;
1946}
1947
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001948/// \brief Substitute template arguments into the default template argument for
1949/// the given template type parameter.
1950///
1951/// \param SemaRef the semantic analysis object for which we are performing
1952/// the substitution.
1953///
1954/// \param Template the template that we are synthesizing template arguments
1955/// for.
1956///
1957/// \param TemplateLoc the location of the template name that started the
1958/// template-id we are checking.
1959///
1960/// \param RAngleLoc the location of the right angle bracket ('>') that
1961/// terminates the template-id.
1962///
1963/// \param Param the template template parameter whose default we are
1964/// substituting into.
1965///
1966/// \param Converted the list of template arguments provided for template
1967/// parameters that precede \p Param in the template parameter list.
1968///
1969/// \returns the substituted template argument, or NULL if an error occurred.
John McCalla93c9342009-12-07 02:54:59 +00001970static TypeSourceInfo *
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001971SubstDefaultTemplateArgument(Sema &SemaRef,
1972 TemplateDecl *Template,
1973 SourceLocation TemplateLoc,
1974 SourceLocation RAngleLoc,
1975 TemplateTypeParmDecl *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00001976 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
John McCalla93c9342009-12-07 02:54:59 +00001977 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001978
1979 // If the argument type is dependent, instantiate it now based
1980 // on the previously-computed template arguments.
1981 if (ArgType->getType()->isDependentType()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001982 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1983 Converted.data(), Converted.size());
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001984
1985 MultiLevelTemplateArgumentList AllTemplateArgs
1986 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1987
1988 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00001989 Template, Converted.data(),
1990 Converted.size(),
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001991 SourceRange(TemplateLoc, RAngleLoc));
1992
1993 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1994 Param->getDefaultArgumentLoc(),
1995 Param->getDeclName());
1996 }
1997
1998 return ArgType;
1999}
2000
2001/// \brief Substitute template arguments into the default template argument for
2002/// the given non-type template parameter.
2003///
2004/// \param SemaRef the semantic analysis object for which we are performing
2005/// the substitution.
2006///
2007/// \param Template the template that we are synthesizing template arguments
2008/// for.
2009///
2010/// \param TemplateLoc the location of the template name that started the
2011/// template-id we are checking.
2012///
2013/// \param RAngleLoc the location of the right angle bracket ('>') that
2014/// terminates the template-id.
2015///
Douglas Gregor788cd062009-11-11 01:00:40 +00002016/// \param Param the non-type template parameter whose default we are
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002017/// substituting into.
2018///
2019/// \param Converted the list of template arguments provided for template
2020/// parameters that precede \p Param in the template parameter list.
2021///
2022/// \returns the substituted template argument, or NULL if an error occurred.
John McCall60d7b3a2010-08-24 06:29:42 +00002023static ExprResult
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002024SubstDefaultTemplateArgument(Sema &SemaRef,
2025 TemplateDecl *Template,
2026 SourceLocation TemplateLoc,
2027 SourceLocation RAngleLoc,
2028 NonTypeTemplateParmDecl *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00002029 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2030 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2031 Converted.data(), Converted.size());
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002032
2033 MultiLevelTemplateArgumentList AllTemplateArgs
2034 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2035
2036 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00002037 Template, Converted.data(),
2038 Converted.size(),
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002039 SourceRange(TemplateLoc, RAngleLoc));
2040
2041 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
2042}
2043
Douglas Gregor788cd062009-11-11 01:00:40 +00002044/// \brief Substitute template arguments into the default template argument for
2045/// the given template template parameter.
2046///
2047/// \param SemaRef the semantic analysis object for which we are performing
2048/// the substitution.
2049///
2050/// \param Template the template that we are synthesizing template arguments
2051/// for.
2052///
2053/// \param TemplateLoc the location of the template name that started the
2054/// template-id we are checking.
2055///
2056/// \param RAngleLoc the location of the right angle bracket ('>') that
2057/// terminates the template-id.
2058///
2059/// \param Param the template template parameter whose default we are
2060/// substituting into.
2061///
2062/// \param Converted the list of template arguments provided for template
2063/// parameters that precede \p Param in the template parameter list.
2064///
2065/// \returns the substituted template argument, or NULL if an error occurred.
2066static TemplateName
2067SubstDefaultTemplateArgument(Sema &SemaRef,
2068 TemplateDecl *Template,
2069 SourceLocation TemplateLoc,
2070 SourceLocation RAngleLoc,
2071 TemplateTemplateParmDecl *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00002072 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2073 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2074 Converted.data(), Converted.size());
Douglas Gregor788cd062009-11-11 01:00:40 +00002075
2076 MultiLevelTemplateArgumentList AllTemplateArgs
2077 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2078
2079 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00002080 Template, Converted.data(),
2081 Converted.size(),
Douglas Gregor788cd062009-11-11 01:00:40 +00002082 SourceRange(TemplateLoc, RAngleLoc));
2083
2084 return SemaRef.SubstTemplateName(
2085 Param->getDefaultArgument().getArgument().getAsTemplate(),
2086 Param->getDefaultArgument().getTemplateNameLoc(),
2087 AllTemplateArgs);
2088}
2089
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002090/// \brief If the given template parameter has a default template
2091/// argument, substitute into that default template argument and
2092/// return the corresponding template argument.
2093TemplateArgumentLoc
2094Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
2095 SourceLocation TemplateLoc,
2096 SourceLocation RAngleLoc,
2097 Decl *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00002098 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2099 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002100 if (!TypeParm->hasDefaultArgument())
2101 return TemplateArgumentLoc();
2102
John McCalla93c9342009-12-07 02:54:59 +00002103 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002104 TemplateLoc,
2105 RAngleLoc,
2106 TypeParm,
2107 Converted);
2108 if (DI)
2109 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
2110
2111 return TemplateArgumentLoc();
2112 }
2113
2114 if (NonTypeTemplateParmDecl *NonTypeParm
2115 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2116 if (!NonTypeParm->hasDefaultArgument())
2117 return TemplateArgumentLoc();
2118
John McCall60d7b3a2010-08-24 06:29:42 +00002119 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002120 TemplateLoc,
2121 RAngleLoc,
2122 NonTypeParm,
2123 Converted);
2124 if (Arg.isInvalid())
2125 return TemplateArgumentLoc();
2126
2127 Expr *ArgE = Arg.takeAs<Expr>();
2128 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
2129 }
2130
2131 TemplateTemplateParmDecl *TempTempParm
2132 = cast<TemplateTemplateParmDecl>(Param);
2133 if (!TempTempParm->hasDefaultArgument())
2134 return TemplateArgumentLoc();
2135
2136 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
2137 TemplateLoc,
2138 RAngleLoc,
2139 TempTempParm,
2140 Converted);
2141 if (TName.isNull())
2142 return TemplateArgumentLoc();
2143
2144 return TemplateArgumentLoc(TemplateArgument(TName),
2145 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
2146 TempTempParm->getDefaultArgument().getTemplateNameLoc());
2147}
2148
Douglas Gregore7526412009-11-11 19:31:23 +00002149/// \brief Check that the given template argument corresponds to the given
2150/// template parameter.
2151bool Sema::CheckTemplateArgument(NamedDecl *Param,
2152 const TemplateArgumentLoc &Arg,
Douglas Gregore7526412009-11-11 19:31:23 +00002153 TemplateDecl *Template,
2154 SourceLocation TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002155 SourceLocation RAngleLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00002156 llvm::SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor02024a92010-03-28 02:42:43 +00002157 CheckTemplateArgumentKind CTAK) {
Douglas Gregord9e15302009-11-11 19:41:09 +00002158 // Check template type parameters.
2159 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregore7526412009-11-11 19:31:23 +00002160 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregore7526412009-11-11 19:31:23 +00002161
Douglas Gregord9e15302009-11-11 19:41:09 +00002162 // Check non-type template parameters.
2163 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregore7526412009-11-11 19:31:23 +00002164 // Do substitution on the type of the non-type template parameter
Peter Collingbourne9f6f6a12010-12-10 17:08:53 +00002165 // with the template arguments we've seen thus far. But if the
2166 // template has a dependent context then we cannot substitute yet.
Douglas Gregore7526412009-11-11 19:31:23 +00002167 QualType NTTPType = NTTP->getType();
Peter Collingbourne9f6f6a12010-12-10 17:08:53 +00002168 if (NTTPType->isDependentType() &&
2169 !isa<TemplateTemplateParmDecl>(Template) &&
2170 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregore7526412009-11-11 19:31:23 +00002171 // Do substitution on the type of the non-type template parameter.
2172 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Douglas Gregor910f8002010-11-07 23:05:16 +00002173 NTTP, Converted.data(), Converted.size(),
Douglas Gregore7526412009-11-11 19:31:23 +00002174 SourceRange(TemplateLoc, RAngleLoc));
2175
Douglas Gregor910f8002010-11-07 23:05:16 +00002176 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2177 Converted.data(), Converted.size());
Douglas Gregore7526412009-11-11 19:31:23 +00002178 NTTPType = SubstType(NTTPType,
2179 MultiLevelTemplateArgumentList(TemplateArgs),
2180 NTTP->getLocation(),
2181 NTTP->getDeclName());
2182 // If that worked, check the non-type template parameter type
2183 // for validity.
2184 if (!NTTPType.isNull())
2185 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2186 NTTP->getLocation());
2187 if (NTTPType.isNull())
2188 return true;
2189 }
2190
2191 switch (Arg.getArgument().getKind()) {
2192 case TemplateArgument::Null:
2193 assert(false && "Should never see a NULL template argument here");
2194 return true;
2195
2196 case TemplateArgument::Expression: {
2197 Expr *E = Arg.getArgument().getAsExpr();
2198 TemplateArgument Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002199 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregore7526412009-11-11 19:31:23 +00002200 return true;
2201
Douglas Gregor910f8002010-11-07 23:05:16 +00002202 Converted.push_back(Result);
Douglas Gregore7526412009-11-11 19:31:23 +00002203 break;
2204 }
2205
2206 case TemplateArgument::Declaration:
2207 case TemplateArgument::Integral:
2208 // We've already checked this template argument, so just copy
2209 // it to the list of converted arguments.
Douglas Gregor910f8002010-11-07 23:05:16 +00002210 Converted.push_back(Arg.getArgument());
Douglas Gregore7526412009-11-11 19:31:23 +00002211 break;
2212
2213 case TemplateArgument::Template:
2214 // We were given a template template argument. It may not be ill-formed;
2215 // see below.
2216 if (DependentTemplateName *DTN
2217 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2218 // We have a template argument such as \c T::template X, which we
2219 // parsed as a template template argument. However, since we now
2220 // know that we need a non-type template argument, convert this
Abramo Bagnara25777432010-08-11 22:01:17 +00002221 // template name into an expression.
2222
2223 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
2224 Arg.getTemplateNameLoc());
2225
John McCallf7a1a742009-11-24 19:00:30 +00002226 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2227 DTN->getQualifier(),
Douglas Gregore7526412009-11-11 19:31:23 +00002228 Arg.getTemplateQualifierRange(),
Abramo Bagnara25777432010-08-11 22:01:17 +00002229 NameInfo);
Douglas Gregore7526412009-11-11 19:31:23 +00002230
2231 TemplateArgument Result;
2232 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2233 return true;
2234
Douglas Gregor910f8002010-11-07 23:05:16 +00002235 Converted.push_back(Result);
Douglas Gregore7526412009-11-11 19:31:23 +00002236 break;
2237 }
2238
2239 // We have a template argument that actually does refer to a class
2240 // template, template alias, or template template parameter, and
2241 // therefore cannot be a non-type template argument.
2242 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2243 << Arg.getSourceRange();
2244
2245 Diag(Param->getLocation(), diag::note_template_param_here);
2246 return true;
2247
2248 case TemplateArgument::Type: {
2249 // We have a non-type template parameter but the template
2250 // argument is a type.
2251
2252 // C++ [temp.arg]p2:
2253 // In a template-argument, an ambiguity between a type-id and
2254 // an expression is resolved to a type-id, regardless of the
2255 // form of the corresponding template-parameter.
2256 //
2257 // We warn specifically about this case, since it can be rather
2258 // confusing for users.
2259 QualType T = Arg.getArgument().getAsType();
2260 SourceRange SR = Arg.getSourceRange();
2261 if (T->isFunctionType())
2262 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2263 else
2264 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2265 Diag(Param->getLocation(), diag::note_template_param_here);
2266 return true;
2267 }
2268
2269 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002270 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002271 break;
2272 }
2273
2274 return false;
2275 }
2276
2277
2278 // Check template template parameters.
2279 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2280
2281 // Substitute into the template parameter list of the template
2282 // template parameter, since previously-supplied template arguments
2283 // may appear within the template template parameter.
2284 {
2285 // Set up a template instantiation context.
2286 LocalInstantiationScope Scope(*this);
2287 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Douglas Gregor910f8002010-11-07 23:05:16 +00002288 TempParm, Converted.data(), Converted.size(),
Douglas Gregore7526412009-11-11 19:31:23 +00002289 SourceRange(TemplateLoc, RAngleLoc));
2290
Douglas Gregor910f8002010-11-07 23:05:16 +00002291 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2292 Converted.data(), Converted.size());
Douglas Gregore7526412009-11-11 19:31:23 +00002293 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2294 SubstDecl(TempParm, CurContext,
2295 MultiLevelTemplateArgumentList(TemplateArgs)));
2296 if (!TempParm)
2297 return true;
2298
2299 // FIXME: TempParam is leaked.
2300 }
2301
2302 switch (Arg.getArgument().getKind()) {
2303 case TemplateArgument::Null:
2304 assert(false && "Should never see a NULL template argument here");
2305 return true;
2306
2307 case TemplateArgument::Template:
2308 if (CheckTemplateArgument(TempParm, Arg))
2309 return true;
2310
Douglas Gregor910f8002010-11-07 23:05:16 +00002311 Converted.push_back(Arg.getArgument());
Douglas Gregore7526412009-11-11 19:31:23 +00002312 break;
2313
2314 case TemplateArgument::Expression:
2315 case TemplateArgument::Type:
2316 // We have a template template parameter but the template
2317 // argument does not refer to a template.
2318 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2319 return true;
2320
2321 case TemplateArgument::Declaration:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002322 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002323 "Declaration argument with template template parameter");
2324 break;
2325 case TemplateArgument::Integral:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002326 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002327 "Integral argument with template template parameter");
2328 break;
2329
2330 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002331 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002332 break;
2333 }
2334
2335 return false;
2336}
2337
Douglas Gregorc15cb382009-02-09 23:23:08 +00002338/// \brief Check that the given template argument list is well-formed
2339/// for specializing the given template.
2340bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2341 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00002342 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00002343 bool PartialTemplateArgs,
Douglas Gregor910f8002010-11-07 23:05:16 +00002344 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002345 TemplateParameterList *Params = Template->getTemplateParameters();
2346 unsigned NumParams = Params->size();
John McCalld5532b62009-11-23 01:53:49 +00002347 unsigned NumArgs = TemplateArgs.size();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002348 bool Invalid = false;
2349
John McCalld5532b62009-11-23 01:53:49 +00002350 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2351
Mike Stump1eb44332009-09-09 15:08:12 +00002352 bool HasParameterPack =
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002353 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump1eb44332009-09-09 15:08:12 +00002354
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002355 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00002356 (NumArgs < Params->getMinRequiredArguments() &&
2357 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002358 // FIXME: point at either the first arg beyond what we can handle,
2359 // or the '>', depending on whether we have too many or too few
2360 // arguments.
2361 SourceRange Range;
2362 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00002363 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002364 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2365 << (NumArgs > NumParams)
2366 << (isa<ClassTemplateDecl>(Template)? 0 :
2367 isa<FunctionTemplateDecl>(Template)? 1 :
2368 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2369 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00002370 Diag(Template->getLocation(), diag::note_template_decl_here)
2371 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002372 Invalid = true;
2373 }
Mike Stump1eb44332009-09-09 15:08:12 +00002374
2375 // C++ [temp.arg]p1:
Douglas Gregorc15cb382009-02-09 23:23:08 +00002376 // [...] The type and form of each template-argument specified in
2377 // a template-id shall match the type and form specified for the
2378 // corresponding parameter declared by the template in its
2379 // template-parameter-list.
2380 unsigned ArgIdx = 0;
2381 for (TemplateParameterList::iterator Param = Params->begin(),
2382 ParamEnd = Params->end();
2383 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregor16134c62009-07-01 00:28:38 +00002384 if (ArgIdx > NumArgs && PartialTemplateArgs)
2385 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002386
Douglas Gregord9e15302009-11-11 19:41:09 +00002387 // If we have a template parameter pack, check every remaining template
2388 // argument against that template parameter pack.
2389 if ((*Param)->isTemplateParameterPack()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00002390 Diag(TemplateLoc, diag::err_variadic_templates_unsupported);
2391 return true;
Douglas Gregord9e15302009-11-11 19:41:09 +00002392 }
2393
Douglas Gregorf35f8282009-11-11 21:54:23 +00002394 if (ArgIdx < NumArgs) {
2395 // Check the template argument we were given.
2396 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2397 TemplateLoc, RAngleLoc, Converted))
2398 return true;
2399
2400 continue;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002401 }
Douglas Gregore7526412009-11-11 19:31:23 +00002402
Douglas Gregorf35f8282009-11-11 21:54:23 +00002403 // We have a default template argument that we will use.
2404 TemplateArgumentLoc Arg;
2405
2406 // Retrieve the default template argument from the template
2407 // parameter. For each kind of template parameter, we substitute the
2408 // template arguments provided thus far and any "outer" template arguments
2409 // (when the template parameter was part of a nested template) into
2410 // the default argument.
2411 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2412 if (!TTP->hasDefaultArgument()) {
2413 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2414 break;
2415 }
2416
John McCalla93c9342009-12-07 02:54:59 +00002417 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002418 Template,
2419 TemplateLoc,
2420 RAngleLoc,
2421 TTP,
2422 Converted);
2423 if (!ArgType)
2424 return true;
2425
2426 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2427 ArgType);
2428 } else if (NonTypeTemplateParmDecl *NTTP
2429 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2430 if (!NTTP->hasDefaultArgument()) {
2431 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2432 break;
2433 }
2434
John McCall60d7b3a2010-08-24 06:29:42 +00002435 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002436 TemplateLoc,
2437 RAngleLoc,
2438 NTTP,
2439 Converted);
2440 if (E.isInvalid())
2441 return true;
2442
2443 Expr *Ex = E.takeAs<Expr>();
2444 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2445 } else {
2446 TemplateTemplateParmDecl *TempParm
2447 = cast<TemplateTemplateParmDecl>(*Param);
2448
2449 if (!TempParm->hasDefaultArgument()) {
2450 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2451 break;
2452 }
2453
2454 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2455 TemplateLoc,
2456 RAngleLoc,
2457 TempParm,
2458 Converted);
2459 if (Name.isNull())
2460 return true;
2461
2462 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2463 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2464 TempParm->getDefaultArgument().getTemplateNameLoc());
2465 }
2466
2467 // Introduce an instantiation record that describes where we are using
2468 // the default template argument.
2469 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00002470 Converted.data(), Converted.size(),
Douglas Gregorf35f8282009-11-11 21:54:23 +00002471 SourceRange(TemplateLoc, RAngleLoc));
2472
2473 // Check the default template argument.
Douglas Gregord9e15302009-11-11 19:41:09 +00002474 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002475 RAngleLoc, Converted))
2476 return true;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002477 }
2478
2479 return Invalid;
2480}
2481
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002482namespace {
2483 class UnnamedLocalNoLinkageFinder
2484 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
2485 {
2486 Sema &S;
2487 SourceRange SR;
2488
2489 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
2490
2491 public:
2492 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
2493
2494 bool Visit(QualType T) {
2495 return inherited::Visit(T.getTypePtr());
2496 }
2497
2498#define TYPE(Class, Parent) \
2499 bool Visit##Class##Type(const Class##Type *);
2500#define ABSTRACT_TYPE(Class, Parent) \
2501 bool Visit##Class##Type(const Class##Type *) { return false; }
2502#define NON_CANONICAL_TYPE(Class, Parent) \
2503 bool Visit##Class##Type(const Class##Type *) { return false; }
2504#include "clang/AST/TypeNodes.def"
2505
2506 bool VisitTagDecl(const TagDecl *Tag);
2507 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
2508 };
2509}
2510
2511bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
2512 return false;
2513}
2514
2515bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
2516 return Visit(T->getElementType());
2517}
2518
2519bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
2520 return Visit(T->getPointeeType());
2521}
2522
2523bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
2524 const BlockPointerType* T) {
2525 return Visit(T->getPointeeType());
2526}
2527
2528bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
2529 const LValueReferenceType* T) {
2530 return Visit(T->getPointeeType());
2531}
2532
2533bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
2534 const RValueReferenceType* T) {
2535 return Visit(T->getPointeeType());
2536}
2537
2538bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
2539 const MemberPointerType* T) {
2540 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
2541}
2542
2543bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
2544 const ConstantArrayType* T) {
2545 return Visit(T->getElementType());
2546}
2547
2548bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
2549 const IncompleteArrayType* T) {
2550 return Visit(T->getElementType());
2551}
2552
2553bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
2554 const VariableArrayType* T) {
2555 return Visit(T->getElementType());
2556}
2557
2558bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
2559 const DependentSizedArrayType* T) {
2560 return Visit(T->getElementType());
2561}
2562
2563bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
2564 const DependentSizedExtVectorType* T) {
2565 return Visit(T->getElementType());
2566}
2567
2568bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
2569 return Visit(T->getElementType());
2570}
2571
2572bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
2573 return Visit(T->getElementType());
2574}
2575
2576bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
2577 const FunctionProtoType* T) {
2578 for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(),
2579 AEnd = T->arg_type_end();
2580 A != AEnd; ++A) {
2581 if (Visit(*A))
2582 return true;
2583 }
2584
2585 return Visit(T->getResultType());
2586}
2587
2588bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
2589 const FunctionNoProtoType* T) {
2590 return Visit(T->getResultType());
2591}
2592
2593bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
2594 const UnresolvedUsingType*) {
2595 return false;
2596}
2597
2598bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
2599 return false;
2600}
2601
2602bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
2603 return Visit(T->getUnderlyingType());
2604}
2605
2606bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
2607 return false;
2608}
2609
2610bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
2611 return VisitTagDecl(T->getDecl());
2612}
2613
2614bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
2615 return VisitTagDecl(T->getDecl());
2616}
2617
2618bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
2619 const TemplateTypeParmType*) {
2620 return false;
2621}
2622
2623bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
2624 const TemplateSpecializationType*) {
2625 return false;
2626}
2627
2628bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
2629 const InjectedClassNameType* T) {
2630 return VisitTagDecl(T->getDecl());
2631}
2632
2633bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
2634 const DependentNameType* T) {
2635 return VisitNestedNameSpecifier(T->getQualifier());
2636}
2637
2638bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
2639 const DependentTemplateSpecializationType* T) {
2640 return VisitNestedNameSpecifier(T->getQualifier());
2641}
2642
2643bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
2644 return false;
2645}
2646
2647bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
2648 const ObjCInterfaceType *) {
2649 return false;
2650}
2651
2652bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
2653 const ObjCObjectPointerType *) {
2654 return false;
2655}
2656
2657bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
2658 if (Tag->getDeclContext()->isFunctionOrMethod()) {
2659 S.Diag(SR.getBegin(), diag::ext_template_arg_local_type)
2660 << S.Context.getTypeDeclType(Tag) << SR;
2661 return true;
2662 }
2663
2664 if (!Tag->getDeclName() && !Tag->getTypedefForAnonDecl()) {
2665 S.Diag(SR.getBegin(), diag::ext_template_arg_unnamed_type) << SR;
2666 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
2667 return true;
2668 }
2669
2670 return false;
2671}
2672
2673bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
2674 NestedNameSpecifier *NNS) {
2675 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
2676 return true;
2677
2678 switch (NNS->getKind()) {
2679 case NestedNameSpecifier::Identifier:
2680 case NestedNameSpecifier::Namespace:
2681 case NestedNameSpecifier::Global:
2682 return false;
2683
2684 case NestedNameSpecifier::TypeSpec:
2685 case NestedNameSpecifier::TypeSpecWithTemplate:
2686 return Visit(QualType(NNS->getAsType(), 0));
2687 }
Fariborz Jahanian7b1ec6c2010-10-13 16:19:16 +00002688 return false;
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002689}
2690
2691
Douglas Gregorc15cb382009-02-09 23:23:08 +00002692/// \brief Check a template argument against its corresponding
2693/// template type parameter.
2694///
2695/// This routine implements the semantics of C++ [temp.arg.type]. It
2696/// returns true if an error occurred, and false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002697bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCalla93c9342009-12-07 02:54:59 +00002698 TypeSourceInfo *ArgInfo) {
2699 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall833ca992009-10-29 08:12:44 +00002700 QualType Arg = ArgInfo->getType();
Douglas Gregor0fddb972010-05-22 16:17:30 +00002701 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth17fb8552010-09-03 21:12:34 +00002702
2703 if (Arg->isVariablyModifiedType()) {
2704 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor4b52e252009-12-21 23:17:24 +00002705 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00002706 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002707 }
2708
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002709 // C++03 [temp.arg.type]p2:
2710 // A local type, a type with no linkage, an unnamed type or a type
2711 // compounded from any of these types shall not be used as a
2712 // template-argument for a template type-parameter.
2713 //
2714 // C++0x allows these, and even in C++03 we allow them as an extension with
2715 // a warning.
Douglas Gregordb4d4bb2010-10-13 18:05:20 +00002716 if (!LangOpts.CPlusPlus0x && Arg->hasUnnamedOrLocalType()) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002717 UnnamedLocalNoLinkageFinder Finder(*this, SR);
2718 (void)Finder.Visit(Context.getCanonicalType(Arg));
2719 }
2720
Douglas Gregorc15cb382009-02-09 23:23:08 +00002721 return false;
2722}
2723
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002724/// \brief Checks whether the given template argument is the address
2725/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002726static bool
2727CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2728 NonTypeTemplateParmDecl *Param,
2729 QualType ParamType,
2730 Expr *ArgIn,
2731 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002732 bool Invalid = false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002733 Expr *Arg = ArgIn;
2734 QualType ArgType = Arg->getType();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002735
2736 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002737 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002738 Arg = Cast->getSubExpr();
2739
2740 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002741 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002742 // A template-argument for a non-type, non-template
2743 // template-parameter shall be one of: [...]
2744 //
2745 // -- the address of an object or function with external
2746 // linkage, including function templates and function
2747 // template-ids but excluding non-static class members,
2748 // expressed as & id-expression where the & is optional if
2749 // the name refers to a function or array, or if the
2750 // corresponding template-parameter is a reference; or
2751 DeclRefExpr *DRE = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002752
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002753 // In C++98/03 mode, give an extension warning on any extra parentheses.
2754 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
2755 bool ExtraParens = false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002756 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002757 if (!Invalid && !ExtraParens && !S.getLangOptions().CPlusPlus0x) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002758 S.Diag(Arg->getSourceRange().getBegin(),
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002759 diag::ext_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002760 << Arg->getSourceRange();
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002761 ExtraParens = true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002762 }
2763
2764 Arg = Parens->getSubExpr();
2765 }
2766
Douglas Gregorb7a09262010-04-01 18:32:35 +00002767 bool AddressTaken = false;
2768 SourceLocation AddrOpLoc;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002769 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00002770 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002771 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb7a09262010-04-01 18:32:35 +00002772 AddressTaken = true;
2773 AddrOpLoc = UnOp->getOperatorLoc();
2774 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002775 } else
2776 DRE = dyn_cast<DeclRefExpr>(Arg);
2777
Douglas Gregorb7a09262010-04-01 18:32:35 +00002778 if (!DRE) {
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002779 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2780 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002781 S.Diag(Param->getLocation(), diag::note_template_param_here);
2782 return true;
2783 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002784
2785 // Stop checking the precise nature of the argument if it is value dependent,
2786 // it should be checked when instantiated.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002787 if (Arg->isValueDependent()) {
John McCall3fa5cae2010-10-26 07:05:15 +00002788 Converted = TemplateArgument(ArgIn);
Chandler Carruth038cc392010-01-31 10:01:20 +00002789 return false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002790 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002791
Douglas Gregorb7a09262010-04-01 18:32:35 +00002792 if (!isa<ValueDecl>(DRE->getDecl())) {
2793 S.Diag(Arg->getSourceRange().getBegin(),
2794 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002795 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002796 S.Diag(Param->getLocation(), diag::note_template_param_here);
2797 return true;
2798 }
2799
2800 NamedDecl *Entity = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002801
2802 // Cannot refer to non-static data members
Douglas Gregorb7a09262010-04-01 18:32:35 +00002803 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2804 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002805 << Field << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002806 S.Diag(Param->getLocation(), diag::note_template_param_here);
2807 return true;
2808 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002809
2810 // Cannot refer to non-static member functions
2811 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb7a09262010-04-01 18:32:35 +00002812 if (!Method->isStatic()) {
2813 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002814 << Method << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002815 S.Diag(Param->getLocation(), diag::note_template_param_here);
2816 return true;
2817 }
Mike Stump1eb44332009-09-09 15:08:12 +00002818
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002819 // Functions must have external linkage.
2820 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002821 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002822 S.Diag(Arg->getSourceRange().getBegin(),
2823 diag::err_template_arg_function_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002824 << Func << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002825 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002826 << true;
2827 return true;
2828 }
2829
2830 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002831 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002832
Douglas Gregorb7a09262010-04-01 18:32:35 +00002833 // If the template parameter has pointer type, the function decays.
2834 if (ParamType->isPointerType() && !AddressTaken)
2835 ArgType = S.Context.getPointerType(Func->getType());
2836 else if (AddressTaken && ParamType->isReferenceType()) {
2837 // If we originally had an address-of operator, but the
2838 // parameter has reference type, complain and (if things look
2839 // like they will work) drop the address-of operator.
2840 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2841 ParamType.getNonReferenceType())) {
2842 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2843 << ParamType;
2844 S.Diag(Param->getLocation(), diag::note_template_param_here);
2845 return true;
2846 }
2847
2848 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2849 << ParamType
2850 << FixItHint::CreateRemoval(AddrOpLoc);
2851 S.Diag(Param->getLocation(), diag::note_template_param_here);
2852
2853 ArgType = Func->getType();
2854 }
2855 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002856 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002857 S.Diag(Arg->getSourceRange().getBegin(),
2858 diag::err_template_arg_object_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002859 << Var << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002860 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002861 << true;
2862 return true;
2863 }
2864
Douglas Gregorb7a09262010-04-01 18:32:35 +00002865 // A value of reference type is not an object.
2866 if (Var->getType()->isReferenceType()) {
2867 S.Diag(Arg->getSourceRange().getBegin(),
2868 diag::err_template_arg_reference_var)
2869 << Var->getType() << Arg->getSourceRange();
2870 S.Diag(Param->getLocation(), diag::note_template_param_here);
2871 return true;
2872 }
2873
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002874 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002875 Entity = Var;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002876
2877 // If the template parameter has pointer type, we must have taken
2878 // the address of this object.
2879 if (ParamType->isReferenceType()) {
2880 if (AddressTaken) {
2881 // If we originally had an address-of operator, but the
2882 // parameter has reference type, complain and (if things look
2883 // like they will work) drop the address-of operator.
2884 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2885 ParamType.getNonReferenceType())) {
2886 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2887 << ParamType;
2888 S.Diag(Param->getLocation(), diag::note_template_param_here);
2889 return true;
2890 }
2891
2892 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2893 << ParamType
2894 << FixItHint::CreateRemoval(AddrOpLoc);
2895 S.Diag(Param->getLocation(), diag::note_template_param_here);
2896
2897 ArgType = Var->getType();
2898 }
2899 } else if (!AddressTaken && ParamType->isPointerType()) {
2900 if (Var->getType()->isArrayType()) {
2901 // Array-to-pointer decay.
2902 ArgType = S.Context.getArrayDecayedType(Var->getType());
2903 } else {
2904 // If the template parameter has pointer type but the address of
2905 // this object was not taken, complain and (possibly) recover by
2906 // taking the address of the entity.
2907 ArgType = S.Context.getPointerType(Var->getType());
2908 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2909 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2910 << ParamType;
2911 S.Diag(Param->getLocation(), diag::note_template_param_here);
2912 return true;
2913 }
2914
2915 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2916 << ParamType
2917 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2918
2919 S.Diag(Param->getLocation(), diag::note_template_param_here);
2920 }
2921 }
2922 } else {
2923 // We found something else, but we don't know specifically what it is.
2924 S.Diag(Arg->getSourceRange().getBegin(),
2925 diag::err_template_arg_not_object_or_func)
2926 << Arg->getSourceRange();
2927 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2928 return true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002929 }
Mike Stump1eb44332009-09-09 15:08:12 +00002930
Douglas Gregorb7a09262010-04-01 18:32:35 +00002931 if (ParamType->isPointerType() &&
2932 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2933 S.IsQualificationConversion(ArgType, ParamType)) {
2934 // For pointer-to-object types, qualification conversions are
2935 // permitted.
2936 } else {
2937 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2938 if (!ParamRef->getPointeeType()->isFunctionType()) {
2939 // C++ [temp.arg.nontype]p5b3:
2940 // For a non-type template-parameter of type reference to
2941 // object, no conversions apply. The type referred to by the
2942 // reference may be more cv-qualified than the (otherwise
2943 // identical) type of the template- argument. The
2944 // template-parameter is bound directly to the
2945 // template-argument, which shall be an lvalue.
2946
2947 // FIXME: Other qualifiers?
2948 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2949 unsigned ArgQuals = ArgType.getCVRQualifiers();
2950
2951 if ((ParamQuals | ArgQuals) != ParamQuals) {
2952 S.Diag(Arg->getSourceRange().getBegin(),
2953 diag::err_template_arg_ref_bind_ignores_quals)
2954 << ParamType << Arg->getType()
2955 << Arg->getSourceRange();
2956 S.Diag(Param->getLocation(), diag::note_template_param_here);
2957 return true;
2958 }
2959 }
2960 }
2961
2962 // At this point, the template argument refers to an object or
2963 // function with external linkage. We now need to check whether the
2964 // argument and parameter types are compatible.
2965 if (!S.Context.hasSameUnqualifiedType(ArgType,
2966 ParamType.getNonReferenceType())) {
2967 // We can't perform this conversion or binding.
2968 if (ParamType->isReferenceType())
2969 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2970 << ParamType << Arg->getType() << Arg->getSourceRange();
2971 else
2972 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2973 << Arg->getType() << ParamType << Arg->getSourceRange();
2974 S.Diag(Param->getLocation(), diag::note_template_param_here);
2975 return true;
2976 }
2977 }
2978
2979 // Create the template argument.
2980 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor77c13e02010-04-24 18:20:53 +00002981 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb7a09262010-04-01 18:32:35 +00002982 return false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002983}
2984
2985/// \brief Checks whether the given template argument is a pointer to
2986/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002987bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2988 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002989 bool Invalid = false;
2990
2991 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002992 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002993 Arg = Cast->getSubExpr();
2994
2995 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002996 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002997 // A template-argument for a non-type, non-template
2998 // template-parameter shall be one of: [...]
2999 //
3000 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregora2813ce2009-10-23 18:54:35 +00003001 DeclRefExpr *DRE = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003002
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003003 // In C++98/03 mode, give an extension warning on any extra parentheses.
3004 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
3005 bool ExtraParens = false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003006 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003007 if (!Invalid && !ExtraParens && !getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00003008 Diag(Arg->getSourceRange().getBegin(),
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003009 diag::ext_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003010 << Arg->getSourceRange();
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003011 ExtraParens = true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003012 }
3013
3014 Arg = Parens->getSubExpr();
3015 }
3016
Douglas Gregorcaddba02009-11-12 18:38:13 +00003017 // A pointer-to-member constant written &Class::member.
3018 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00003019 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00003020 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
3021 if (DRE && !DRE->getQualifier())
3022 DRE = 0;
3023 }
Douglas Gregorcaddba02009-11-12 18:38:13 +00003024 }
3025 // A constant of pointer-to-member type.
3026 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
3027 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
3028 if (VD->getType()->isMemberPointerType()) {
3029 if (isa<NonTypeTemplateParmDecl>(VD) ||
3030 (isa<VarDecl>(VD) &&
3031 Context.getCanonicalType(VD->getType()).isConstQualified())) {
3032 if (Arg->isTypeDependent() || Arg->isValueDependent())
John McCall3fa5cae2010-10-26 07:05:15 +00003033 Converted = TemplateArgument(Arg);
Douglas Gregorcaddba02009-11-12 18:38:13 +00003034 else
3035 Converted = TemplateArgument(VD->getCanonicalDecl());
3036 return Invalid;
3037 }
3038 }
3039 }
3040
3041 DRE = 0;
3042 }
3043
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003044 if (!DRE)
3045 return Diag(Arg->getSourceRange().getBegin(),
3046 diag::err_template_arg_not_pointer_to_member_form)
3047 << Arg->getSourceRange();
3048
3049 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
3050 assert((isa<FieldDecl>(DRE->getDecl()) ||
3051 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
3052 "Only non-static member pointers can make it here");
3053
3054 // Okay: this is the address of a non-static member, and therefore
3055 // a member pointer constant.
Douglas Gregorcaddba02009-11-12 18:38:13 +00003056 if (Arg->isTypeDependent() || Arg->isValueDependent())
John McCall3fa5cae2010-10-26 07:05:15 +00003057 Converted = TemplateArgument(Arg);
Douglas Gregorcaddba02009-11-12 18:38:13 +00003058 else
3059 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003060 return Invalid;
3061 }
3062
3063 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00003064 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003065 diag::err_template_arg_not_pointer_to_member_form)
3066 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003067 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003068 diag::note_template_arg_refers_here);
3069 return true;
3070}
3071
Douglas Gregorc15cb382009-02-09 23:23:08 +00003072/// \brief Check a template argument against its corresponding
3073/// non-type template parameter.
3074///
Douglas Gregor2943aed2009-03-03 04:44:36 +00003075/// This routine implements the semantics of C++ [temp.arg.nontype].
3076/// It returns true if an error occurred, and false otherwise. \p
3077/// InstantiatedParamType is the type of the non-type template
3078/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003079///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003080/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00003081bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump1eb44332009-09-09 15:08:12 +00003082 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02024a92010-03-28 02:42:43 +00003083 TemplateArgument &Converted,
3084 CheckTemplateArgumentKind CTAK) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00003085 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
3086
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003087 // If either the parameter has a dependent type or the argument is
3088 // type-dependent, there's nothing we can check now.
Douglas Gregor40808ce2009-03-09 23:48:35 +00003089 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
3090 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003091 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003092 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00003093 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003094
3095 // C++ [temp.arg.nontype]p5:
3096 // The following conversions are performed on each expression used
3097 // as a non-type template-argument. If a non-type
3098 // template-argument cannot be converted to the type of the
3099 // corresponding template-parameter then the program is
3100 // ill-formed.
3101 //
3102 // -- for a non-type template-parameter of integral or
3103 // enumeration type, integral promotions (4.5) and integral
3104 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00003105 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00003106 QualType ArgType = Arg->getType();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003107 if (ParamType->isIntegralOrEnumerationType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003108 // C++ [temp.arg.nontype]p1:
3109 // A template-argument for a non-type, non-template
3110 // template-parameter shall be one of:
3111 //
3112 // -- an integral constant-expression of integral or enumeration
3113 // type; or
3114 // -- the name of a non-type template-parameter; or
3115 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003116 llvm::APSInt Value;
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003117 if (!ArgType->isIntegralOrEnumerationType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003118 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003119 diag::err_template_arg_not_integral_or_enumeral)
3120 << ArgType << Arg->getSourceRange();
3121 Diag(Param->getLocation(), diag::note_template_param_here);
3122 return true;
3123 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003124 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003125 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
3126 << ArgType << Arg->getSourceRange();
3127 return true;
3128 }
3129
Douglas Gregor02024a92010-03-28 02:42:43 +00003130 // From here on out, all we care about are the unqualified forms
3131 // of the parameter and argument types.
3132 ParamType = ParamType.getUnqualifiedType();
3133 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003134
3135 // Try to convert the argument to the parameter's type.
Douglas Gregorff524392009-11-04 21:50:46 +00003136 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003137 // Okay: no conversion necessary
Douglas Gregor02024a92010-03-28 02:42:43 +00003138 } else if (CTAK == CTAK_Deduced) {
3139 // C++ [temp.deduct.type]p17:
3140 // If, in the declaration of a function template with a non-type
3141 // template-parameter, the non-type template- parameter is used
3142 // in an expression in the function parameter-list and, if the
3143 // corresponding template-argument is deduced, the
3144 // template-argument type shall match the type of the
3145 // template-parameter exactly, except that a template-argument
3146 // deduced from an array bound may be of any integral type.
3147 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
3148 << ArgType << ParamType;
3149 Diag(Param->getLocation(), diag::note_template_param_here);
John McCalldaa8e4e2010-11-15 09:13:47 +00003150 return true;
3151 } else if (ParamType->isBooleanType()) {
3152 // This is an integral-to-boolean conversion.
3153 ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003154 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
3155 !ParamType->isEnumeralType()) {
3156 // This is an integral promotion or conversion.
John McCall2de56d12010-08-25 11:45:40 +00003157 ImpCastExprToType(Arg, ParamType, CK_IntegralCast);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003158 } else {
3159 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00003160 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003161 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00003162 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003163 Diag(Param->getLocation(), diag::note_template_param_here);
3164 return true;
3165 }
3166
Douglas Gregorf80a9d52009-03-14 00:20:21 +00003167 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall183700f2009-09-21 23:43:11 +00003168 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003169 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00003170
3171 if (!Arg->isValueDependent()) {
Douglas Gregor1a6e0342010-03-26 02:38:37 +00003172 llvm::APSInt OldValue = Value;
3173
3174 // Coerce the template argument's value to the value it will have
3175 // based on the template parameter's type.
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00003176 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00003177 if (Value.getBitWidth() != AllowedBits)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003178 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00003179 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregor1a6e0342010-03-26 02:38:37 +00003180
3181 // Complain if an unsigned parameter received a negative value.
3182 if (IntegerType->isUnsignedIntegerType()
3183 && (OldValue.isSigned() && OldValue.isNegative())) {
3184 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
3185 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3186 << Arg->getSourceRange();
3187 Diag(Param->getLocation(), diag::note_template_param_here);
3188 }
3189
3190 // Complain if we overflowed the template parameter's type.
3191 unsigned RequiredBits;
3192 if (IntegerType->isUnsignedIntegerType())
3193 RequiredBits = OldValue.getActiveBits();
3194 else if (OldValue.isUnsigned())
3195 RequiredBits = OldValue.getActiveBits() + 1;
3196 else
3197 RequiredBits = OldValue.getMinSignedBits();
3198 if (RequiredBits > AllowedBits) {
3199 Diag(Arg->getSourceRange().getBegin(),
3200 diag::warn_template_arg_too_large)
3201 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3202 << Arg->getSourceRange();
3203 Diag(Param->getLocation(), diag::note_template_param_here);
3204 }
Douglas Gregorf80a9d52009-03-14 00:20:21 +00003205 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003206
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003207 // Add the value of this argument to the list of converted
3208 // arguments. We use the bitwidth and signedness of the template
3209 // parameter.
3210 if (Arg->isValueDependent()) {
3211 // The argument is value-dependent. Create a new
3212 // TemplateArgument with the converted expression.
3213 Converted = TemplateArgument(Arg);
3214 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003215 }
3216
John McCall833ca992009-10-29 08:12:44 +00003217 Converted = TemplateArgument(Value,
Mike Stump1eb44332009-09-09 15:08:12 +00003218 ParamType->isEnumeralType() ? ParamType
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003219 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003220 return false;
3221 }
Douglas Gregora35284b2009-02-11 00:19:33 +00003222
John McCall6bb80172010-03-30 21:47:33 +00003223 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
3224
Douglas Gregorb7a09262010-04-01 18:32:35 +00003225 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
3226 // from a template argument of type std::nullptr_t to a non-type
3227 // template parameter of type pointer to object, pointer to
3228 // function, or pointer-to-member, respectively.
3229 if (ArgType->isNullPtrType() &&
3230 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
3231 Converted = TemplateArgument((NamedDecl *)0);
3232 return false;
3233 }
3234
Douglas Gregorb86b0572009-02-11 01:18:59 +00003235 // Handle pointer-to-function, reference-to-function, and
3236 // pointer-to-member-function all in (roughly) the same way.
3237 if (// -- For a non-type template-parameter of type pointer to
3238 // function, only the function-to-pointer conversion (4.3) is
3239 // applied. If the template-argument represents a set of
3240 // overloaded functions (or a pointer to such), the matching
3241 // function is selected from the set (13.4).
3242 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003243 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00003244 // -- For a non-type template-parameter of type reference to
3245 // function, no conversions apply. If the template-argument
3246 // represents a set of overloaded functions, the matching
3247 // function is selected from the set (13.4).
3248 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003249 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00003250 // -- For a non-type template-parameter of type pointer to
3251 // member function, no conversions apply. If the
3252 // template-argument represents a set of overloaded member
3253 // functions, the matching member function is selected from
3254 // the set (13.4).
3255 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003256 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00003257 ->isFunctionType())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003258
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003259 if (Arg->getType() == Context.OverloadTy) {
3260 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
3261 true,
3262 FoundResult)) {
3263 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
3264 return true;
3265
3266 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3267 ArgType = Arg->getType();
3268 } else
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003269 return true;
Douglas Gregora35284b2009-02-11 00:19:33 +00003270 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003271
Douglas Gregorb7a09262010-04-01 18:32:35 +00003272 if (!ParamType->isMemberPointerType())
3273 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3274 ParamType,
3275 Arg, Converted);
3276
3277 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
John McCall2de56d12010-08-25 11:45:40 +00003278 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregorb7a09262010-04-01 18:32:35 +00003279 } else if (!Context.hasSameUnqualifiedType(ArgType,
3280 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00003281 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00003282 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregora35284b2009-02-11 00:19:33 +00003283 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00003284 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00003285 Diag(Param->getLocation(), diag::note_template_param_here);
3286 return true;
3287 }
Mike Stump1eb44332009-09-09 15:08:12 +00003288
Douglas Gregorb7a09262010-04-01 18:32:35 +00003289 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregora35284b2009-02-11 00:19:33 +00003290 }
3291
Chris Lattnerfe90de72009-02-20 21:37:53 +00003292 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00003293 // -- for a non-type template-parameter of type pointer to
3294 // object, qualification conversions (4.4) and the
3295 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00003296 // C++0x also allows a value of std::nullptr_t.
Eli Friedman13578692010-08-05 02:49:48 +00003297 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00003298 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00003299
Douglas Gregorb7a09262010-04-01 18:32:35 +00003300 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3301 ParamType,
3302 Arg, Converted);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00003303 }
Mike Stump1eb44332009-09-09 15:08:12 +00003304
Ted Kremenek6217b802009-07-29 21:53:49 +00003305 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00003306 // -- For a non-type template-parameter of type reference to
3307 // object, no conversions apply. The type referred to by the
3308 // reference may be more cv-qualified than the (otherwise
3309 // identical) type of the template-argument. The
3310 // template-parameter is bound directly to the
3311 // template-argument, which must be an lvalue.
Eli Friedman13578692010-08-05 02:49:48 +00003312 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00003313 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00003314
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003315 if (Arg->getType() == Context.OverloadTy) {
3316 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
3317 ParamRefType->getPointeeType(),
3318 true,
3319 FoundResult)) {
3320 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
3321 return true;
3322
3323 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3324 ArgType = Arg->getType();
3325 } else
Douglas Gregorb7a09262010-04-01 18:32:35 +00003326 return true;
Douglas Gregorb86b0572009-02-11 01:18:59 +00003327 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003328
Douglas Gregorb7a09262010-04-01 18:32:35 +00003329 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3330 ParamType,
3331 Arg, Converted);
Douglas Gregorb86b0572009-02-11 01:18:59 +00003332 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00003333
3334 // -- For a non-type template-parameter of type pointer to data
3335 // member, qualification conversions (4.4) are applied.
3336 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
3337
Douglas Gregor8e6563b2009-02-11 18:22:40 +00003338 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00003339 // Types match exactly: nothing more to do here.
3340 } else if (IsQualificationConversion(ArgType, ParamType)) {
John McCall2de56d12010-08-25 11:45:40 +00003341 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregor658bbb52009-02-11 16:16:59 +00003342 } else {
3343 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00003344 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor658bbb52009-02-11 16:16:59 +00003345 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00003346 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00003347 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00003348 return true;
Douglas Gregor658bbb52009-02-11 16:16:59 +00003349 }
3350
Douglas Gregorcaddba02009-11-12 18:38:13 +00003351 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregorc15cb382009-02-09 23:23:08 +00003352}
3353
3354/// \brief Check a template argument against its corresponding
3355/// template template parameter.
3356///
3357/// This routine implements the semantics of C++ [temp.arg.template].
3358/// It returns true if an error occurred, and false otherwise.
3359bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor788cd062009-11-11 01:00:40 +00003360 const TemplateArgumentLoc &Arg) {
3361 TemplateName Name = Arg.getArgument().getAsTemplate();
3362 TemplateDecl *Template = Name.getAsTemplateDecl();
3363 if (!Template) {
3364 // Any dependent template name is fine.
3365 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3366 return false;
3367 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00003368
3369 // C++ [temp.arg.template]p1:
3370 // A template-argument for a template template-parameter shall be
3371 // the name of a class template, expressed as id-expression. Only
3372 // primary class templates are considered when matching the
3373 // template template argument with the corresponding parameter;
3374 // partial specializations are not considered even if their
3375 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003376 //
3377 // Note that we also allow template template parameters here, which
3378 // will happen when we are dealing with, e.g., class template
3379 // partial specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00003380 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003381 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003382 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregordd0574e2009-02-10 00:24:35 +00003383 "Only function templates are possible here");
Douglas Gregor788cd062009-11-11 01:00:40 +00003384 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregore53060f2009-06-25 22:08:12 +00003385 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00003386 << Template;
3387 }
3388
3389 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3390 Param->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +00003391 true,
3392 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor788cd062009-11-11 01:00:40 +00003393 Arg.getLocation());
Douglas Gregorc15cb382009-02-09 23:23:08 +00003394}
3395
Douglas Gregor02024a92010-03-28 02:42:43 +00003396/// \brief Given a non-type template argument that refers to a
3397/// declaration and the type of its corresponding non-type template
3398/// parameter, produce an expression that properly refers to that
3399/// declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00003400ExprResult
Douglas Gregor02024a92010-03-28 02:42:43 +00003401Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3402 QualType ParamType,
3403 SourceLocation Loc) {
3404 assert(Arg.getKind() == TemplateArgument::Declaration &&
3405 "Only declaration template arguments permitted here");
3406 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3407
3408 if (VD->getDeclContext()->isRecord() &&
3409 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3410 // If the value is a class member, we might have a pointer-to-member.
3411 // Determine whether the non-type template template parameter is of
3412 // pointer-to-member type. If so, we need to build an appropriate
3413 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3414 // would refer to the member itself.
3415 if (ParamType->isMemberPointerType()) {
3416 QualType ClassType
3417 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3418 NestedNameSpecifier *Qualifier
John McCall9ae2f072010-08-23 23:25:46 +00003419 = NestedNameSpecifier::Create(Context, 0, false,
3420 ClassType.getTypePtr());
Douglas Gregor02024a92010-03-28 02:42:43 +00003421 CXXScopeSpec SS;
3422 SS.setScopeRep(Qualifier);
John McCalldfa1edb2010-11-23 20:48:44 +00003423
3424 // The actual value-ness of this is unimportant, but for
3425 // internal consistency's sake, references to instance methods
3426 // are r-values.
3427 ExprValueKind VK = VK_LValue;
3428 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
3429 VK = VK_RValue;
3430
John McCall60d7b3a2010-08-24 06:29:42 +00003431 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCallf89e55a2010-11-18 06:31:45 +00003432 VD->getType().getNonReferenceType(),
John McCalldfa1edb2010-11-23 20:48:44 +00003433 VK,
John McCallf89e55a2010-11-18 06:31:45 +00003434 Loc,
3435 &SS);
Douglas Gregor02024a92010-03-28 02:42:43 +00003436 if (RefExpr.isInvalid())
3437 return ExprError();
3438
John McCall2de56d12010-08-25 11:45:40 +00003439 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregorc0c83002010-04-30 21:46:38 +00003440
3441 // We might need to perform a trailing qualification conversion, since
3442 // the element type on the parameter could be more qualified than the
3443 // element type in the expression we constructed.
3444 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3445 ParamType.getUnqualifiedType())) {
3446 Expr *RefE = RefExpr.takeAs<Expr>();
John McCall2de56d12010-08-25 11:45:40 +00003447 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(), CK_NoOp);
Douglas Gregorc0c83002010-04-30 21:46:38 +00003448 RefExpr = Owned(RefE);
3449 }
3450
Douglas Gregor02024a92010-03-28 02:42:43 +00003451 assert(!RefExpr.isInvalid() &&
3452 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorc0c83002010-04-30 21:46:38 +00003453 ParamType.getUnqualifiedType()));
Douglas Gregor02024a92010-03-28 02:42:43 +00003454 return move(RefExpr);
3455 }
3456 }
3457
3458 QualType T = VD->getType().getNonReferenceType();
3459 if (ParamType->isPointerType()) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003460 // When the non-type template parameter is a pointer, take the
3461 // address of the declaration.
John McCallf89e55a2010-11-18 06:31:45 +00003462 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregor02024a92010-03-28 02:42:43 +00003463 if (RefExpr.isInvalid())
3464 return ExprError();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003465
3466 if (T->isFunctionType() || T->isArrayType()) {
3467 // Decay functions and arrays.
3468 Expr *RefE = (Expr *)RefExpr.get();
3469 DefaultFunctionArrayConversion(RefE);
3470 if (RefE != RefExpr.get()) {
3471 RefExpr.release();
3472 RefExpr = Owned(RefE);
3473 }
3474
3475 return move(RefExpr);
Douglas Gregor02024a92010-03-28 02:42:43 +00003476 }
3477
Douglas Gregorb7a09262010-04-01 18:32:35 +00003478 // Take the address of everything else
John McCall2de56d12010-08-25 11:45:40 +00003479 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregor02024a92010-03-28 02:42:43 +00003480 }
3481
John McCallf89e55a2010-11-18 06:31:45 +00003482 ExprValueKind VK = VK_RValue;
3483
Douglas Gregor02024a92010-03-28 02:42:43 +00003484 // If the non-type template parameter has reference type, qualify the
3485 // resulting declaration reference with the extra qualifiers on the
3486 // type that the reference refers to.
John McCallf89e55a2010-11-18 06:31:45 +00003487 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
3488 VK = VK_LValue;
3489 T = Context.getQualifiedType(T,
3490 TargetRef->getPointeeType().getQualifiers());
3491 }
Douglas Gregor02024a92010-03-28 02:42:43 +00003492
John McCallf89e55a2010-11-18 06:31:45 +00003493 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregor02024a92010-03-28 02:42:43 +00003494}
3495
3496/// \brief Construct a new expression that refers to the given
3497/// integral template argument with the given source-location
3498/// information.
3499///
3500/// This routine takes care of the mapping from an integral template
3501/// argument (which may have any integral type) to the appropriate
3502/// literal value.
John McCall60d7b3a2010-08-24 06:29:42 +00003503ExprResult
Douglas Gregor02024a92010-03-28 02:42:43 +00003504Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3505 SourceLocation Loc) {
3506 assert(Arg.getKind() == TemplateArgument::Integral &&
3507 "Operation is only value for integral template arguments");
3508 QualType T = Arg.getIntegralType();
3509 if (T->isCharType() || T->isWideCharType())
3510 return Owned(new (Context) CharacterLiteral(
3511 Arg.getAsIntegral()->getZExtValue(),
3512 T->isWideCharType(),
3513 T,
3514 Loc));
3515 if (T->isBooleanType())
3516 return Owned(new (Context) CXXBoolLiteralExpr(
3517 Arg.getAsIntegral()->getBoolValue(),
3518 T,
3519 Loc));
3520
Peter Collingbournefb7b3632010-12-15 15:06:14 +00003521 QualType BT;
3522 if (const EnumType *ET = T->getAs<EnumType>())
3523 BT = ET->getDecl()->getPromotionType();
3524 else
3525 BT = T;
3526
3527 Expr *E = IntegerLiteral::Create(Context, *Arg.getAsIntegral(), BT, Loc);
3528 ImpCastExprToType(E, T, CK_IntegralCast);
3529
3530 return Owned(E);
Douglas Gregor02024a92010-03-28 02:42:43 +00003531}
3532
3533
Douglas Gregorddc29e12009-02-06 22:42:48 +00003534/// \brief Determine whether the given template parameter lists are
3535/// equivalent.
3536///
Mike Stump1eb44332009-09-09 15:08:12 +00003537/// \param New The new template parameter list, typically written in the
Douglas Gregorddc29e12009-02-06 22:42:48 +00003538/// source code as part of a new template declaration.
3539///
3540/// \param Old The old template parameter list, typically found via
3541/// name lookup of the template declared with this template parameter
3542/// list.
3543///
3544/// \param Complain If true, this routine will produce a diagnostic if
3545/// the template parameter lists are not equivalent.
3546///
Douglas Gregorfb898e12009-11-12 16:20:59 +00003547/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregordd0574e2009-02-10 00:24:35 +00003548///
3549/// \param TemplateArgLoc If this source location is valid, then we
3550/// are actually checking the template parameter list of a template
3551/// argument (New) against the template parameter list of its
3552/// corresponding template template parameter (Old). We produce
3553/// slightly different diagnostics in this scenario.
3554///
Douglas Gregorddc29e12009-02-06 22:42:48 +00003555/// \returns True if the template parameter lists are equal, false
3556/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00003557bool
Douglas Gregorddc29e12009-02-06 22:42:48 +00003558Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3559 TemplateParameterList *Old,
3560 bool Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003561 TemplateParameterListEqualKind Kind,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003562 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003563 if (Old->size() != New->size()) {
3564 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00003565 unsigned NextDiag = diag::err_template_param_list_different_arity;
3566 if (TemplateArgLoc.isValid()) {
3567 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3568 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump1eb44332009-09-09 15:08:12 +00003569 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00003570 Diag(New->getTemplateLoc(), NextDiag)
3571 << (New->size() > Old->size())
Douglas Gregorfb898e12009-11-12 16:20:59 +00003572 << (Kind != TPL_TemplateMatch)
Douglas Gregordd0574e2009-02-10 00:24:35 +00003573 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00003574 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003575 << (Kind != TPL_TemplateMatch)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003576 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3577 }
3578
3579 return false;
3580 }
3581
3582 for (TemplateParameterList::iterator OldParm = Old->begin(),
3583 OldParmEnd = Old->end(), NewParm = New->begin();
3584 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3585 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003586 if (Complain) {
3587 unsigned NextDiag = diag::err_template_param_different_kind;
3588 if (TemplateArgLoc.isValid()) {
3589 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3590 NextDiag = diag::note_template_param_different_kind;
3591 }
3592 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003593 << (Kind != TPL_TemplateMatch);
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003594 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003595 << (Kind != TPL_TemplateMatch);
Douglas Gregordd0574e2009-02-10 00:24:35 +00003596 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00003597 return false;
3598 }
3599
Douglas Gregora417b872010-06-04 08:34:32 +00003600 if (TemplateTypeParmDecl *OldTTP
3601 = dyn_cast<TemplateTypeParmDecl>(*OldParm)) {
3602 // Template type parameters are equivalent if either both are template
3603 // type parameter packs or neither are (since we know we're at the same
3604 // index).
3605 TemplateTypeParmDecl *NewTTP = cast<TemplateTypeParmDecl>(*NewParm);
3606 if (OldTTP->isParameterPack() != NewTTP->isParameterPack()) {
3607 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3608 // allow one to match a template parameter pack in the template
3609 // parameter list of a template template parameter to one or more
3610 // template parameters in the template parameter list of the
3611 // corresponding template template argument.
3612 if (Complain) {
3613 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3614 if (TemplateArgLoc.isValid()) {
3615 Diag(TemplateArgLoc,
3616 diag::err_template_arg_template_params_mismatch);
3617 NextDiag = diag::note_template_parameter_pack_non_pack;
3618 }
3619 Diag(NewTTP->getLocation(), NextDiag)
3620 << 0 << NewTTP->isParameterPack();
3621 Diag(OldTTP->getLocation(), diag::note_template_parameter_pack_here)
3622 << 0 << OldTTP->isParameterPack();
3623 }
3624 return false;
3625 }
Mike Stump1eb44332009-09-09 15:08:12 +00003626 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003627 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3628 // The types of non-type template parameters must agree.
3629 NonTypeTemplateParmDecl *NewNTTP
3630 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregorfb898e12009-11-12 16:20:59 +00003631
3632 // If we are matching a template template argument to a template
3633 // template parameter and one of the non-type template parameter types
3634 // is dependent, then we must wait until template instantiation time
3635 // to actually compare the arguments.
3636 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3637 (OldNTTP->getType()->isDependentType() ||
3638 NewNTTP->getType()->isDependentType()))
3639 continue;
3640
Douglas Gregorddc29e12009-02-06 22:42:48 +00003641 if (Context.getCanonicalType(OldNTTP->getType()) !=
3642 Context.getCanonicalType(NewNTTP->getType())) {
3643 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00003644 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3645 if (TemplateArgLoc.isValid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003646 Diag(TemplateArgLoc,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003647 diag::err_template_arg_template_params_mismatch);
3648 NextDiag = diag::note_template_nontype_parm_different_type;
3649 }
3650 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003651 << NewNTTP->getType()
Douglas Gregorfb898e12009-11-12 16:20:59 +00003652 << (Kind != TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00003653 Diag(OldNTTP->getLocation(),
Douglas Gregorddc29e12009-02-06 22:42:48 +00003654 diag::note_template_nontype_parm_prev_declaration)
3655 << OldNTTP->getType();
3656 }
3657 return false;
3658 }
3659 } else {
3660 // The template parameter lists of template template
3661 // parameters must agree.
Mike Stump1eb44332009-09-09 15:08:12 +00003662 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorddc29e12009-02-06 22:42:48 +00003663 "Only template template parameters handled here");
Mike Stump1eb44332009-09-09 15:08:12 +00003664 TemplateTemplateParmDecl *OldTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003665 = cast<TemplateTemplateParmDecl>(*OldParm);
3666 TemplateTemplateParmDecl *NewTTP
3667 = cast<TemplateTemplateParmDecl>(*NewParm);
3668 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3669 OldTTP->getTemplateParameters(),
3670 Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003671 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregordd0574e2009-02-10 00:24:35 +00003672 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003673 return false;
3674 }
3675 }
3676
3677 return true;
3678}
3679
3680/// \brief Check whether a template can be declared within this scope.
3681///
3682/// If the template declaration is valid in this scope, returns
3683/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump1eb44332009-09-09 15:08:12 +00003684bool
Douglas Gregor05396e22009-08-25 17:23:04 +00003685Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003686 // Find the nearest enclosing declaration scope.
3687 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3688 (S->getFlags() & Scope::TemplateParamScope) != 0)
3689 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00003690
Douglas Gregorddc29e12009-02-06 22:42:48 +00003691 // C++ [temp]p2:
3692 // A template-declaration can appear only as a namespace scope or
3693 // class scope declaration.
3694 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00003695 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3696 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump1eb44332009-09-09 15:08:12 +00003697 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor05396e22009-08-25 17:23:04 +00003698 << TemplateParams->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003699
Eli Friedman1503f772009-07-31 01:43:05 +00003700 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003701 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003702
3703 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3704 return false;
3705
Mike Stump1eb44332009-09-09 15:08:12 +00003706 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003707 diag::err_template_outside_namespace_or_class_scope)
3708 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003709}
Douglas Gregorcc636682009-02-17 23:15:12 +00003710
Douglas Gregord5cb8762009-10-07 00:13:32 +00003711/// \brief Determine what kind of template specialization the given declaration
3712/// is.
3713static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3714 if (!D)
3715 return TSK_Undeclared;
3716
Douglas Gregorf6b11852009-10-08 15:14:33 +00003717 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3718 return Record->getTemplateSpecializationKind();
Douglas Gregord5cb8762009-10-07 00:13:32 +00003719 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3720 return Function->getTemplateSpecializationKind();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003721 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3722 return Var->getTemplateSpecializationKind();
3723
Douglas Gregord5cb8762009-10-07 00:13:32 +00003724 return TSK_Undeclared;
3725}
3726
Douglas Gregor9302da62009-10-14 23:50:59 +00003727/// \brief Check whether a specialization is well-formed in the current
3728/// context.
Douglas Gregor88b70942009-02-25 22:02:03 +00003729///
Douglas Gregor9302da62009-10-14 23:50:59 +00003730/// This routine determines whether a template specialization can be declared
3731/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003732///
3733/// \param S the semantic analysis object for which this check is being
3734/// performed.
3735///
3736/// \param Specialized the entity being specialized or instantiated, which
3737/// may be a kind of template (class template, function template, etc.) or
3738/// a member of a class template (member function, static data member,
3739/// member class).
3740///
3741/// \param PrevDecl the previous declaration of this entity, if any.
3742///
3743/// \param Loc the location of the explicit specialization or instantiation of
3744/// this entity.
3745///
3746/// \param IsPartialSpecialization whether this is a partial specialization of
3747/// a class template.
3748///
Douglas Gregord5cb8762009-10-07 00:13:32 +00003749/// \returns true if there was an error that we cannot recover from, false
3750/// otherwise.
3751static bool CheckTemplateSpecializationScope(Sema &S,
3752 NamedDecl *Specialized,
3753 NamedDecl *PrevDecl,
3754 SourceLocation Loc,
Douglas Gregor9302da62009-10-14 23:50:59 +00003755 bool IsPartialSpecialization) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003756 // Keep these "kind" numbers in sync with the %select statements in the
3757 // various diagnostics emitted by this routine.
3758 int EntityKind = 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003759 bool isTemplateSpecialization = false;
3760 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003761 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003762 isTemplateSpecialization = true;
3763 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003764 EntityKind = 2;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003765 isTemplateSpecialization = true;
3766 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00003767 EntityKind = 3;
3768 else if (isa<VarDecl>(Specialized))
3769 EntityKind = 4;
3770 else if (isa<RecordDecl>(Specialized))
3771 EntityKind = 5;
3772 else {
Douglas Gregor9302da62009-10-14 23:50:59 +00003773 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3774 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregord5cb8762009-10-07 00:13:32 +00003775 return true;
3776 }
3777
Douglas Gregor88b70942009-02-25 22:02:03 +00003778 // C++ [temp.expl.spec]p2:
3779 // An explicit specialization shall be declared in the namespace
3780 // of which the template is a member, or, for member templates, in
3781 // the namespace of which the enclosing class or enclosing class
3782 // template is a member. An explicit specialization of a member
3783 // function, member class or static data member of a class
3784 // template shall be declared in the namespace of which the class
3785 // template is a member. Such a declaration may also be a
3786 // definition. If the declaration is not a definition, the
3787 // specialization may be defined later in the name- space in which
3788 // the explicit specialization was declared, or in a namespace
3789 // that encloses the one in which the explicit specialization was
3790 // declared.
Sebastian Redl7a126a42010-08-31 00:36:30 +00003791 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003792 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003793 << Specialized;
Douglas Gregor88b70942009-02-25 22:02:03 +00003794 return true;
3795 }
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003796
Douglas Gregor0a407472009-10-07 17:30:37 +00003797 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3798 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003799 << Specialized;
Douglas Gregor0a407472009-10-07 17:30:37 +00003800 return true;
3801 }
3802
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003803 // C++ [temp.class.spec]p6:
3804 // A class template partial specialization may be declared or redeclared
3805 // in any namespace scope in which its definition may be defined (14.5.1
3806 // and 14.5.2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003807 bool ComplainedAboutScope = false;
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003808 DeclContext *SpecializedContext
Douglas Gregord5cb8762009-10-07 00:13:32 +00003809 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003810 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregor9302da62009-10-14 23:50:59 +00003811 if ((!PrevDecl ||
3812 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3813 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
Douglas Gregor121dc9a2010-09-12 05:08:28 +00003814 // C++ [temp.exp.spec]p2:
3815 // An explicit specialization shall be declared in the namespace of which
3816 // the template is a member, or, for member templates, in the namespace
3817 // of which the enclosing class or enclosing class template is a member.
3818 // An explicit specialization of a member function, member class or
3819 // static data member of a class template shall be declared in the
3820 // namespace of which the class template is a member.
3821 //
3822 // C++0x [temp.expl.spec]p2:
3823 // An explicit specialization shall be declared in a namespace enclosing
3824 // the specialized template.
3825 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext) &&
3826 !(S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext))) {
Douglas Gregora4d5de52010-09-12 05:24:55 +00003827 bool IsCPlusPlus0xExtension
3828 = !S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext);
Douglas Gregor9302da62009-10-14 23:50:59 +00003829 if (isa<TranslationUnitDecl>(SpecializedContext))
Douglas Gregora4d5de52010-09-12 05:24:55 +00003830 S.Diag(Loc, IsCPlusPlus0xExtension
3831 ? diag::ext_template_spec_decl_out_of_scope_global
3832 : diag::err_template_spec_decl_out_of_scope_global)
3833 << EntityKind << Specialized;
Douglas Gregor9302da62009-10-14 23:50:59 +00003834 else if (isa<NamespaceDecl>(SpecializedContext))
Douglas Gregora4d5de52010-09-12 05:24:55 +00003835 S.Diag(Loc, IsCPlusPlus0xExtension
3836 ? diag::ext_template_spec_decl_out_of_scope
3837 : diag::err_template_spec_decl_out_of_scope)
3838 << EntityKind << Specialized
3839 << cast<NamedDecl>(SpecializedContext);
Douglas Gregor9302da62009-10-14 23:50:59 +00003840
3841 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3842 ComplainedAboutScope = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003843 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003844 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003845
3846 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregor9302da62009-10-14 23:50:59 +00003847 // namespace.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003848 // Note that HandleDeclarator() performs this check for explicit
3849 // specializations of function templates, static data members, and member
3850 // functions, so we skip the check here for those kinds of entities.
3851 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003852 // Should we refactor that check, so that it occurs later?
3853 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor9302da62009-10-14 23:50:59 +00003854 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3855 isa<FunctionDecl>(Specialized))) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003856 if (isa<TranslationUnitDecl>(SpecializedContext))
3857 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3858 << EntityKind << Specialized;
3859 else if (isa<NamespaceDecl>(SpecializedContext))
3860 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3861 << EntityKind << Specialized
3862 << cast<NamedDecl>(SpecializedContext);
3863
Douglas Gregor9302da62009-10-14 23:50:59 +00003864 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor88b70942009-02-25 22:02:03 +00003865 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003866
3867 // FIXME: check for specialization-after-instantiation errors and such.
3868
Douglas Gregor88b70942009-02-25 22:02:03 +00003869 return false;
3870}
Douglas Gregord5cb8762009-10-07 00:13:32 +00003871
Douglas Gregore94866f2009-06-12 21:21:02 +00003872/// \brief Check the non-type template arguments of a class template
3873/// partial specialization according to C++ [temp.class.spec]p9.
3874///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003875/// \param TemplateParams the template parameters of the primary class
3876/// template.
3877///
3878/// \param TemplateArg the template arguments of the class template
3879/// partial specialization.
3880///
3881/// \param MirrorsPrimaryTemplate will be set true if the class
3882/// template partial specialization arguments are identical to the
3883/// implicit template arguments of the primary template. This is not
3884/// necessarily an error (C++0x), and it is left to the caller to diagnose
3885/// this condition when it is an error.
3886///
Douglas Gregore94866f2009-06-12 21:21:02 +00003887/// \returns true if there was an error, false otherwise.
3888bool Sema::CheckClassTemplatePartialSpecializationArgs(
3889 TemplateParameterList *TemplateParams,
Douglas Gregor910f8002010-11-07 23:05:16 +00003890 llvm::SmallVectorImpl<TemplateArgument> &TemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003891 bool &MirrorsPrimaryTemplate) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003892 // FIXME: the interface to this function will have to change to
3893 // accommodate variadic templates.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003894 MirrorsPrimaryTemplate = true;
Mike Stump1eb44332009-09-09 15:08:12 +00003895
Douglas Gregor910f8002010-11-07 23:05:16 +00003896 const TemplateArgument *ArgList = TemplateArgs.data();
Mike Stump1eb44332009-09-09 15:08:12 +00003897
Douglas Gregore94866f2009-06-12 21:21:02 +00003898 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003899 // Determine whether the template argument list of the partial
3900 // specialization is identical to the implicit argument list of
3901 // the primary template. The caller may need to diagnostic this as
3902 // an error per C++ [temp.class.spec]p9b3.
3903 if (MirrorsPrimaryTemplate) {
Mike Stump1eb44332009-09-09 15:08:12 +00003904 if (TemplateTypeParmDecl *TTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003905 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3906 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson6360be72009-06-13 18:20:51 +00003907 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003908 MirrorsPrimaryTemplate = false;
3909 } else if (TemplateTemplateParmDecl *TTP
3910 = dyn_cast<TemplateTemplateParmDecl>(
3911 TemplateParams->getParam(I))) {
Douglas Gregor788cd062009-11-11 01:00:40 +00003912 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00003913 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor788cd062009-11-11 01:00:40 +00003914 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003915 if (!ArgDecl ||
3916 ArgDecl->getIndex() != TTP->getIndex() ||
3917 ArgDecl->getDepth() != TTP->getDepth())
3918 MirrorsPrimaryTemplate = false;
3919 }
3920 }
3921
Mike Stump1eb44332009-09-09 15:08:12 +00003922 NonTypeTemplateParmDecl *Param
Douglas Gregore94866f2009-06-12 21:21:02 +00003923 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003924 if (!Param) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003925 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003926 }
3927
Anders Carlsson6360be72009-06-13 18:20:51 +00003928 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003929 if (!ArgExpr) {
3930 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003931 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003932 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003933
3934 // C++ [temp.class.spec]p8:
3935 // A non-type argument is non-specialized if it is the name of a
3936 // non-type parameter. All other non-type arguments are
3937 // specialized.
3938 //
3939 // Below, we check the two conditions that only apply to
3940 // specialized non-type arguments, so skip any non-specialized
3941 // arguments.
3942 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump1eb44332009-09-09 15:08:12 +00003943 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003944 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003945 if (MirrorsPrimaryTemplate &&
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003946 (Param->getIndex() != NTTP->getIndex() ||
3947 Param->getDepth() != NTTP->getDepth()))
3948 MirrorsPrimaryTemplate = false;
3949
Douglas Gregore94866f2009-06-12 21:21:02 +00003950 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003951 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003952
3953 // C++ [temp.class.spec]p9:
3954 // Within the argument list of a class template partial
3955 // specialization, the following restrictions apply:
3956 // -- A partially specialized non-type argument expression
3957 // shall not involve a template parameter of the partial
3958 // specialization except when the argument expression is a
3959 // simple identifier.
3960 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003961 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003962 diag::err_dependent_non_type_arg_in_partial_spec)
3963 << ArgExpr->getSourceRange();
3964 return true;
3965 }
3966
3967 // -- The type of a template parameter corresponding to a
3968 // specialized non-type argument shall not be dependent on a
3969 // parameter of the specialization.
3970 if (Param->getType()->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003971 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003972 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3973 << Param->getType()
3974 << ArgExpr->getSourceRange();
3975 Diag(Param->getLocation(), diag::note_template_param_here);
3976 return true;
3977 }
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003978
3979 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003980 }
3981
3982 return false;
3983}
3984
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003985/// \brief Retrieve the previous declaration of the given declaration.
3986static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3987 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3988 return VD->getPreviousDeclaration();
3989 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3990 return FD->getPreviousDeclaration();
3991 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3992 return TD->getPreviousDeclaration();
3993 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3994 return TD->getPreviousDeclaration();
3995 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3996 return FTD->getPreviousDeclaration();
3997 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3998 return CTD->getPreviousDeclaration();
3999 return 0;
4000}
4001
John McCalld226f652010-08-21 09:40:31 +00004002DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00004003Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
4004 TagUseKind TUK,
Mike Stump1eb44332009-09-09 15:08:12 +00004005 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004006 CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004007 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00004008 SourceLocation TemplateNameLoc,
4009 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00004010 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00004011 SourceLocation RAngleLoc,
4012 AttributeList *Attr,
4013 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004014 assert(TUK != TUK_Reference && "References are not specializations");
John McCallf1bbbb42009-09-04 01:14:41 +00004015
Douglas Gregorcc636682009-02-17 23:15:12 +00004016 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00004017 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00004018 ClassTemplateDecl *ClassTemplate
Douglas Gregor8b13c082009-11-12 00:46:20 +00004019 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
4020
4021 if (!ClassTemplate) {
4022 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
4023 << (Name.getAsTemplateDecl() &&
4024 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
4025 return true;
4026 }
Douglas Gregorcc636682009-02-17 23:15:12 +00004027
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004028 bool isExplicitSpecialization = false;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004029 bool isPartialSpecialization = false;
4030
Douglas Gregor88b70942009-02-25 22:02:03 +00004031 // Check the validity of the template headers that introduce this
4032 // template.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004033 // FIXME: We probably shouldn't complain about these headers for
4034 // friend declarations.
Douglas Gregor0167f3c2010-07-14 23:14:12 +00004035 bool Invalid = false;
Douglas Gregor05396e22009-08-25 17:23:04 +00004036 TemplateParameterList *TemplateParams
Mike Stump1eb44332009-09-09 15:08:12 +00004037 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
4038 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004039 TemplateParameterLists.size(),
John McCall77e8b112010-04-13 20:37:33 +00004040 TUK == TUK_Friend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00004041 isExplicitSpecialization,
4042 Invalid);
4043 if (Invalid)
4044 return true;
4045
Abramo Bagnara9b934882010-06-12 08:15:14 +00004046 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
4047 if (TemplateParams)
4048 --NumMatchedTemplateParamLists;
4049
Douglas Gregor05396e22009-08-25 17:23:04 +00004050 if (TemplateParams && TemplateParams->size() > 0) {
4051 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00004052
Douglas Gregor05396e22009-08-25 17:23:04 +00004053 // C++ [temp.class.spec]p10:
4054 // The template parameter list of a specialization shall not
4055 // contain default template argument values.
4056 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
4057 Decl *Param = TemplateParams->getParam(I);
4058 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
4059 if (TTP->hasDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004060 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004061 diag::err_default_arg_in_partial_spec);
John McCall833ca992009-10-29 08:12:44 +00004062 TTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00004063 }
4064 } else if (NonTypeTemplateParmDecl *NTTP
4065 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4066 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004067 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004068 diag::err_default_arg_in_partial_spec)
4069 << DefArg->getSourceRange();
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00004070 NTTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00004071 }
4072 } else {
4073 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor788cd062009-11-11 01:00:40 +00004074 if (TTP->hasDefaultArgument()) {
4075 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004076 diag::err_default_arg_in_partial_spec)
Douglas Gregor788cd062009-11-11 01:00:40 +00004077 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00004078 TTP->removeDefaultArgument();
Douglas Gregorba1ecb52009-06-12 19:43:02 +00004079 }
4080 }
4081 }
Douglas Gregora735b202009-10-13 14:39:41 +00004082 } else if (TemplateParams) {
4083 if (TUK == TUK_Friend)
4084 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregor849b2432010-03-31 17:46:05 +00004085 << FixItHint::CreateRemoval(
Douglas Gregora735b202009-10-13 14:39:41 +00004086 SourceRange(TemplateParams->getTemplateLoc(),
4087 TemplateParams->getRAngleLoc()))
4088 << SourceRange(LAngleLoc, RAngleLoc);
4089 else
4090 isExplicitSpecialization = true;
4091 } else if (TUK != TUK_Friend) {
Douglas Gregor05396e22009-08-25 17:23:04 +00004092 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor849b2432010-03-31 17:46:05 +00004093 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004094 isExplicitSpecialization = true;
4095 }
Douglas Gregor88b70942009-02-25 22:02:03 +00004096
Douglas Gregorcc636682009-02-17 23:15:12 +00004097 // Check that the specialization uses the same tag kind as the
4098 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004099 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4100 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004101 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00004102 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004103 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004104 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00004105 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00004106 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +00004107 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00004108 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregorcc636682009-02-17 23:15:12 +00004109 diag::note_previous_use);
4110 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4111 }
4112
Douglas Gregor40808ce2009-03-09 23:48:35 +00004113 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00004114 TemplateArgumentListInfo TemplateArgs;
4115 TemplateArgs.setLAngleLoc(LAngleLoc);
4116 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00004117 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00004118
Douglas Gregorcc636682009-02-17 23:15:12 +00004119 // Check that the template argument list is well-formed for this
4120 // template.
Douglas Gregor910f8002010-11-07 23:05:16 +00004121 llvm::SmallVector<TemplateArgument, 4> Converted;
John McCalld5532b62009-11-23 01:53:49 +00004122 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4123 TemplateArgs, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00004124 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00004125
Douglas Gregor910f8002010-11-07 23:05:16 +00004126 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) &&
Douglas Gregorcc636682009-02-17 23:15:12 +00004127 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00004128
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004129 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00004130 // corresponds to these arguments.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00004131 if (isPartialSpecialization) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00004132 bool MirrorsPrimaryTemplate;
Douglas Gregore94866f2009-06-12 21:21:02 +00004133 if (CheckClassTemplatePartialSpecializationArgs(
4134 ClassTemplate->getTemplateParameters(),
Anders Carlssonfb250522009-06-23 01:26:57 +00004135 Converted, MirrorsPrimaryTemplate))
Douglas Gregore94866f2009-06-12 21:21:02 +00004136 return true;
4137
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00004138 if (MirrorsPrimaryTemplate) {
4139 // C++ [temp.class.spec]p9b3:
4140 //
Mike Stump1eb44332009-09-09 15:08:12 +00004141 // -- The argument list of the specialization shall not be identical
4142 // to the implicit argument list of the primary template.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00004143 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall0f434ec2009-07-31 02:45:11 +00004144 << (TUK == TUK_Definition)
Douglas Gregor849b2432010-03-31 17:46:05 +00004145 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
John McCall0f434ec2009-07-31 02:45:11 +00004146 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00004147 ClassTemplate->getIdentifier(),
4148 TemplateNameLoc,
4149 Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +00004150 TemplateParams,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00004151 AS_none);
4152 }
4153
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004154 // FIXME: Diagnose friend partial specializations
4155
Douglas Gregorde090962010-02-09 00:37:32 +00004156 if (!Name.isDependent() &&
4157 !TemplateSpecializationType::anyDependentTemplateArguments(
4158 TemplateArgs.getArgumentArray(),
4159 TemplateArgs.size())) {
4160 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4161 << ClassTemplate->getDeclName();
4162 isPartialSpecialization = false;
Douglas Gregorde090962010-02-09 00:37:32 +00004163 }
4164 }
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004165
Douglas Gregorcc636682009-02-17 23:15:12 +00004166 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004167 ClassTemplateSpecializationDecl *PrevDecl = 0;
4168
4169 if (isPartialSpecialization)
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004170 // FIXME: Template parameter list matters, too
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004171 PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00004172 = ClassTemplate->findPartialSpecialization(Converted.data(),
4173 Converted.size(),
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004174 InsertPos);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004175 else
4176 PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00004177 = ClassTemplate->findSpecialization(Converted.data(),
4178 Converted.size(), InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00004179
4180 ClassTemplateSpecializationDecl *Specialization = 0;
4181
Douglas Gregor88b70942009-02-25 22:02:03 +00004182 // Check whether we can declare a class template specialization in
4183 // the current scope.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004184 if (TUK != TUK_Friend &&
Douglas Gregord5cb8762009-10-07 00:13:32 +00004185 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregor9302da62009-10-14 23:50:59 +00004186 TemplateNameLoc,
4187 isPartialSpecialization))
Douglas Gregor212e81c2009-03-25 00:13:59 +00004188 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004189
Douglas Gregorb88e8882009-07-30 17:40:51 +00004190 // The canonical type
4191 QualType CanonType;
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004192 if (PrevDecl &&
4193 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregorde090962010-02-09 00:37:32 +00004194 TUK == TUK_Friend)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00004195 // Since the only prior class template specialization with these
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004196 // arguments was referenced but not declared, or we're only
4197 // referencing this specialization as a friend, reuse that
Douglas Gregorcc636682009-02-17 23:15:12 +00004198 // declaration node as our own, updating its source location to
4199 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00004200 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00004201 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00004202 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00004203 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004204 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00004205 // Build the canonical type that describes the converted template
4206 // arguments of the class template partial specialization.
Douglas Gregorde090962010-02-09 00:37:32 +00004207 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4208 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00004209 Converted.data(),
4210 Converted.size());
Douglas Gregorb88e8882009-07-30 17:40:51 +00004211
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004212 // Create a new class template partial specialization declaration node.
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004213 ClassTemplatePartialSpecializationDecl *PrevPartial
4214 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregordc60c1e2010-04-30 05:56:50 +00004215 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004216 : ClassTemplate->getNextPartialSpecSequenceNumber();
Mike Stump1eb44332009-09-09 15:08:12 +00004217 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregor13c85772010-05-06 00:28:52 +00004218 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004219 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00004220 TemplateNameLoc,
4221 TemplateParams,
4222 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00004223 Converted.data(),
4224 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00004225 TemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00004226 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00004227 PrevPartial,
4228 SequenceNumber);
John McCallb6217662010-03-15 10:12:16 +00004229 SetNestedNameSpecifier(Partial, SS);
Douglas Gregor98c2e622010-07-28 23:59:57 +00004230 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00004231 Partial->setTemplateParameterListsInfo(Context,
4232 NumMatchedTemplateParamLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00004233 (TemplateParameterList**) TemplateParameterLists.release());
4234 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004235
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004236 if (!PrevPartial)
4237 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004238 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00004239
Douglas Gregored9c0f92009-10-29 00:04:11 +00004240 // If we are providing an explicit specialization of a member class
4241 // template specialization, make a note of that.
4242 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4243 PrevPartial->setMemberSpecialization();
4244
Douglas Gregor031a5882009-06-13 00:26:55 +00004245 // Check that all of the template parameters of the class template
4246 // partial specialization are deducible from the template
4247 // arguments. If not, this class template partial specialization
4248 // will never be used.
4249 llvm::SmallVector<bool, 8> DeducibleParams;
4250 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore73bb602009-09-14 21:25:05 +00004251 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004252 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00004253 DeducibleParams);
Douglas Gregor031a5882009-06-13 00:26:55 +00004254 unsigned NumNonDeducible = 0;
4255 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
4256 if (!DeducibleParams[I])
4257 ++NumNonDeducible;
4258
4259 if (NumNonDeducible) {
4260 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
4261 << (NumNonDeducible > 1)
4262 << SourceRange(TemplateNameLoc, RAngleLoc);
4263 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4264 if (!DeducibleParams[I]) {
4265 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
4266 if (Param->getDeclName())
Mike Stump1eb44332009-09-09 15:08:12 +00004267 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00004268 diag::note_partial_spec_unused_parameter)
4269 << Param->getDeclName();
4270 else
Mike Stump1eb44332009-09-09 15:08:12 +00004271 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00004272 diag::note_partial_spec_unused_parameter)
Benjamin Kramer476d8b82010-08-11 14:47:12 +00004273 << "<anonymous>";
Douglas Gregor031a5882009-06-13 00:26:55 +00004274 }
4275 }
4276 }
Douglas Gregorcc636682009-02-17 23:15:12 +00004277 } else {
4278 // Create a new class template specialization declaration node for
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004279 // this explicit specialization or friend declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00004280 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00004281 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregorcc636682009-02-17 23:15:12 +00004282 ClassTemplate->getDeclContext(),
4283 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004284 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00004285 Converted.data(),
4286 Converted.size(),
Douglas Gregorcc636682009-02-17 23:15:12 +00004287 PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00004288 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor98c2e622010-07-28 23:59:57 +00004289 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00004290 Specialization->setTemplateParameterListsInfo(Context,
4291 NumMatchedTemplateParamLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00004292 (TemplateParameterList**) TemplateParameterLists.release());
4293 }
Douglas Gregorcc636682009-02-17 23:15:12 +00004294
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004295 if (!PrevDecl)
4296 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregorb88e8882009-07-30 17:40:51 +00004297
4298 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00004299 }
4300
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004301 // C++ [temp.expl.spec]p6:
4302 // If a template, a member template or the member of a class template is
4303 // explicitly specialized then that specialization shall be declared
4304 // before the first use of that specialization that would cause an implicit
4305 // instantiation to take place, in every translation unit in which such a
4306 // use occurs; no diagnostic is required.
4307 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004308 bool Okay = false;
4309 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4310 // Is there any previous explicit specialization declaration?
4311 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
4312 Okay = true;
4313 break;
4314 }
4315 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004316
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004317 if (!Okay) {
4318 SourceRange Range(TemplateNameLoc, RAngleLoc);
4319 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4320 << Context.getTypeDeclType(Specialization) << Range;
4321
4322 Diag(PrevDecl->getPointOfInstantiation(),
4323 diag::note_instantiation_required_here)
4324 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004325 != TSK_ImplicitInstantiation);
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004326 return true;
4327 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004328 }
4329
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004330 // If this is not a friend, note that this is an explicit specialization.
4331 if (TUK != TUK_Friend)
4332 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00004333
4334 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00004335 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +00004336 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregorcc636682009-02-17 23:15:12 +00004337 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004338 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004339 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00004340 Diag(Def->getLocation(), diag::note_previous_definition);
4341 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00004342 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00004343 }
4344 }
4345
Douglas Gregorfc705b82009-02-26 22:19:44 +00004346 // Build the fully-sugared type for this class template
4347 // specialization as the user wrote in the specialization
4348 // itself. This means that we'll pretty-print the type retrieved
4349 // from the specialization's declaration the way that the user
4350 // actually wrote the specialization, rather than formatting the
4351 // name based on the "canonical" representation used to store the
4352 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00004353 TypeSourceInfo *WrittenTy
4354 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4355 TemplateArgs, CanonType);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004356 if (TUK != TUK_Friend) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004357 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor7e9b57b2010-07-06 18:33:12 +00004358 if (TemplateParams)
4359 Specialization->setTemplateKeywordLoc(TemplateParams->getTemplateLoc());
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004360 }
Douglas Gregor40808ce2009-03-09 23:48:35 +00004361 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00004362
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00004363 // C++ [temp.expl.spec]p9:
4364 // A template explicit specialization is in the scope of the
4365 // namespace in which the template was defined.
4366 //
4367 // We actually implement this paragraph where we set the semantic
4368 // context (in the creation of the ClassTemplateSpecializationDecl),
4369 // but we also maintain the lexical context where the actual
4370 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00004371 Specialization->setLexicalDeclContext(CurContext);
Mike Stump1eb44332009-09-09 15:08:12 +00004372
Douglas Gregorcc636682009-02-17 23:15:12 +00004373 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00004374 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00004375 Specialization->startDefinition();
4376
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004377 if (TUK == TUK_Friend) {
4378 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
4379 TemplateNameLoc,
John McCall32f2fb52010-03-25 18:04:51 +00004380 WrittenTy,
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004381 /*FIXME:*/KWLoc);
4382 Friend->setAccess(AS_public);
4383 CurContext->addDecl(Friend);
4384 } else {
4385 // Add the specialization into its lexical context, so that it can
4386 // be seen when iterating through the list of declarations in that
4387 // context. However, specializations are not found by name lookup.
4388 CurContext->addDecl(Specialization);
4389 }
John McCalld226f652010-08-21 09:40:31 +00004390 return Specialization;
Douglas Gregorcc636682009-02-17 23:15:12 +00004391}
Douglas Gregord57959a2009-03-27 23:10:48 +00004392
John McCalld226f652010-08-21 09:40:31 +00004393Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregore542c862009-06-23 23:11:28 +00004394 MultiTemplateParamsArg TemplateParameterLists,
John McCalld226f652010-08-21 09:40:31 +00004395 Declarator &D) {
Douglas Gregore542c862009-06-23 23:11:28 +00004396 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
4397}
4398
John McCalld226f652010-08-21 09:40:31 +00004399Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor52591bf2009-06-24 00:54:41 +00004400 MultiTemplateParamsArg TemplateParameterLists,
John McCalld226f652010-08-21 09:40:31 +00004401 Declarator &D) {
Douglas Gregor52591bf2009-06-24 00:54:41 +00004402 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004403 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00004404
Douglas Gregor52591bf2009-06-24 00:54:41 +00004405 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00004406 // FIXME: Diagnose arguments without names in C.
Douglas Gregor52591bf2009-06-24 00:54:41 +00004407 }
Mike Stump1eb44332009-09-09 15:08:12 +00004408
Douglas Gregor52591bf2009-06-24 00:54:41 +00004409 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00004410
John McCalld226f652010-08-21 09:40:31 +00004411 Decl *DP = HandleDeclarator(ParentScope, D,
4412 move(TemplateParameterLists),
4413 /*IsFunctionDefinition=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00004414 if (FunctionTemplateDecl *FunctionTemplate
John McCalld226f652010-08-21 09:40:31 +00004415 = dyn_cast_or_null<FunctionTemplateDecl>(DP))
Mike Stump1eb44332009-09-09 15:08:12 +00004416 return ActOnStartOfFunctionDef(FnBodyScope,
John McCalld226f652010-08-21 09:40:31 +00004417 FunctionTemplate->getTemplatedDecl());
4418 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP))
4419 return ActOnStartOfFunctionDef(FnBodyScope, Function);
4420 return 0;
Douglas Gregor52591bf2009-06-24 00:54:41 +00004421}
4422
John McCall75042392010-02-11 01:33:53 +00004423/// \brief Strips various properties off an implicit instantiation
4424/// that has just been explicitly specialized.
4425static void StripImplicitInstantiation(NamedDecl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00004426 D->dropAttrs();
John McCall75042392010-02-11 01:33:53 +00004427
4428 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4429 FD->setInlineSpecified(false);
4430 }
4431}
4432
Douglas Gregor454885e2009-10-15 15:54:05 +00004433/// \brief Diagnose cases where we have an explicit template specialization
4434/// before/after an explicit template instantiation, producing diagnostics
4435/// for those cases where they are required and determining whether the
4436/// new specialization/instantiation will have any effect.
4437///
Douglas Gregor454885e2009-10-15 15:54:05 +00004438/// \param NewLoc the location of the new explicit specialization or
4439/// instantiation.
4440///
4441/// \param NewTSK the kind of the new explicit specialization or instantiation.
4442///
4443/// \param PrevDecl the previous declaration of the entity.
4444///
4445/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4446///
4447/// \param PrevPointOfInstantiation if valid, indicates where the previus
4448/// declaration was instantiated (either implicitly or explicitly).
4449///
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004450/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregor454885e2009-10-15 15:54:05 +00004451/// specialization or instantiation has no effect and should be ignored.
4452///
4453/// \returns true if there was an error that should prevent the introduction of
4454/// the new declaration into the AST, false otherwise.
Douglas Gregor0d035142009-10-27 18:42:08 +00004455bool
4456Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4457 TemplateSpecializationKind NewTSK,
4458 NamedDecl *PrevDecl,
4459 TemplateSpecializationKind PrevTSK,
4460 SourceLocation PrevPointOfInstantiation,
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004461 bool &HasNoEffect) {
4462 HasNoEffect = false;
Douglas Gregor454885e2009-10-15 15:54:05 +00004463
4464 switch (NewTSK) {
4465 case TSK_Undeclared:
4466 case TSK_ImplicitInstantiation:
4467 assert(false && "Don't check implicit instantiations here");
4468 return false;
4469
4470 case TSK_ExplicitSpecialization:
4471 switch (PrevTSK) {
4472 case TSK_Undeclared:
4473 case TSK_ExplicitSpecialization:
4474 // Okay, we're just specializing something that is either already
4475 // explicitly specialized or has merely been mentioned without any
4476 // instantiation.
4477 return false;
4478
4479 case TSK_ImplicitInstantiation:
4480 if (PrevPointOfInstantiation.isInvalid()) {
4481 // The declaration itself has not actually been instantiated, so it is
4482 // still okay to specialize it.
John McCall75042392010-02-11 01:33:53 +00004483 StripImplicitInstantiation(PrevDecl);
Douglas Gregor454885e2009-10-15 15:54:05 +00004484 return false;
4485 }
4486 // Fall through
4487
4488 case TSK_ExplicitInstantiationDeclaration:
4489 case TSK_ExplicitInstantiationDefinition:
4490 assert((PrevTSK == TSK_ImplicitInstantiation ||
4491 PrevPointOfInstantiation.isValid()) &&
4492 "Explicit instantiation without point of instantiation?");
4493
4494 // C++ [temp.expl.spec]p6:
4495 // If a template, a member template or the member of a class template
4496 // is explicitly specialized then that specialization shall be declared
4497 // before the first use of that specialization that would cause an
4498 // implicit instantiation to take place, in every translation unit in
4499 // which such a use occurs; no diagnostic is required.
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004500 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4501 // Is there any previous explicit specialization declaration?
4502 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4503 return false;
4504 }
4505
Douglas Gregor0d035142009-10-27 18:42:08 +00004506 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregor454885e2009-10-15 15:54:05 +00004507 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004508 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregor454885e2009-10-15 15:54:05 +00004509 << (PrevTSK != TSK_ImplicitInstantiation);
4510
4511 return true;
4512 }
4513 break;
4514
4515 case TSK_ExplicitInstantiationDeclaration:
4516 switch (PrevTSK) {
4517 case TSK_ExplicitInstantiationDeclaration:
4518 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004519 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004520 return false;
4521
4522 case TSK_Undeclared:
4523 case TSK_ImplicitInstantiation:
4524 // We're explicitly instantiating something that may have already been
4525 // implicitly instantiated; that's fine.
4526 return false;
4527
4528 case TSK_ExplicitSpecialization:
4529 // C++0x [temp.explicit]p4:
4530 // For a given set of template parameters, if an explicit instantiation
4531 // of a template appears after a declaration of an explicit
4532 // specialization for that template, the explicit instantiation has no
4533 // effect.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004534 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004535 return false;
4536
4537 case TSK_ExplicitInstantiationDefinition:
4538 // C++0x [temp.explicit]p10:
4539 // If an entity is the subject of both an explicit instantiation
4540 // declaration and an explicit instantiation definition in the same
4541 // translation unit, the definition shall follow the declaration.
Douglas Gregor0d035142009-10-27 18:42:08 +00004542 Diag(NewLoc,
4543 diag::err_explicit_instantiation_declaration_after_definition);
4544 Diag(PrevPointOfInstantiation,
4545 diag::note_explicit_instantiation_definition_here);
Douglas Gregor454885e2009-10-15 15:54:05 +00004546 assert(PrevPointOfInstantiation.isValid() &&
4547 "Explicit instantiation without point of instantiation?");
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004548 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004549 return false;
4550 }
4551 break;
4552
4553 case TSK_ExplicitInstantiationDefinition:
4554 switch (PrevTSK) {
4555 case TSK_Undeclared:
4556 case TSK_ImplicitInstantiation:
4557 // We're explicitly instantiating something that may have already been
4558 // implicitly instantiated; that's fine.
4559 return false;
4560
4561 case TSK_ExplicitSpecialization:
4562 // C++ DR 259, C++0x [temp.explicit]p4:
4563 // For a given set of template parameters, if an explicit
4564 // instantiation of a template appears after a declaration of
4565 // an explicit specialization for that template, the explicit
4566 // instantiation has no effect.
4567 //
4568 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregorc42b6522010-04-09 21:02:29 +00004569 // is not harmful to try to explicitly instantiate something that
Douglas Gregor454885e2009-10-15 15:54:05 +00004570 // has been explicitly specialized.
Douglas Gregor0d035142009-10-27 18:42:08 +00004571 if (!getLangOptions().CPlusPlus0x) {
4572 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregor454885e2009-10-15 15:54:05 +00004573 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004574 Diag(PrevDecl->getLocation(),
Douglas Gregor454885e2009-10-15 15:54:05 +00004575 diag::note_previous_template_specialization);
4576 }
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004577 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004578 return false;
4579
4580 case TSK_ExplicitInstantiationDeclaration:
4581 // We're explicity instantiating a definition for something for which we
4582 // were previously asked to suppress instantiations. That's fine.
4583 return false;
4584
4585 case TSK_ExplicitInstantiationDefinition:
4586 // C++0x [temp.spec]p5:
4587 // For a given template and a given set of template-arguments,
4588 // - an explicit instantiation definition shall appear at most once
4589 // in a program,
Douglas Gregor0d035142009-10-27 18:42:08 +00004590 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregor454885e2009-10-15 15:54:05 +00004591 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004592 Diag(PrevPointOfInstantiation,
4593 diag::note_previous_explicit_instantiation);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004594 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004595 return false;
4596 }
4597 break;
4598 }
4599
4600 assert(false && "Missing specialization/instantiation case?");
4601
4602 return false;
4603}
4604
John McCallaf2094e2010-04-08 09:05:18 +00004605/// \brief Perform semantic analysis for the given dependent function
4606/// template specialization. The only possible way to get a dependent
4607/// function template specialization is with a friend declaration,
4608/// like so:
4609///
4610/// template <class T> void foo(T);
4611/// template <class T> class A {
4612/// friend void foo<>(T);
4613/// };
4614///
4615/// There really isn't any useful analysis we can do here, so we
4616/// just store the information.
4617bool
4618Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4619 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4620 LookupResult &Previous) {
4621 // Remove anything from Previous that isn't a function template in
4622 // the correct context.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004623 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallaf2094e2010-04-08 09:05:18 +00004624 LookupResult::Filter F = Previous.makeFilter();
4625 while (F.hasNext()) {
4626 NamedDecl *D = F.next()->getUnderlyingDecl();
4627 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl7a126a42010-08-31 00:36:30 +00004628 !FDLookupContext->InEnclosingNamespaceSetOf(
4629 D->getDeclContext()->getRedeclContext()))
John McCallaf2094e2010-04-08 09:05:18 +00004630 F.erase();
4631 }
4632 F.done();
4633
4634 // Should this be diagnosed here?
4635 if (Previous.empty()) return true;
4636
4637 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4638 ExplicitTemplateArgs);
4639 return false;
4640}
4641
Abramo Bagnarae03db982010-05-20 15:32:11 +00004642/// \brief Perform semantic analysis for the given function template
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004643/// specialization.
4644///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004645/// This routine performs all of the semantic analysis required for an
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004646/// explicit function template specialization. On successful completion,
4647/// the function declaration \p FD will become a function template
4648/// specialization.
4649///
4650/// \param FD the function declaration, which will be updated to become a
4651/// function template specialization.
4652///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004653/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4654/// if any. Note that this may be valid info even when 0 arguments are
4655/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4656/// as it anyway contains info on the angle brackets locations.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004657///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004658/// \param PrevDecl the set of declarations that may be specialized by
4659/// this function specialization.
4660bool
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004661Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCalld5532b62009-11-23 01:53:49 +00004662 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall68263142009-11-18 22:49:29 +00004663 LookupResult &Previous) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004664 // The set of function template specializations that could match this
4665 // explicit function template specialization.
John McCallc373d482010-01-27 01:50:18 +00004666 UnresolvedSet<8> Candidates;
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004667
Sebastian Redl7a126a42010-08-31 00:36:30 +00004668 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall68263142009-11-18 22:49:29 +00004669 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4670 I != E; ++I) {
4671 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4672 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004673 // Only consider templates found within the same semantic lookup scope as
4674 // FD.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004675 if (!FDLookupContext->InEnclosingNamespaceSetOf(
4676 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004677 continue;
4678
4679 // C++ [temp.expl.spec]p11:
4680 // A trailing template-argument can be left unspecified in the
4681 // template-id naming an explicit function template specialization
4682 // provided it can be deduced from the function argument type.
4683 // Perform template argument deduction to determine whether we may be
4684 // specializing this template.
4685 // FIXME: It is somewhat wasteful to build
John McCall5769d612010-02-08 23:07:23 +00004686 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004687 FunctionDecl *Specialization = 0;
4688 if (TemplateDeductionResult TDK
John McCalld5532b62009-11-23 01:53:49 +00004689 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004690 FD->getType(),
4691 Specialization,
4692 Info)) {
4693 // FIXME: Template argument deduction failed; record why it failed, so
4694 // that we can provide nifty diagnostics.
4695 (void)TDK;
4696 continue;
4697 }
4698
4699 // Record this candidate.
John McCallc373d482010-01-27 01:50:18 +00004700 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004701 }
4702 }
4703
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004704 // Find the most specialized function template.
John McCallc373d482010-01-27 01:50:18 +00004705 UnresolvedSetIterator Result
4706 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4707 TPOC_Other, FD->getLocation(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004708 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004709 << FD->getDeclName(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004710 PDiag(diag::err_function_template_spec_ambiguous)
John McCalld5532b62009-11-23 01:53:49 +00004711 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004712 PDiag(diag::note_function_template_spec_matched));
John McCallc373d482010-01-27 01:50:18 +00004713 if (Result == Candidates.end())
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004714 return true;
John McCallc373d482010-01-27 01:50:18 +00004715
4716 // Ignore access information; it doesn't figure into redeclaration checking.
4717 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregorc42b6522010-04-09 21:02:29 +00004718 Specialization->setLocation(FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004719
4720 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004721 // If so, we have run afoul of .
John McCall7ad650f2010-03-24 07:46:06 +00004722
4723 // If this is a friend declaration, then we're not really declaring
4724 // an explicit specialization.
4725 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004726
Douglas Gregord5cb8762009-10-07 00:13:32 +00004727 // Check the scope of this explicit specialization.
John McCall7ad650f2010-03-24 07:46:06 +00004728 if (!isFriend &&
4729 CheckTemplateSpecializationScope(*this,
Douglas Gregord5cb8762009-10-07 00:13:32 +00004730 Specialization->getPrimaryTemplate(),
4731 Specialization, FD->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004732 false))
Douglas Gregord5cb8762009-10-07 00:13:32 +00004733 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004734
4735 // C++ [temp.expl.spec]p6:
4736 // If a template, a member template or the member of a class template is
Douglas Gregor0d035142009-10-27 18:42:08 +00004737 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004738 // before the first use of that specialization that would cause an implicit
4739 // instantiation to take place, in every translation unit in which such a
4740 // use occurs; no diagnostic is required.
4741 FunctionTemplateSpecializationInfo *SpecInfo
4742 = Specialization->getTemplateSpecializationInfo();
4743 assert(SpecInfo && "Function template specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004744
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004745 bool HasNoEffect = false;
John McCall7ad650f2010-03-24 07:46:06 +00004746 if (!isFriend &&
4747 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall75042392010-02-11 01:33:53 +00004748 TSK_ExplicitSpecialization,
4749 Specialization,
4750 SpecInfo->getTemplateSpecializationKind(),
4751 SpecInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004752 HasNoEffect))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004753 return true;
Douglas Gregord5cb8762009-10-07 00:13:32 +00004754
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004755 // Mark the prior declaration as an explicit specialization, so that later
4756 // clients know that this is an explicit specialization.
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004757 if (!isFriend) {
John McCall7ad650f2010-03-24 07:46:06 +00004758 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004759 MarkUnusedFileScopedDecl(Specialization);
4760 }
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004761
4762 // Turn the given function declaration into a function template
4763 // specialization, with the template arguments from the previous
4764 // specialization.
Abramo Bagnarae03db982010-05-20 15:32:11 +00004765 // Take copies of (semantic and syntactic) template argument lists.
4766 const TemplateArgumentList* TemplArgs = new (Context)
4767 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4768 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4769 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
Douglas Gregor838db382010-02-11 01:19:42 +00004770 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnarae03db982010-05-20 15:32:11 +00004771 TemplArgs, /*InsertPos=*/0,
4772 SpecInfo->getTemplateSpecializationKind(),
4773 TemplArgsAsWritten);
4774
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004775 // The "previous declaration" for this function template specialization is
4776 // the prior function template specialization.
John McCall68263142009-11-18 22:49:29 +00004777 Previous.clear();
4778 Previous.addDecl(Specialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004779 return false;
4780}
4781
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004782/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004783/// specialization.
4784///
4785/// This routine performs all of the semantic analysis required for an
4786/// explicit member function specialization. On successful completion,
4787/// the function declaration \p FD will become a member function
4788/// specialization.
4789///
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004790/// \param Member the member declaration, which will be updated to become a
4791/// specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004792///
John McCall68263142009-11-18 22:49:29 +00004793/// \param Previous the set of declarations, one of which may be specialized
4794/// by this function specialization; the set will be modified to contain the
4795/// redeclared member.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004796bool
John McCall68263142009-11-18 22:49:29 +00004797Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004798 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCall77e8b112010-04-13 20:37:33 +00004799
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004800 // Try to find the member we are instantiating.
4801 NamedDecl *Instantiation = 0;
4802 NamedDecl *InstantiatedFrom = 0;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004803 MemberSpecializationInfo *MSInfo = 0;
4804
John McCall68263142009-11-18 22:49:29 +00004805 if (Previous.empty()) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004806 // Nowhere to look anyway.
4807 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004808 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4809 I != E; ++I) {
4810 NamedDecl *D = (*I)->getUnderlyingDecl();
4811 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004812 if (Context.hasSameType(Function->getType(), Method->getType())) {
4813 Instantiation = Method;
4814 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004815 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004816 break;
4817 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004818 }
4819 }
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004820 } else if (isa<VarDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004821 VarDecl *PrevVar;
4822 if (Previous.isSingleResult() &&
4823 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004824 if (PrevVar->isStaticDataMember()) {
John McCall68263142009-11-18 22:49:29 +00004825 Instantiation = PrevVar;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004826 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004827 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004828 }
4829 } else if (isa<RecordDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004830 CXXRecordDecl *PrevRecord;
4831 if (Previous.isSingleResult() &&
4832 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4833 Instantiation = PrevRecord;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004834 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004835 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004836 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004837 }
4838
4839 if (!Instantiation) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004840 // There is no previous declaration that matches. Since member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004841 // specializations are always out-of-line, the caller will complain about
4842 // this mismatch later.
4843 return false;
4844 }
John McCall77e8b112010-04-13 20:37:33 +00004845
4846 // If this is a friend, just bail out here before we start turning
4847 // things into explicit specializations.
4848 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4849 // Preserve instantiation information.
4850 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4851 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4852 cast<CXXMethodDecl>(InstantiatedFrom),
4853 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4854 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4855 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4856 cast<CXXRecordDecl>(InstantiatedFrom),
4857 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4858 }
4859
4860 Previous.clear();
4861 Previous.addDecl(Instantiation);
4862 return false;
4863 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004864
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004865 // Make sure that this is a specialization of a member.
4866 if (!InstantiatedFrom) {
4867 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4868 << Member;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004869 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4870 return true;
4871 }
4872
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004873 // C++ [temp.expl.spec]p6:
4874 // If a template, a member template or the member of a class template is
4875 // explicitly specialized then that spe- cialization shall be declared
4876 // before the first use of that specialization that would cause an implicit
4877 // instantiation to take place, in every translation unit in which such a
4878 // use occurs; no diagnostic is required.
4879 assert(MSInfo && "Member specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004880
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004881 bool HasNoEffect = false;
John McCall75042392010-02-11 01:33:53 +00004882 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4883 TSK_ExplicitSpecialization,
4884 Instantiation,
4885 MSInfo->getTemplateSpecializationKind(),
4886 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004887 HasNoEffect))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004888 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004889
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004890 // Check the scope of this explicit specialization.
4891 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004892 InstantiatedFrom,
4893 Instantiation, Member->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004894 false))
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004895 return true;
Douglas Gregor2db32322009-10-07 23:56:10 +00004896
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004897 // Note that this is an explicit instantiation of a member.
Douglas Gregorf6b11852009-10-08 15:14:33 +00004898 // the original declaration to note that it is an explicit specialization
4899 // (if it was previously an implicit instantiation). This latter step
4900 // makes bookkeeping easier.
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004901 if (isa<FunctionDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004902 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4903 if (InstantiationFunction->getTemplateSpecializationKind() ==
4904 TSK_ImplicitInstantiation) {
4905 InstantiationFunction->setTemplateSpecializationKind(
4906 TSK_ExplicitSpecialization);
4907 InstantiationFunction->setLocation(Member->getLocation());
4908 }
4909
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004910 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4911 cast<CXXMethodDecl>(InstantiatedFrom),
4912 TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004913 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004914 } else if (isa<VarDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004915 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4916 if (InstantiationVar->getTemplateSpecializationKind() ==
4917 TSK_ImplicitInstantiation) {
4918 InstantiationVar->setTemplateSpecializationKind(
4919 TSK_ExplicitSpecialization);
4920 InstantiationVar->setLocation(Member->getLocation());
4921 }
4922
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004923 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4924 cast<VarDecl>(InstantiatedFrom),
4925 TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004926 MarkUnusedFileScopedDecl(InstantiationVar);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004927 } else {
4928 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorf6b11852009-10-08 15:14:33 +00004929 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4930 if (InstantiationClass->getTemplateSpecializationKind() ==
4931 TSK_ImplicitInstantiation) {
4932 InstantiationClass->setTemplateSpecializationKind(
4933 TSK_ExplicitSpecialization);
4934 InstantiationClass->setLocation(Member->getLocation());
4935 }
4936
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004937 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorf6b11852009-10-08 15:14:33 +00004938 cast<CXXRecordDecl>(InstantiatedFrom),
4939 TSK_ExplicitSpecialization);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004940 }
4941
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004942 // Save the caller the trouble of having to figure out which declaration
4943 // this specialization matches.
John McCall68263142009-11-18 22:49:29 +00004944 Previous.clear();
4945 Previous.addDecl(Instantiation);
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004946 return false;
4947}
4948
Douglas Gregor558c0322009-10-14 23:41:34 +00004949/// \brief Check the scope of an explicit instantiation.
Douglas Gregor669eed82010-07-13 00:10:04 +00004950///
4951/// \returns true if a serious error occurs, false otherwise.
4952static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregor558c0322009-10-14 23:41:34 +00004953 SourceLocation InstLoc,
4954 bool WasQualifiedName) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00004955 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
4956 DeclContext *CurContext = S.CurContext->getRedeclContext();
Douglas Gregor558c0322009-10-14 23:41:34 +00004957
Douglas Gregor669eed82010-07-13 00:10:04 +00004958 if (CurContext->isRecord()) {
4959 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
4960 << D;
4961 return true;
4962 }
4963
Douglas Gregor558c0322009-10-14 23:41:34 +00004964 // C++0x [temp.explicit]p2:
4965 // An explicit instantiation shall appear in an enclosing namespace of its
4966 // template.
4967 //
4968 // This is DR275, which we do not retroactively apply to C++98/03.
4969 if (S.getLangOptions().CPlusPlus0x &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00004970 !CurContext->Encloses(OrigContext)) {
4971 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext))
Douglas Gregor2166beb2010-05-11 17:39:34 +00004972 S.Diag(InstLoc,
4973 S.getLangOptions().CPlusPlus0x?
4974 diag::err_explicit_instantiation_out_of_scope
4975 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00004976 << D << NS;
4977 else
Douglas Gregor2166beb2010-05-11 17:39:34 +00004978 S.Diag(InstLoc,
4979 S.getLangOptions().CPlusPlus0x?
4980 diag::err_explicit_instantiation_must_be_global
4981 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00004982 << D;
4983 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor669eed82010-07-13 00:10:04 +00004984 return false;
Douglas Gregor558c0322009-10-14 23:41:34 +00004985 }
Sebastian Redl7a126a42010-08-31 00:36:30 +00004986
Douglas Gregor558c0322009-10-14 23:41:34 +00004987 // C++0x [temp.explicit]p2:
4988 // If the name declared in the explicit instantiation is an unqualified
4989 // name, the explicit instantiation shall appear in the namespace where
4990 // its template is declared or, if that namespace is inline (7.3.1), any
4991 // namespace from its enclosing namespace set.
4992 if (WasQualifiedName)
Douglas Gregor669eed82010-07-13 00:10:04 +00004993 return false;
Sebastian Redl7a126a42010-08-31 00:36:30 +00004994
4995 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
Douglas Gregor669eed82010-07-13 00:10:04 +00004996 return false;
Sebastian Redl7a126a42010-08-31 00:36:30 +00004997
Douglas Gregor2166beb2010-05-11 17:39:34 +00004998 S.Diag(InstLoc,
4999 S.getLangOptions().CPlusPlus0x?
5000 diag::err_explicit_instantiation_unqualified_wrong_namespace
5001 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
Sebastian Redl7a126a42010-08-31 00:36:30 +00005002 << D << OrigContext;
Douglas Gregor558c0322009-10-14 23:41:34 +00005003 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor669eed82010-07-13 00:10:04 +00005004 return false;
Douglas Gregor558c0322009-10-14 23:41:34 +00005005}
5006
5007/// \brief Determine whether the given scope specifier has a template-id in it.
5008static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
5009 if (!SS.isSet())
5010 return false;
5011
5012 // C++0x [temp.explicit]p2:
5013 // If the explicit instantiation is for a member function, a member class
5014 // or a static data member of a class template specialization, the name of
5015 // the class template specialization in the qualified-id for the member
5016 // name shall be a simple-template-id.
5017 //
5018 // C++98 has the same restriction, just worded differently.
5019 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
5020 NNS; NNS = NNS->getPrefix())
5021 if (Type *T = NNS->getAsType())
5022 if (isa<TemplateSpecializationType>(T))
5023 return true;
5024
5025 return false;
5026}
5027
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005028// Explicit instantiation of a class template specialization
John McCallf312b1e2010-08-26 23:41:50 +00005029DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00005030Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00005031 SourceLocation ExternLoc,
5032 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005033 unsigned TagSpec,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005034 SourceLocation KWLoc,
5035 const CXXScopeSpec &SS,
5036 TemplateTy TemplateD,
5037 SourceLocation TemplateNameLoc,
5038 SourceLocation LAngleLoc,
5039 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005040 SourceLocation RAngleLoc,
5041 AttributeList *Attr) {
5042 // Find the class template we're specializing
5043 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00005044 ClassTemplateDecl *ClassTemplate
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005045 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
5046
5047 // Check that the specialization uses the same tag kind as the
5048 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005049 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
5050 assert(Kind != TTK_Enum &&
5051 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005052 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00005053 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005054 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00005055 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005056 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00005057 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005058 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00005059 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005060 diag::note_previous_use);
5061 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
5062 }
5063
Douglas Gregor558c0322009-10-14 23:41:34 +00005064 // C++0x [temp.explicit]p2:
5065 // There are two forms of explicit instantiation: an explicit instantiation
5066 // definition and an explicit instantiation declaration. An explicit
5067 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5cb8762009-10-07 00:13:32 +00005068 TemplateSpecializationKind TSK
5069 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5070 : TSK_ExplicitInstantiationDeclaration;
5071
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005072 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00005073 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00005074 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005075
5076 // Check that the template argument list is well-formed for this
5077 // template.
Douglas Gregor910f8002010-11-07 23:05:16 +00005078 llvm::SmallVector<TemplateArgument, 4> Converted;
John McCalld5532b62009-11-23 01:53:49 +00005079 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
5080 TemplateArgs, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005081 return true;
5082
Douglas Gregor910f8002010-11-07 23:05:16 +00005083 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) &&
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005084 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00005085
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005086 // Find the class template specialization declaration that
5087 // corresponds to these arguments.
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005088 void *InsertPos = 0;
5089 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00005090 = ClassTemplate->findSpecialization(Converted.data(),
5091 Converted.size(), InsertPos);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005092
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005093 TemplateSpecializationKind PrevDecl_TSK
5094 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
5095
Douglas Gregord5cb8762009-10-07 00:13:32 +00005096 // C++0x [temp.explicit]p2:
5097 // [...] An explicit instantiation shall appear in an enclosing
5098 // namespace of its template. [...]
5099 //
5100 // This is C++ DR 275.
Douglas Gregor669eed82010-07-13 00:10:04 +00005101 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
5102 SS.isSet()))
5103 return true;
Douglas Gregord5cb8762009-10-07 00:13:32 +00005104
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005105 ClassTemplateSpecializationDecl *Specialization = 0;
5106
Douglas Gregord78f5982009-11-25 06:01:46 +00005107 bool ReusedDecl = false;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005108 bool HasNoEffect = false;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005109 if (PrevDecl) {
Douglas Gregor0d035142009-10-27 18:42:08 +00005110 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005111 PrevDecl, PrevDecl_TSK,
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005112 PrevDecl->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005113 HasNoEffect))
John McCalld226f652010-08-21 09:40:31 +00005114 return PrevDecl;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005115
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005116 // Even though HasNoEffect == true means that this explicit instantiation
5117 // has no effect on semantics, we go on to put its syntax in the AST.
5118
5119 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
5120 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor52604ab2009-09-11 21:19:12 +00005121 // Since the only prior class template specialization with these
5122 // arguments was referenced but not declared, reuse that
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005123 // declaration node as our own, updating the source location
5124 // for the template name to reflect our new declaration.
5125 // (Other source locations will be updated later.)
Douglas Gregor52604ab2009-09-11 21:19:12 +00005126 Specialization = PrevDecl;
5127 Specialization->setLocation(TemplateNameLoc);
5128 PrevDecl = 0;
Douglas Gregord78f5982009-11-25 06:01:46 +00005129 ReusedDecl = true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00005130 }
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005131 }
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005132
Douglas Gregor52604ab2009-09-11 21:19:12 +00005133 if (!Specialization) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005134 // Create a new class template specialization declaration node for
5135 // this explicit specialization.
5136 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00005137 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005138 ClassTemplate->getDeclContext(),
5139 TemplateNameLoc,
5140 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00005141 Converted.data(),
5142 Converted.size(),
5143 PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00005144 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005145
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005146 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005147 // Insert the new specialization.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005148 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005149 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005150 }
5151
5152 // Build the fully-sugared type for this explicit instantiation as
5153 // the user wrote in the explicit instantiation itself. This means
5154 // that we'll pretty-print the type retrieved from the
5155 // specialization's declaration the way that the user actually wrote
5156 // the explicit instantiation, rather than formatting the name based
5157 // on the "canonical" representation used to store the template
5158 // arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00005159 TypeSourceInfo *WrittenTy
5160 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
5161 TemplateArgs,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005162 Context.getTypeDeclType(Specialization));
5163 Specialization->setTypeAsWritten(WrittenTy);
5164 TemplateArgsIn.release();
5165
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005166 // Set source locations for keywords.
5167 Specialization->setExternLoc(ExternLoc);
5168 Specialization->setTemplateKeywordLoc(TemplateLoc);
5169
5170 // Add the explicit instantiation into its lexical context. However,
5171 // since explicit instantiations are never found by name lookup, we
5172 // just put it into the declaration context directly.
5173 Specialization->setLexicalDeclContext(CurContext);
5174 CurContext->addDecl(Specialization);
5175
5176 // Syntax is now OK, so return if it has no other effect on semantics.
5177 if (HasNoEffect) {
5178 // Set the template specialization kind.
5179 Specialization->setTemplateSpecializationKind(TSK);
John McCalld226f652010-08-21 09:40:31 +00005180 return Specialization;
Douglas Gregord78f5982009-11-25 06:01:46 +00005181 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005182
5183 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005184 // A definition of a class template or class member template
5185 // shall be in scope at the point of the explicit instantiation of
5186 // the class template or class member template.
5187 //
5188 // This check comes when we actually try to perform the
5189 // instantiation.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005190 ClassTemplateSpecializationDecl *Def
5191 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00005192 Specialization->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005193 if (!Def)
Douglas Gregor972e6ce2009-10-27 06:26:26 +00005194 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005195 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005196 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005197 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
5198 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005199
Douglas Gregor0d035142009-10-27 18:42:08 +00005200 // Instantiate the members of this class template specialization.
5201 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00005202 Specialization->getDefinition());
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00005203 if (Def) {
Rafael Espindolaf075b222010-03-23 19:55:22 +00005204 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
5205
5206 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
5207 // TSK_ExplicitInstantiationDefinition
5208 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
5209 TSK == TSK_ExplicitInstantiationDefinition)
5210 Def->setTemplateSpecializationKind(TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00005211
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005212 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00005213 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005214
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005215 // Set the template specialization kind.
5216 Specialization->setTemplateSpecializationKind(TSK);
John McCalld226f652010-08-21 09:40:31 +00005217 return Specialization;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005218}
5219
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005220// Explicit instantiation of a member class of a class template.
John McCalld226f652010-08-21 09:40:31 +00005221DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00005222Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00005223 SourceLocation ExternLoc,
5224 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005225 unsigned TagSpec,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005226 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005227 CXXScopeSpec &SS,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005228 IdentifierInfo *Name,
5229 SourceLocation NameLoc,
5230 AttributeList *Attr) {
5231
Douglas Gregor402abb52009-05-28 23:31:59 +00005232 bool Owned = false;
John McCallc4e70192009-09-11 04:59:25 +00005233 bool IsDependent = false;
John McCallf312b1e2010-08-26 23:41:50 +00005234 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCalld226f652010-08-21 09:40:31 +00005235 KWLoc, SS, Name, NameLoc, Attr, AS_none,
5236 MultiTemplateParamsArg(*this, 0, 0),
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +00005237 Owned, IsDependent, false, false,
Douglas Gregor1274ccd2010-10-08 23:50:27 +00005238 TypeResult());
John McCallc4e70192009-09-11 04:59:25 +00005239 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
5240
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005241 if (!TagD)
5242 return true;
5243
John McCalld226f652010-08-21 09:40:31 +00005244 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005245 if (Tag->isEnum()) {
5246 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
5247 << Context.getTypeDeclType(Tag);
5248 return true;
5249 }
5250
Douglas Gregord0c87372009-05-27 17:30:49 +00005251 if (Tag->isInvalidDecl())
5252 return true;
Douglas Gregor558c0322009-10-14 23:41:34 +00005253
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005254 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
5255 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
5256 if (!Pattern) {
5257 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
5258 << Context.getTypeDeclType(Record);
5259 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
5260 return true;
5261 }
5262
Douglas Gregor558c0322009-10-14 23:41:34 +00005263 // C++0x [temp.explicit]p2:
5264 // If the explicit instantiation is for a class or member class, the
5265 // elaborated-type-specifier in the declaration shall include a
5266 // simple-template-id.
5267 //
5268 // C++98 has the same restriction, just worded differently.
5269 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregora2dd8282010-06-16 16:26:47 +00005270 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00005271 << Record << SS.getRange();
5272
5273 // C++0x [temp.explicit]p2:
5274 // There are two forms of explicit instantiation: an explicit instantiation
5275 // definition and an explicit instantiation declaration. An explicit
5276 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregora74bbe22009-10-14 21:46:58 +00005277 TemplateSpecializationKind TSK
5278 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5279 : TSK_ExplicitInstantiationDeclaration;
5280
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005281 // C++0x [temp.explicit]p2:
5282 // [...] An explicit instantiation shall appear in an enclosing
5283 // namespace of its template. [...]
5284 //
5285 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00005286 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregor454885e2009-10-15 15:54:05 +00005287
5288 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor583f33b2009-10-15 18:07:02 +00005289 CXXRecordDecl *PrevDecl
5290 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor952b0172010-02-11 01:04:33 +00005291 if (!PrevDecl && Record->getDefinition())
Douglas Gregor583f33b2009-10-15 18:07:02 +00005292 PrevDecl = Record;
5293 if (PrevDecl) {
Douglas Gregor454885e2009-10-15 15:54:05 +00005294 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005295 bool HasNoEffect = false;
Douglas Gregor454885e2009-10-15 15:54:05 +00005296 assert(MSInfo && "No member specialization information?");
Douglas Gregor0d035142009-10-27 18:42:08 +00005297 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregor454885e2009-10-15 15:54:05 +00005298 PrevDecl,
5299 MSInfo->getTemplateSpecializationKind(),
5300 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005301 HasNoEffect))
Douglas Gregor454885e2009-10-15 15:54:05 +00005302 return true;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005303 if (HasNoEffect)
Douglas Gregor454885e2009-10-15 15:54:05 +00005304 return TagD;
5305 }
5306
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005307 CXXRecordDecl *RecordDef
Douglas Gregor952b0172010-02-11 01:04:33 +00005308 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005309 if (!RecordDef) {
Douglas Gregorbf7643e2009-10-15 12:53:22 +00005310 // C++ [temp.explicit]p3:
5311 // A definition of a member class of a class template shall be in scope
5312 // at the point of an explicit instantiation of the member class.
5313 CXXRecordDecl *Def
Douglas Gregor952b0172010-02-11 01:04:33 +00005314 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregorbf7643e2009-10-15 12:53:22 +00005315 if (!Def) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00005316 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
5317 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregorbf7643e2009-10-15 12:53:22 +00005318 Diag(Pattern->getLocation(), diag::note_forward_declaration)
5319 << Pattern;
5320 return true;
Douglas Gregor0d035142009-10-27 18:42:08 +00005321 } else {
5322 if (InstantiateClass(NameLoc, Record, Def,
5323 getTemplateInstantiationArgs(Record),
5324 TSK))
5325 return true;
5326
Douglas Gregor952b0172010-02-11 01:04:33 +00005327 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00005328 if (!RecordDef)
5329 return true;
5330 }
5331 }
5332
5333 // Instantiate all of the members of the class.
5334 InstantiateClassMembers(NameLoc, RecordDef,
5335 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005336
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005337 if (TSK == TSK_ExplicitInstantiationDefinition)
5338 MarkVTableUsed(NameLoc, RecordDef, true);
5339
Mike Stump390b4cc2009-05-16 07:39:55 +00005340 // FIXME: We don't have any representation for explicit instantiations of
5341 // member classes. Such a representation is not needed for compilation, but it
5342 // should be available for clients that want to see all of the declarations in
5343 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005344 return TagD;
5345}
5346
John McCallf312b1e2010-08-26 23:41:50 +00005347DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
5348 SourceLocation ExternLoc,
5349 SourceLocation TemplateLoc,
5350 Declarator &D) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00005351 // Explicit instantiations always require a name.
Abramo Bagnara25777432010-08-11 22:01:17 +00005352 // TODO: check if/when DNInfo should replace Name.
5353 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5354 DeclarationName Name = NameInfo.getName();
Douglas Gregord5a423b2009-09-25 18:43:00 +00005355 if (!Name) {
5356 if (!D.isInvalidType())
5357 Diag(D.getDeclSpec().getSourceRange().getBegin(),
5358 diag::err_explicit_instantiation_requires_name)
5359 << D.getDeclSpec().getSourceRange()
5360 << D.getSourceRange();
5361
5362 return true;
5363 }
5364
5365 // The scope passed in may not be a decl scope. Zip up the scope tree until
5366 // we find one that is.
5367 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5368 (S->getFlags() & Scope::TemplateParamScope) != 0)
5369 S = S->getParent();
5370
5371 // Determine the type of the declaration.
John McCallbf1a0282010-06-04 23:28:52 +00005372 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
5373 QualType R = T->getType();
Douglas Gregord5a423b2009-09-25 18:43:00 +00005374 if (R.isNull())
5375 return true;
5376
5377 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5378 // Cannot explicitly instantiate a typedef.
5379 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
5380 << Name;
5381 return true;
5382 }
5383
Douglas Gregor663b5a02009-10-14 20:14:33 +00005384 // C++0x [temp.explicit]p1:
5385 // [...] An explicit instantiation of a function template shall not use the
5386 // inline or constexpr specifiers.
5387 // Presumably, this also applies to member functions of class templates as
5388 // well.
5389 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
5390 Diag(D.getDeclSpec().getInlineSpecLoc(),
5391 diag::err_explicit_instantiation_inline)
Douglas Gregor849b2432010-03-31 17:46:05 +00005392 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor663b5a02009-10-14 20:14:33 +00005393
5394 // FIXME: check for constexpr specifier.
5395
Douglas Gregor558c0322009-10-14 23:41:34 +00005396 // C++0x [temp.explicit]p2:
5397 // There are two forms of explicit instantiation: an explicit instantiation
5398 // definition and an explicit instantiation declaration. An explicit
5399 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5a423b2009-09-25 18:43:00 +00005400 TemplateSpecializationKind TSK
5401 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5402 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregor558c0322009-10-14 23:41:34 +00005403
Abramo Bagnara25777432010-08-11 22:01:17 +00005404 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCalla24dc2e2009-11-17 02:14:36 +00005405 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005406
5407 if (!R->isFunctionType()) {
5408 // C++ [temp.explicit]p1:
5409 // A [...] static data member of a class template can be explicitly
5410 // instantiated from the member definition associated with its class
5411 // template.
John McCalla24dc2e2009-11-17 02:14:36 +00005412 if (Previous.isAmbiguous())
5413 return true;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005414
John McCall1bcee0a2009-12-02 08:25:40 +00005415 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregord5a423b2009-09-25 18:43:00 +00005416 if (!Prev || !Prev->isStaticDataMember()) {
5417 // We expect to see a data data member here.
5418 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5419 << Name;
5420 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5421 P != PEnd; ++P)
John McCallf36e02d2009-10-09 21:13:30 +00005422 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005423 return true;
5424 }
5425
5426 if (!Prev->getInstantiatedFromStaticDataMember()) {
5427 // FIXME: Check for explicit specialization?
5428 Diag(D.getIdentifierLoc(),
5429 diag::err_explicit_instantiation_data_member_not_instantiated)
5430 << Prev;
5431 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5432 // FIXME: Can we provide a note showing where this was declared?
5433 return true;
5434 }
5435
Douglas Gregor558c0322009-10-14 23:41:34 +00005436 // C++0x [temp.explicit]p2:
5437 // If the explicit instantiation is for a member function, a member class
5438 // or a static data member of a class template specialization, the name of
5439 // the class template specialization in the qualified-id for the member
5440 // name shall be a simple-template-id.
5441 //
5442 // C++98 has the same restriction, just worded differently.
5443 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5444 Diag(D.getIdentifierLoc(),
Douglas Gregora2dd8282010-06-16 16:26:47 +00005445 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00005446 << Prev << D.getCXXScopeSpec().getRange();
5447
5448 // Check the scope of this explicit instantiation.
5449 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5450
Douglas Gregor454885e2009-10-15 15:54:05 +00005451 // Verify that it is okay to explicitly instantiate here.
5452 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5453 assert(MSInfo && "Missing static data member specialization info?");
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005454 bool HasNoEffect = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00005455 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregor454885e2009-10-15 15:54:05 +00005456 MSInfo->getTemplateSpecializationKind(),
5457 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005458 HasNoEffect))
Douglas Gregor454885e2009-10-15 15:54:05 +00005459 return true;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005460 if (HasNoEffect)
John McCalld226f652010-08-21 09:40:31 +00005461 return (Decl*) 0;
Douglas Gregor454885e2009-10-15 15:54:05 +00005462
Douglas Gregord5a423b2009-09-25 18:43:00 +00005463 // Instantiate static data member.
Douglas Gregor0a897e32009-10-15 17:21:20 +00005464 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005465 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruth58e390e2010-08-25 08:27:02 +00005466 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005467
5468 // FIXME: Create an ExplicitInstantiation node?
John McCalld226f652010-08-21 09:40:31 +00005469 return (Decl*) 0;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005470 }
5471
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00005472 // If the declarator is a template-id, translate the parser's template
5473 // argument list into our AST format.
Douglas Gregordb422df2009-09-25 21:45:23 +00005474 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00005475 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005476 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5477 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCalld5532b62009-11-23 01:53:49 +00005478 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5479 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregordb422df2009-09-25 21:45:23 +00005480 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5481 TemplateId->getTemplateArgs(),
Douglas Gregordb422df2009-09-25 21:45:23 +00005482 TemplateId->NumArgs);
John McCalld5532b62009-11-23 01:53:49 +00005483 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregordb422df2009-09-25 21:45:23 +00005484 HasExplicitTemplateArgs = true;
Douglas Gregorb2f81cf2009-10-01 23:51:25 +00005485 TemplateArgsPtr.release();
Douglas Gregordb422df2009-09-25 21:45:23 +00005486 }
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00005487
Douglas Gregord5a423b2009-09-25 18:43:00 +00005488 // C++ [temp.explicit]p1:
5489 // A [...] function [...] can be explicitly instantiated from its template.
5490 // A member function [...] of a class template can be explicitly
5491 // instantiated from the member definition associated with its class
5492 // template.
John McCallc373d482010-01-27 01:50:18 +00005493 UnresolvedSet<8> Matches;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005494 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5495 P != PEnd; ++P) {
5496 NamedDecl *Prev = *P;
Douglas Gregordb422df2009-09-25 21:45:23 +00005497 if (!HasExplicitTemplateArgs) {
5498 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5499 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5500 Matches.clear();
Douglas Gregor48026d22010-01-11 18:40:55 +00005501
John McCallc373d482010-01-27 01:50:18 +00005502 Matches.addDecl(Method, P.getAccess());
Douglas Gregor48026d22010-01-11 18:40:55 +00005503 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5504 break;
Douglas Gregordb422df2009-09-25 21:45:23 +00005505 }
Douglas Gregord5a423b2009-09-25 18:43:00 +00005506 }
5507 }
5508
5509 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5510 if (!FunTmpl)
5511 continue;
5512
John McCall5769d612010-02-08 23:07:23 +00005513 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005514 FunctionDecl *Specialization = 0;
5515 if (TemplateDeductionResult TDK
Douglas Gregor48026d22010-01-11 18:40:55 +00005516 = DeduceTemplateArguments(FunTmpl,
John McCalld5532b62009-11-23 01:53:49 +00005517 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregord5a423b2009-09-25 18:43:00 +00005518 R, Specialization, Info)) {
5519 // FIXME: Keep track of almost-matches?
5520 (void)TDK;
5521 continue;
5522 }
5523
John McCallc373d482010-01-27 01:50:18 +00005524 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005525 }
5526
5527 // Find the most specialized function template specialization.
John McCallc373d482010-01-27 01:50:18 +00005528 UnresolvedSetIterator Result
5529 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregord5a423b2009-09-25 18:43:00 +00005530 D.getIdentifierLoc(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005531 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5532 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5533 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregord5a423b2009-09-25 18:43:00 +00005534
John McCallc373d482010-01-27 01:50:18 +00005535 if (Result == Matches.end())
Douglas Gregord5a423b2009-09-25 18:43:00 +00005536 return true;
John McCallc373d482010-01-27 01:50:18 +00005537
5538 // Ignore access control bits, we don't need them for redeclaration checking.
5539 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005540
Douglas Gregor0a897e32009-10-15 17:21:20 +00005541 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00005542 Diag(D.getIdentifierLoc(),
5543 diag::err_explicit_instantiation_member_function_not_instantiated)
5544 << Specialization
5545 << (Specialization->getTemplateSpecializationKind() ==
5546 TSK_ExplicitSpecialization);
5547 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5548 return true;
Douglas Gregor0a897e32009-10-15 17:21:20 +00005549 }
Douglas Gregor558c0322009-10-14 23:41:34 +00005550
Douglas Gregor0a897e32009-10-15 17:21:20 +00005551 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor583f33b2009-10-15 18:07:02 +00005552 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5553 PrevDecl = Specialization;
5554
Douglas Gregor0a897e32009-10-15 17:21:20 +00005555 if (PrevDecl) {
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005556 bool HasNoEffect = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00005557 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor0a897e32009-10-15 17:21:20 +00005558 PrevDecl,
5559 PrevDecl->getTemplateSpecializationKind(),
5560 PrevDecl->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005561 HasNoEffect))
Douglas Gregor0a897e32009-10-15 17:21:20 +00005562 return true;
5563
5564 // FIXME: We may still want to build some representation of this
5565 // explicit specialization.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005566 if (HasNoEffect)
John McCalld226f652010-08-21 09:40:31 +00005567 return (Decl*) 0;
Douglas Gregor0a897e32009-10-15 17:21:20 +00005568 }
Anders Carlsson26d6e9d2009-11-24 05:34:41 +00005569
5570 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor0a897e32009-10-15 17:21:20 +00005571
5572 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruth58e390e2010-08-25 08:27:02 +00005573 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
Douglas Gregor0a897e32009-10-15 17:21:20 +00005574
Douglas Gregor558c0322009-10-14 23:41:34 +00005575 // C++0x [temp.explicit]p2:
5576 // If the explicit instantiation is for a member function, a member class
5577 // or a static data member of a class template specialization, the name of
5578 // the class template specialization in the qualified-id for the member
5579 // name shall be a simple-template-id.
5580 //
5581 // C++98 has the same restriction, just worded differently.
Douglas Gregor0a897e32009-10-15 17:21:20 +00005582 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005583 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregor558c0322009-10-14 23:41:34 +00005584 D.getCXXScopeSpec().isSet() &&
5585 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5586 Diag(D.getIdentifierLoc(),
Douglas Gregora2dd8282010-06-16 16:26:47 +00005587 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00005588 << Specialization << D.getCXXScopeSpec().getRange();
5589
5590 CheckExplicitInstantiationScope(*this,
5591 FunTmpl? (NamedDecl *)FunTmpl
5592 : Specialization->getInstantiatedFromMemberFunction(),
5593 D.getIdentifierLoc(),
5594 D.getCXXScopeSpec().isSet());
5595
Douglas Gregord5a423b2009-09-25 18:43:00 +00005596 // FIXME: Create some kind of ExplicitInstantiationDecl here.
John McCalld226f652010-08-21 09:40:31 +00005597 return (Decl*) 0;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005598}
5599
John McCallf312b1e2010-08-26 23:41:50 +00005600TypeResult
John McCallc4e70192009-09-11 04:59:25 +00005601Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5602 const CXXScopeSpec &SS, IdentifierInfo *Name,
5603 SourceLocation TagLoc, SourceLocation NameLoc) {
5604 // This has to hold, because SS is expected to be defined.
5605 assert(Name && "Expected a name in a dependent tag");
5606
5607 NestedNameSpecifier *NNS
5608 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5609 if (!NNS)
5610 return true;
5611
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005612 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbar12c0ade2010-04-01 16:50:48 +00005613
Douglas Gregor48c89f42010-04-24 16:38:41 +00005614 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5615 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005616 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregor48c89f42010-04-24 16:38:41 +00005617 return true;
5618 }
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005619
5620 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
John McCallb3d87482010-08-24 05:47:05 +00005621 return ParsedType::make(Context.getDependentNameType(Kwd, NNS, Name));
John McCallc4e70192009-09-11 04:59:25 +00005622}
5623
John McCallf312b1e2010-08-26 23:41:50 +00005624TypeResult
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005625Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5626 const CXXScopeSpec &SS, const IdentifierInfo &II,
5627 SourceLocation IdLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00005628 NestedNameSpecifier *NNS
Douglas Gregord57959a2009-03-27 23:10:48 +00005629 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5630 if (!NNS)
5631 return true;
5632
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005633 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5634 !getLangOptions().CPlusPlus0x)
5635 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5636 << FixItHint::CreateRemoval(TypenameLoc);
5637
Douglas Gregor107de902010-04-24 15:35:55 +00005638 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005639 TypenameLoc, SS.getRange(), IdLoc);
Douglas Gregor31a19b62009-04-01 21:51:26 +00005640 if (T.isNull())
5641 return true;
John McCall63b43852010-04-29 23:50:39 +00005642
5643 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5644 if (isa<DependentNameType>(T)) {
5645 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCall4e449832010-05-28 23:32:21 +00005646 TL.setKeywordLoc(TypenameLoc);
5647 TL.setQualifierRange(SS.getRange());
5648 TL.setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00005649 } else {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005650 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCall4e449832010-05-28 23:32:21 +00005651 TL.setKeywordLoc(TypenameLoc);
5652 TL.setQualifierRange(SS.getRange());
5653 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00005654 }
5655
John McCallb3d87482010-08-24 05:47:05 +00005656 return CreateParsedType(T, TSI);
Douglas Gregord57959a2009-03-27 23:10:48 +00005657}
5658
John McCallf312b1e2010-08-26 23:41:50 +00005659TypeResult
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005660Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5661 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
John McCallb3d87482010-08-24 05:47:05 +00005662 ParsedType Ty) {
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005663 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5664 !getLangOptions().CPlusPlus0x)
5665 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5666 << FixItHint::CreateRemoval(TypenameLoc);
5667
John McCall4e449832010-05-28 23:32:21 +00005668 TypeSourceInfo *InnerTSI = 0;
5669 QualType T = GetTypeFromParser(Ty, &InnerTSI);
John McCall4e449832010-05-28 23:32:21 +00005670
5671 assert(isa<TemplateSpecializationType>(T) &&
5672 "Expected a template specialization type");
Douglas Gregor17343172009-04-01 00:28:59 +00005673
Douglas Gregor6946baf2009-09-02 13:05:45 +00005674 if (computeDeclContext(SS, false)) {
5675 // If we can compute a declaration context, then the "typename"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005676 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor6946baf2009-09-02 13:05:45 +00005677 // track of the nested-name-specifier.
John McCall4e449832010-05-28 23:32:21 +00005678
5679 // Push the inner type, preserving its source locations if possible.
5680 TypeLocBuilder Builder;
5681 if (InnerTSI)
5682 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5683 else
5684 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(TemplateLoc);
5685
Abramo Bagnara22f638a2010-08-10 13:46:45 +00005686 /* Note: NNS already embedded in template specialization type T. */
5687 T = Context.getElaboratedType(ETK_Typename, /*NNS=*/0, T);
John McCall4e449832010-05-28 23:32:21 +00005688 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5689 TL.setKeywordLoc(TypenameLoc);
5690 TL.setQualifierRange(SS.getRange());
5691
5692 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
John McCallb3d87482010-08-24 05:47:05 +00005693 return CreateParsedType(T, TSI);
Douglas Gregor6946baf2009-09-02 13:05:45 +00005694 }
Mike Stump1eb44332009-09-09 15:08:12 +00005695
John McCall33500952010-06-11 00:33:02 +00005696 // TODO: it's really silly that we make a template specialization
5697 // type earlier only to drop it again here.
5698 TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
5699 DependentTemplateName *DTN =
5700 TST->getTemplateName().getAsDependentTemplateName();
5701 assert(DTN && "dependent template has non-dependent name?");
Abramo Bagnara22f638a2010-08-10 13:46:45 +00005702 assert(DTN->getQualifier()
5703 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
5704 T = Context.getDependentTemplateSpecializationType(ETK_Typename,
5705 DTN->getQualifier(),
John McCall33500952010-06-11 00:33:02 +00005706 DTN->getIdentifier(),
5707 TST->getNumArgs(),
5708 TST->getArgs());
John McCall63b43852010-04-29 23:50:39 +00005709 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
John McCall33500952010-06-11 00:33:02 +00005710 DependentTemplateSpecializationTypeLoc TL =
5711 cast<DependentTemplateSpecializationTypeLoc>(TSI->getTypeLoc());
5712 if (InnerTSI) {
5713 TemplateSpecializationTypeLoc TSTL =
5714 cast<TemplateSpecializationTypeLoc>(InnerTSI->getTypeLoc());
5715 TL.setLAngleLoc(TSTL.getLAngleLoc());
5716 TL.setRAngleLoc(TSTL.getRAngleLoc());
5717 for (unsigned I = 0, E = TST->getNumArgs(); I != E; ++I)
5718 TL.setArgLocInfo(I, TSTL.getArgLocInfo(I));
5719 } else {
5720 TL.initializeLocal(SourceLocation());
5721 }
John McCall4e449832010-05-28 23:32:21 +00005722 TL.setKeywordLoc(TypenameLoc);
5723 TL.setQualifierRange(SS.getRange());
John McCallb3d87482010-08-24 05:47:05 +00005724 return CreateParsedType(T, TSI);
Douglas Gregor17343172009-04-01 00:28:59 +00005725}
5726
Douglas Gregord57959a2009-03-27 23:10:48 +00005727/// \brief Build the type that describes a C++ typename specifier,
5728/// e.g., "typename T::type".
5729QualType
Douglas Gregor107de902010-04-24 15:35:55 +00005730Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5731 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005732 SourceLocation KeywordLoc, SourceRange NNSRange,
5733 SourceLocation IILoc) {
John McCall77bb1aa2010-05-01 00:40:08 +00005734 CXXScopeSpec SS;
5735 SS.setScopeRep(NNS);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005736 SS.setRange(NNSRange);
Douglas Gregord57959a2009-03-27 23:10:48 +00005737
John McCall77bb1aa2010-05-01 00:40:08 +00005738 DeclContext *Ctx = computeDeclContext(SS);
5739 if (!Ctx) {
5740 // If the nested-name-specifier is dependent and couldn't be
5741 // resolved to a type, build a typename type.
5742 assert(NNS->isDependent());
5743 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor42af25f2009-05-11 19:58:34 +00005744 }
Douglas Gregord57959a2009-03-27 23:10:48 +00005745
John McCall77bb1aa2010-05-01 00:40:08 +00005746 // If the nested-name-specifier refers to the current instantiation,
5747 // the "typename" keyword itself is superfluous. In C++03, the
5748 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5749 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregor732281d2010-06-14 22:07:54 +00005750 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregor42af25f2009-05-11 19:58:34 +00005751
John McCall77bb1aa2010-05-01 00:40:08 +00005752 if (RequireCompleteDeclContext(SS, Ctx))
5753 return QualType();
Douglas Gregord57959a2009-03-27 23:10:48 +00005754
5755 DeclarationName Name(&II);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005756 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCalla24dc2e2009-11-17 02:14:36 +00005757 LookupQualifiedName(Result, Ctx);
Douglas Gregord57959a2009-03-27 23:10:48 +00005758 unsigned DiagID = 0;
5759 Decl *Referenced = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005760 switch (Result.getResultKind()) {
Douglas Gregord57959a2009-03-27 23:10:48 +00005761 case LookupResult::NotFound:
Douglas Gregor3f093272009-10-13 21:16:44 +00005762 DiagID = diag::err_typename_nested_not_found;
Douglas Gregord57959a2009-03-27 23:10:48 +00005763 break;
Douglas Gregord9545042010-12-09 00:06:27 +00005764
5765 case LookupResult::FoundUnresolvedValue: {
5766 // We found a using declaration that is a value. Most likely, the using
5767 // declaration itself is meant to have the 'typename' keyword.
5768 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5769 IILoc);
5770 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
5771 << Name << Ctx << FullRange;
5772 if (UnresolvedUsingValueDecl *Using
5773 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
5774 SourceLocation Loc = Using->getTargetNestedNameRange().getBegin();
5775 Diag(Loc, diag::note_using_value_decl_missing_typename)
5776 << FixItHint::CreateInsertion(Loc, "typename ");
5777 }
5778 }
5779 // Fall through to create a dependent typename type, from which we can recover
5780 // better.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00005781
5782 case LookupResult::NotFoundInCurrentInstantiation:
5783 // Okay, it's a member of an unknown instantiation.
Douglas Gregor107de902010-04-24 15:35:55 +00005784 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregord57959a2009-03-27 23:10:48 +00005785
5786 case LookupResult::Found:
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005787 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005788 // We found a type. Build an ElaboratedType, since the
5789 // typename-specifier was just sugar.
5790 return Context.getElaboratedType(ETK_Typename, NNS,
5791 Context.getTypeDeclType(Type));
Douglas Gregord57959a2009-03-27 23:10:48 +00005792 }
5793
5794 DiagID = diag::err_typename_nested_not_type;
John McCallf36e02d2009-10-09 21:13:30 +00005795 Referenced = Result.getFoundDecl();
Douglas Gregord57959a2009-03-27 23:10:48 +00005796 break;
5797
Douglas Gregord9545042010-12-09 00:06:27 +00005798
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005799 llvm_unreachable("unresolved using decl in non-dependent context");
John McCall7ba107a2009-11-18 02:36:19 +00005800 return QualType();
5801
Douglas Gregord57959a2009-03-27 23:10:48 +00005802 case LookupResult::FoundOverloaded:
5803 DiagID = diag::err_typename_nested_not_type;
5804 Referenced = *Result.begin();
5805 break;
5806
John McCall6e247262009-10-10 05:48:19 +00005807 case LookupResult::Ambiguous:
Douglas Gregord57959a2009-03-27 23:10:48 +00005808 return QualType();
5809 }
5810
5811 // If we get here, it's because name lookup did not find a
5812 // type. Emit an appropriate diagnostic and return an error.
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005813 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5814 IILoc);
5815 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregord57959a2009-03-27 23:10:48 +00005816 if (Referenced)
5817 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5818 << Name;
5819 return QualType();
5820}
Douglas Gregor4a959d82009-08-06 16:20:37 +00005821
5822namespace {
5823 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer85b45212009-11-28 19:45:26 +00005824 class CurrentInstantiationRebuilder
Mike Stump1eb44332009-09-09 15:08:12 +00005825 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor4a959d82009-08-06 16:20:37 +00005826 SourceLocation Loc;
5827 DeclarationName Entity;
Mike Stump1eb44332009-09-09 15:08:12 +00005828
Douglas Gregor4a959d82009-08-06 16:20:37 +00005829 public:
Douglas Gregor895162d2010-04-30 18:55:50 +00005830 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5831
Mike Stump1eb44332009-09-09 15:08:12 +00005832 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor4a959d82009-08-06 16:20:37 +00005833 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00005834 DeclarationName Entity)
5835 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor4a959d82009-08-06 16:20:37 +00005836 Loc(Loc), Entity(Entity) { }
Mike Stump1eb44332009-09-09 15:08:12 +00005837
5838 /// \brief Determine whether the given type \p T has already been
Douglas Gregor4a959d82009-08-06 16:20:37 +00005839 /// transformed.
5840 ///
5841 /// For the purposes of type reconstruction, a type has already been
5842 /// transformed if it is NULL or if it is not dependent.
5843 bool AlreadyTransformed(QualType T) {
5844 return T.isNull() || !T->isDependentType();
5845 }
Mike Stump1eb44332009-09-09 15:08:12 +00005846
5847 /// \brief Returns the location of the entity whose type is being
Douglas Gregor4a959d82009-08-06 16:20:37 +00005848 /// rebuilt.
5849 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +00005850
Douglas Gregor4a959d82009-08-06 16:20:37 +00005851 /// \brief Returns the name of the entity whose type is being rebuilt.
5852 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +00005853
Douglas Gregor972e6ce2009-10-27 06:26:26 +00005854 /// \brief Sets the "base" location and entity when that
5855 /// information is known based on another transformation.
5856 void setBase(SourceLocation Loc, DeclarationName Entity) {
5857 this->Loc = Loc;
5858 this->Entity = Entity;
5859 }
Douglas Gregor4a959d82009-08-06 16:20:37 +00005860 };
5861}
5862
Douglas Gregor4a959d82009-08-06 16:20:37 +00005863/// \brief Rebuilds a type within the context of the current instantiation.
5864///
Mike Stump1eb44332009-09-09 15:08:12 +00005865/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor4a959d82009-08-06 16:20:37 +00005866/// a class template (or class template partial specialization) that was parsed
Mike Stump1eb44332009-09-09 15:08:12 +00005867/// and constructed before we entered the scope of the class template (or
Douglas Gregor4a959d82009-08-06 16:20:37 +00005868/// partial specialization thereof). This routine will rebuild that type now
5869/// that we have entered the declarator's scope, which may produce different
5870/// canonical types, e.g.,
5871///
5872/// \code
5873/// template<typename T>
5874/// struct X {
5875/// typedef T* pointer;
5876/// pointer data();
5877/// };
5878///
5879/// template<typename T>
5880/// typename X<T>::pointer X<T>::data() { ... }
5881/// \endcode
5882///
Douglas Gregor4714c122010-03-31 17:34:00 +00005883/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor4a959d82009-08-06 16:20:37 +00005884/// since we do not know that we can look into X<T> when we parsed the type.
5885/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005886/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor4a959d82009-08-06 16:20:37 +00005887/// as the canonical type of T*, allowing the return types of the out-of-line
5888/// definition and the declaration to match.
John McCall63b43852010-04-29 23:50:39 +00005889TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5890 SourceLocation Loc,
5891 DeclarationName Name) {
5892 if (!T || !T->getType()->isDependentType())
Douglas Gregor4a959d82009-08-06 16:20:37 +00005893 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00005894
Douglas Gregor4a959d82009-08-06 16:20:37 +00005895 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5896 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00005897}
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005898
John McCall60d7b3a2010-08-24 06:29:42 +00005899ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallb3d87482010-08-24 05:47:05 +00005900 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
5901 DeclarationName());
5902 return Rebuilder.TransformExpr(E);
5903}
5904
John McCall63b43852010-04-29 23:50:39 +00005905bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
5906 if (SS.isInvalid()) return true;
John McCall31f17ec2010-04-27 00:57:59 +00005907
5908 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5909 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
5910 DeclarationName());
5911 NestedNameSpecifier *Rebuilt =
5912 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall63b43852010-04-29 23:50:39 +00005913 if (!Rebuilt) return true;
5914
5915 SS.setScopeRep(Rebuilt);
5916 return false;
John McCall31f17ec2010-04-27 00:57:59 +00005917}
5918
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005919/// \brief Produces a formatted string that describes the binding of
5920/// template parameters to template arguments.
5921std::string
5922Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5923 const TemplateArgumentList &Args) {
Douglas Gregor910f8002010-11-07 23:05:16 +00005924 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005925}
5926
5927std::string
5928Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5929 const TemplateArgument *Args,
5930 unsigned NumArgs) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005931 std::string Result;
5932
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005933 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005934 return Result;
5935
5936 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005937 if (I >= NumArgs)
5938 break;
5939
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005940 if (I == 0)
5941 Result += "[with ";
5942 else
5943 Result += ", ";
5944
5945 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5946 Result += Id->getName();
5947 } else {
5948 Result += '$';
5949 Result += llvm::utostr(I);
5950 }
5951
5952 Result += " = ";
5953
5954 switch (Args[I].getKind()) {
5955 case TemplateArgument::Null:
5956 Result += "<no value>";
5957 break;
5958
5959 case TemplateArgument::Type: {
5960 std::string TypeStr;
5961 Args[I].getAsType().getAsStringInternal(TypeStr,
5962 Context.PrintingPolicy);
5963 Result += TypeStr;
5964 break;
5965 }
5966
5967 case TemplateArgument::Declaration: {
5968 bool Unnamed = true;
5969 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5970 if (ND->getDeclName()) {
5971 Unnamed = false;
5972 Result += ND->getNameAsString();
5973 }
5974 }
5975
5976 if (Unnamed) {
5977 Result += "<anonymous>";
5978 }
5979 break;
5980 }
5981
Douglas Gregor788cd062009-11-11 01:00:40 +00005982 case TemplateArgument::Template: {
5983 std::string Str;
5984 llvm::raw_string_ostream OS(Str);
5985 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5986 Result += OS.str();
5987 break;
5988 }
5989
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005990 case TemplateArgument::Integral: {
5991 Result += Args[I].getAsIntegral()->toString(10);
5992 break;
5993 }
5994
5995 case TemplateArgument::Expression: {
Douglas Gregor77e2c672010-04-29 04:55:13 +00005996 // FIXME: This is non-optimal, since we're regurgitating the
5997 // expression we were given.
5998 std::string Str;
5999 {
6000 llvm::raw_string_ostream OS(Str);
6001 Args[I].getAsExpr()->printPretty(OS, Context, 0,
6002 Context.PrintingPolicy);
6003 }
6004 Result += Str;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006005 break;
6006 }
6007
6008 case TemplateArgument::Pack:
6009 // FIXME: Format template argument packs
6010 Result += "<template argument pack>";
6011 break;
6012 }
6013 }
6014
6015 Result += ']';
6016 return Result;
6017}
Douglas Gregord0937222010-12-13 22:49:22 +00006018